Compare commits

..

903 Commits

Author SHA1 Message Date
Dylan Conway
d8b5176cc0 fix 2023-09-12 21:27:30 -07:00
Dylan Conway
ec251863d1 track registered one shot fds 2023-09-12 20:47:14 -07:00
Dylan Conway
85bf54a3ac Merge branch 'main' into dylan/cli-fixes 2023-09-11 20:38:47 -07:00
Colin McDonnell
03b8e9d5cf fix formatting in sveltekit guide 2023-09-11 20:12:48 -07:00
Dylan Conway
58d5771589 Merge branch 'main' into dylan/cli-fixes 2023-09-11 18:21:14 -07:00
Dylan Conway
5884a5cec2 make sure epoll is deleted 2023-09-11 18:18:25 -07:00
Ai Hoshino
f267c1d097 fix(path): Fix edge case in path.relative (#4811)
Close: #4789
2023-09-11 17:53:43 -07:00
Ai Hoshino
c4507a5db3 Fix Buffer.from to handle double-byte hex encoding strings (#4933)
Close: #4919
2023-09-11 17:27:12 -07:00
Ciro Spaciari
c9a0ea96cd fix(BunFile) .slice offset on macOS (#4991)
* fix offset

* simplify error
2023-09-11 17:19:43 -07:00
Dylan Conway
ca461f9e83 fix loading env from .env.production and friends (#4630)
* reload conditional vars

* test

* change `get` and `put` methods

* dont clone empty env variables
2023-09-11 17:19:21 -07:00
Colin McDonnell
9c4765f616 Update benchmark readme 2023-09-11 16:53:34 -07:00
Justin "J.R." Hill
e091290748 fix(bun-lambda): Don't drop arguments in console.log(...) (#4992)
Closes #4826
2023-09-11 12:39:56 -07:00
Dylan Conway
00be978c3a delete on rearm 2023-09-11 12:10:19 -07:00
Dylan Conway
bd359df23c Merge branch 'main' into dylan/cli-fixes 2023-09-11 12:02:02 -07:00
Ben Jervis
350403663e Fix error message typo in js_ast.zig (#4937) 2023-09-11 11:03:45 -07:00
Dylan Conway
895f3824b5 update test 2023-09-11 10:43:33 -07:00
Diogo Goncalves
58e69ef9f4 Remove unnecessary backticks in quickstart doc page (#4927) 2023-09-11 08:54:22 -07:00
Vladimir Pesterev
decad91d24 Fixed inconsistent log messages in the Quickstart guide (#4942)
Looks like it is just a typo and needs to be fixed.

Signed-off-by: Vladimir Pesterev <8786922+pesterev@users.noreply.github.com>
2023-09-11 08:53:54 -07:00
Yonathan Benolol
ea56182c5a Update http.js - Fix Methods Fallback naming (#4948) 2023-09-11 08:51:35 -07:00
Matthew Yu
9d6a8ee79d Fix punctuation (#4870) 2023-09-11 08:50:39 -07:00
fehnomenal
b55b511f68 Make detect-libc package match the upstream api (#4910) 2023-09-11 08:49:57 -07:00
Krzysztof Szala
49b9306dce fix: changes wrong command name in the tests chapter (#4965)
This PR fixes the command name for running tests flagged with `.only`
2023-09-11 08:48:53 -07:00
Krystian Pracuk
2956ed4289 added .idea to .gitignore (#4951) 2023-09-11 08:48:26 -07:00
Jarred Sumner
51d3d43822 Support named imports for json & toml files at runtime (#4783)
* Support named exports in json imports

* Support named imports for `*.json` files

* Remove stale comments

* Don't export arrays as non-default

* Add test for default exports

* Don't break webpack

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-09-10 23:15:35 -07:00
Jarred Sumner
edea4f095a Fixes #4588 (#4804)
* Fixes #4588

* typo

* fixup

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-09-10 21:40:46 -07:00
Diogo Goncalves
07c88435e0 Replace unnecessary '' wih "` in code snippets (#4792) 2023-09-10 11:34:04 -07:00
Jeroen van Rensen
7121c1d6ab Update modules.md - Explain case-insensitivity (#4782) 2023-09-10 11:33:39 -07:00
Ed Knowles
60dc76676c docs: remove duplicate sentence from debugger (#4807) 2023-09-10 11:33:04 -07:00
toneyzhen
f64b504bae Update todo-tests.md (#4771) 2023-09-10 11:32:31 -07:00
Vyacheslav Kulik
97153c5a5f Add compatibility page link to index.md (#4809)
Add a link to compatibility page (https://bun.sh/docs/runtime/nodejs-apis) to its reference in index.md, so it's easier to reach out to.
2023-09-10 11:30:46 -07:00
Tom Sherman
d48ff53e4e docs: Update Bun.write(path, Response) example to be clear that it writes the body (#4802) 2023-09-10 05:06:25 -07:00
WingLim
afcbed218c fix(bindings): add missing binding (#4682) 2023-09-10 02:58:10 -07:00
Rinku Chaudhari
682406c42c docs: fix spelling (#4763) 2023-09-09 22:40:56 -07:00
Richard
6fe40f383a Fix mongoose ecosystem guid (#4740)
Fix missing method declaration on schema and Schema database name from Kitten to Animal
2023-09-09 19:05:13 -07:00
thunfisch987
e2d327881c fix(docs); typo on Nuxt guide page (#4745) 2023-09-09 19:04:05 -07:00
Robert Soriano
4280f74429 docs: fix wasi-js link (#4741) 2023-09-09 19:03:46 -07:00
Chris Hutchinson
8139a20c9f fix: remove from bun-server.test.ts test case (#4709) 2023-09-09 19:03:28 -07:00
akumarujon
620f6c51ce fix typo (#4639) 2023-09-09 14:46:41 -07:00
Ashcon Partovi
ffe4f561a3 Fix listen() using unix socket if argument is a valid port (#4620)
* Fix listen() using unix socket if argument is a valid port

Fixes #4582

* Add test
2023-09-08 16:27:44 -07:00
Ana Margarida Silva
c896792c37 fix(docs): connect websocket client repeated documentation (#4615) 2023-09-08 14:22:28 -07:00
Colin McDonnell
088491cb59 Add extension guide 2023-09-08 13:49:12 -07:00
xxxhussein
f27ef667c7 Delete docs/ecosystem/buchta.md (#4536)
Delete buchta.md since its development is discontinued by LowByteFox: https://twitter.com/LowByteFox/status/1694025965452636612
2023-09-08 13:21:41 -07:00
Arjunkumar
7d9820d478 Update mongoose.md (#4534) 2023-09-08 13:20:07 -07:00
Ethan Steere
b5da5168bf Update Svelte Kit Docs (#4541)
* Update Svelte Kit Docs

I added some guidance about how to build for production. Still WIP since I would like to add a more complete deployment guide.

* Formatting

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2023-09-08 13:19:53 -07:00
rajatdua
61569fab80 docs(template.md): spelling (#4614) 2023-09-08 13:19:33 -07:00
Frederik De Bleser
0887825f54 Fix code typo in transpiler.md (#4604)
There are some extra closing brackets at the end of the `scanImports` example. These cause a syntax error ("Unterminated string literal")
2023-09-08 12:10:17 -07:00
Colin McDonnell
6d02b18680 Remove await plugin 2023-09-08 11:42:27 -07:00
Vitor Dino
1b8c6f266f docs: fix --backend options list on cache.md (#4599)
`symlink` wasn’t an item, it appeared the same as `copyfile`
2023-09-08 11:19:29 -07:00
Dan Fabulich
989dd92ea8 Move "Importing CJS from CJS" back out of low-level details section (#4600)
This section appears to have been accidentally moved into the low-level details section in 5424ea3403.

This fixes the example in the low-level details section, because the "Importing CJS from CJS" section is not the example code that the low-level details section is intended to provide.
2023-09-08 11:18:52 -07:00
Colin McDonnell
9e3cabc540 Remove community-templates 2023-09-08 10:55:16 -07:00
Ondrej Brablc
3170cf08ba Make the link to application clickable in the terminal (#4544)
Terminals like iTerm require valid URL to make them clickable. Adding a space to make it valid. Similar problem is on https://bun.sh/, where protocol is missing.
2023-09-08 09:33:35 -07:00
Samual Norman
182d3f1567 Fix Bun.CryptoHasher missing argument in docs (#4585) 2023-09-08 09:32:36 -07:00
Tiramify (A.K. Daniel)
189f0f7c36 Update development.md (#4578) 2023-09-08 09:32:15 -07:00
Ashcon Partovi
a05a1780c1 Fix bun-types 2023-09-08 08:29:59 -07:00
Jarred Sumner
822a00c4d5 Fix a couple important bugs (#4560) 2023-09-07 21:07:00 -08:00
Adam
f6a621f36a Fix typo in sveltekit.md (#4550) 2023-09-07 13:11:09 -07:00
dave caruso
5b9d8b87c4 Bump version to Bun 1.0.0 (#4543)
* hi

* Update Version to 1.0.0

* 2

---------

Co-authored-by: Dylan Conway <35280289+dylan-conway@users.noreply.github.com>
2023-09-07 10:57:46 -07:00
Colin McDonnell
a7c3bc8a5a Fix markdown 2023-09-07 10:12:52 -07:00
Colin McDonnell
5424ea3403 Doc updates for v1.0 (#4485)
* Remove v0.x messages

* Add windows section to Installatino

* update

* update

* Update

* Comment out windows
2023-09-07 10:09:09 -07:00
dave caruso
4b63ced72d fix(cli): final touches for 1.0 (#4538)
* better

* cli

* remove submodule

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-09-07 09:04:21 -07:00
Ciro Spaciari
c8883a39a5 fix(fetch) closeAndFail instead of close (#4537)
* closeAndFail instead of close

* use constant

* add some protection

* dont deinit

---------

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-09-07 08:34:13 -07:00
dave caruso
36e5a072a9 revert (#4539)
* Revert "remove native events from streams"

This reverts commit e063a47a53.

* finish revert

* remove accidental submodule

* dfghj
2023-09-07 07:45:00 -07:00
dave caruso
57a06745a4 Progress for Next.js (#4468)
* L

* ipc

* asdfghjkl

* dfghjk

* it works!

* types

* patches for next.js

* sdfghj

* wsdfgn,./

* this

* yolo

* okay loser

* asdfghjk

* add some more APIs

* MESS

* sdfghjkl

* remove native events from streams

* stuff

* remove lazy(primordials) test

* debugging

* okay

* less fake extensions object

* fix `Buffer.toString()` args logic

* fix deserialize

* make tests work

* add test for `Buffer.toString` args

* Update server.zig

* remove test

* update test

* Update spawn-streaming-stdin.test.ts

* fix linux build

* Update fs.test.ts

* cli message improvements

* dfshaj

* Fix fs.watch bug maybe?

* remove

---------

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
2023-09-07 04:58:44 -07:00
Ciro Spaciari
4360ec83b4 feat(fetch) rejectUnauthorized and checkServerIdentity (#4514)
* enable root certs on fetch

* rebase

* fix lookup

* some fixes and improvements

* fmt

* more fixes

* more fixes

* check detached onHandshake

* fix promise case

* fix cert non-Native

* add fetch tls tests

* more one test
2023-09-06 22:23:24 -07:00
Birk Skyum
3b9829f171 Update nodejs compat docs cp/cpSync/watchFile/unwatchFile (#4525) 2023-09-06 14:04:07 -07:00
Ashcon Partovi
849a2cdfae Add bun-types to 'bun fmt' script 2023-09-06 10:03:12 -07:00
Ashcon Partovi
77f1f2480d Add types for watchFile and unwatchFile 2023-09-06 10:02:48 -07:00
Ashcon Partovi
5e074209c6 Add types for cp and cpSync 2023-09-06 09:58:00 -07:00
Ashcon Partovi
0c2675c8d3 Remove issue template for install
It's not used, and use the bug issue instead.
2023-09-06 09:37:39 -07:00
dave caruso
a79440f0c3 fix(runtime): fix events.once not working (#4520) 2023-09-06 07:13:05 -07:00
Dylan Conway
daaac7792c allocate task for ThreadSafeFunction (#4513)
* create thread safe function task

* Update napi.zig

* Update napi.zig
2023-09-06 02:04:00 -07:00
Derrick Farris
7c82dc86ba Update development.md (#4480)
Remove comment about removed `BUN_OVERRIDE_MODULE_PATH` env var
2023-09-05 20:28:39 -07:00
Ciro Spaciari
125880af7d update root certs (#4499) 2023-09-05 20:28:20 -07:00
Dylan Conway
70a5cfe908 fix text decode trim (#4495)
* remove trim

* separate function

* a test

* trim when `stream` is true

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-09-05 17:53:31 -07:00
Jarred Sumner
1bd5b245b8 Align process.nextTick execution order with Node (#4409)
* Align `process.nextTick` execution order with Node

* some tests

* formatting

* fixups

* fix the test failures

* simplify the logic here

* push it up

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: dave caruso <me@paperdave.net>
2023-09-05 17:52:57 -07:00
dave caruso
acfd028e8f feat(runtime): Implement fs.watchFile (#4467)
* really lame prototype

* uses threads but badly

* it works i guess

* unwatchFile but lame

* it works

* test

* a

* aomitcs

* fix unwatching race condition

* use hasPendingActivity and GC stuff better

* test

* revert this
2023-09-05 17:41:39 -07:00
dave caruso
6f8a393492 fix(node:net): emit close event on connection error (#4336)
* emit close event on connection error

* re-review

* add test
2023-09-05 16:59:40 -07:00
Ciro Spaciari
6e50dd210f fix(fetch) always use readable stream if it is available (#4503)
* always use readable stream if it is available

* use bun sleep

* fix tests

* rm uws dep
2023-09-05 15:22:09 -07:00
Ciro Spaciari
d268097ded fix SSL proxy tunneling on fetch (#4510) 2023-09-05 15:21:34 -07:00
dave caruso
1e998c1bf2 fix(install): ensure all lockfile structs do not have undefined padding (#4401)
* padding sucks

* this assertion is already done elsewhere

* remove test. will be covered alex's pr i believe?

* fix webkit submodule

* fix uws submodule
2023-09-05 14:25:19 -07:00
Alex Lam S.L
bc2b55fdee fix checkout/build failure due to src/deps/uws (#4505) 2023-09-05 19:16:11 +03:00
Dylan Conway
7dae4db52a fix ipv6 localhost fetch (#4498)
* `node` null for localhost getaddrinfo

* more test
2023-09-05 06:12:54 -07:00
Alex Lam S.L
bcab2f9a0e minor rebuild diffs (#4486) 2023-09-05 14:49:07 +03:00
Jason
a85bd5d083 fix dup syscall on Windows (#4496) 2023-09-05 01:33:30 -07:00
Dylan Conway
f73f77d0de no need to chmod (#4490) 2023-09-04 17:16:37 -08:00
Ciro Spaciari
f1afd58338 fix zlib deflate on fetch (#4483)
* fix zlib deflate on fetch

* mention issue on test

* more tests

* oops
2023-09-04 17:37:47 -07:00
Ai Hoshino
5f34c44ec6 chore: fix typo (#4476)
Close: #4377
2023-09-04 12:35:08 -07:00
Ciro Spaciari
2d80f94eda fix(HTMLRewriter) buffer response before transform (#4418)
* html rewriter response buffering

* pipe the data when marked as used

* fix empty response

* add some fetch tests

* deinit parent stream

* fix decompression

* keep byte_reader alive

* update builds

* remove nonsense

* was not nonsense after all

* protect tmp ret value from GC, fix readable strong ref deinit/init

* fmt

* if we detach the stream we cannot update the fetch stream

* detach checking source

* more tests, progress with javascript and Direct sink

* drop support for pure readable stream for now

* more fixes

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-09-04 12:26:49 -07:00
Dylan Conway
6bc5098e7e eof and check for undefined 2023-09-03 22:56:25 -07:00
Dylan Conway
18767906db initialize JSC for macros from cli 2023-09-03 20:49:06 -07:00
Ai Hoshino
f1b109d5dd fix(syscall): fix handling syscall errno (#4461)
* fix(syscall): fix handling syscall errno
Close: #4198

* remove unused code

* add more tests

* remove unused code
2023-09-03 17:30:30 -07:00
dave caruso
5c43744bce workaround a zig bug (#4440) 2023-09-02 01:39:39 -07:00
Karl Böhlmark
db2faf7c5b docs: fix http simple example log statement (#4320)
Co-authored-by: Karl Böhlmark <karl.bohlmark@netinsight.net>
2023-09-01 23:49:50 -07:00
Jorge Jiménez
bd690bb2b5 Fix typo (#4445)
Replace
`key: [Bun.file('./key1.pem'), Bun.file('./key2.pem']`
with
`key: [Bun.file('./key1.pem'), Bun.file('./key2.pem')]`
2023-09-01 23:49:09 -07:00
Dylan Conway
900f38d144 keep export star as (#4451) 2023-09-01 22:32:27 -07:00
Colin McDonnell
4920f458bc bun-vscode 0.0.8 2023-09-01 22:16:54 -07:00
Colin McDonnell
48cf9dddcb Update commands 2023-09-01 21:35:34 -07:00
Dylan Conway
0019073c8a fix Bun.serve with tls and Bun.file (#4450)
* check sendfile ctx

* add test

* undo blob check

* undo undo and add assert
2023-09-01 20:10:54 -07:00
Dylan Conway
45edb7bcf7 exclusive max 2023-09-01 20:09:45 -07:00
Ashcon Partovi
f0f91a2a31 Fix debug console from appears on start 2023-09-01 19:34:57 -07:00
Ashcon Partovi
94a4cda713 Add configuration options to extension 2023-09-01 18:56:25 -07:00
Ashcon Partovi
eeb683d977 Fix run button starting cwd at / 2023-09-01 15:35:14 -07:00
dave caruso
0fd0ad993b fix(runtime): fix dns_resolver crash (#4435)
* fix incorrect c pointer

* format

* lets go

* random other test case fixed

* hanassagi patch

* Update dns_resolver.zig

* Revert "Update dns_resolver.zig"

This reverts commit 53eb338048.

* See if the tests pass

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-09-01 15:27:59 -07:00
Ashcon Partovi
27de8bbf7b Fix background color 2023-09-01 13:55:19 -07:00
Ashcon Partovi
6bdf24c8ef Allow older versions of VSCode 2023-09-01 13:49:52 -07:00
Ashcon Partovi
57caea5ae7 Fix README for extension 2023-09-01 13:40:48 -07:00
Ashcon Partovi
fe3be666bc Update VSCode extension 2023-09-01 13:34:29 -07:00
Ashcon Partovi
2b421be06f Fix breakpoint on entry for extension 2023-09-01 10:19:14 -07:00
Ashcon Partovi
1ff8155c28 Add Bun.canReload event to inspector 2023-09-01 00:33:33 -07:00
Ashcon Partovi
40d749b480 JavaScript Debug Terminal == Bun Terminal 2023-08-31 23:19:04 -07:00
dave caruso
5288178c86 fix(runtime): fs.cp edge cases (#4439)
* yippee

* enable cpSync tests

* much better

* that doesnt actually do anything

* lose
2023-08-31 23:04:19 -07:00
Dylan Conway
6ae4dd808b only set initial debugger breakpoint once (#4441)
* unset `set_breakpoint_on_first_line` on reload

* move to `module_loader.zig`
2023-08-31 23:03:44 -07:00
Ashcon Partovi
b07bb3ce17 Make breakpoints faster in VSCode extension 2023-08-31 21:42:11 -07:00
Julian
59edbe645c bun install correctly join dependency URLs (#4421)
* use WTF to join registry strings

* show dependency error messages, better join error

We actually report errors when enqueuing dependencies now. I also made
the join URLs error message read better. It'd be cleaner to handle it
all in one place, but there's currently no way to propagate the data up.

* starting on registry URL tests

* added more registry URL tests

* [install] prevent optional/peer deps from failing builds

Couldn't get the peer dependency test to work, but the code is there.

* ran prettier

* changed error note to use realname, updated tests

* ran prettier again...
2023-08-31 17:36:03 -07:00
Dylan Conway
fef70f2473 get name if not provided in FormData.append (#4434)
* get file name from blob if not provided

* add test

* another test

* format
2023-08-31 17:33:08 -07:00
Ashcon Partovi
bd7262f037 Fix vscode debug terminal 2023-08-31 00:18:59 -07:00
Jarred Sumner
10c8013ef2 Create cp-r.mjs 2023-08-30 22:18:04 -07:00
Jarred Sumner
82d26dd9bd Add bench 2023-08-30 21:00:44 -07:00
Ai Hoshino
9334fbe9b4 fix(install): resolve semver matching with pre-release tags. (#4412)
Close: #4398
2023-08-30 18:49:09 -07:00
dave caruso
0a5d2a8195 feat(node:fs): add cp/cpSync/promises.cp + async copyFile (#4340)
* half working disaster code

* this

* async copyFile

* .

* its failing symlink tests

* asdfg

* asdf

* hmm

* okay i think ti works

* small edits

* fix test on linux

* i hate atomics / atomics hate me back <3

* add a message in the builtins bundler that 0.8 is needed. it breaks on older versions lol.

* fixed

* rebase
2023-08-30 18:30:06 -07:00
Dylan Conway
89f24e66ff add life cycle scripts to lockfile metahash (#4420)
* add life cycle scripts to lockfile metahash

* Update lockfile.zig
2023-08-30 18:29:08 -07:00
Alex Lam S.L
037463fc48 [install] fix stale root life-cycle script in lockfile (#4411)
fixes #4319
2023-08-30 17:35:28 -07:00
Dylan Conway
04215e2f3a reset tty at exit (#4419) 2023-08-30 16:38:25 -07:00
Alex Lam S.L
c19714aff7 minor rebuild diffs (#4416) 2023-08-30 14:48:30 -07:00
Ciro Spaciari
908018a4df fix(http/https) disable decompress on http/https client (#4399)
* disable decompress on http/https module

* make js again
2023-08-30 13:50:09 -03:00
Jarred Sumner
f24ca39004 Fix bug in util/types.{isGeneratorFunction,isAsyncFunction} 2023-08-30 00:19:39 -07:00
Jarred Sumner
e3dc5b6b4c reset signal handlers in Bun.spawn (#4405)
* see if this fixes it

* We don't need this

* Remove extra flag

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-30 00:16:08 -07:00
Ashcon Partovi
f2553d2454 More support for DAP (#4380)
* Fix reconnect with --watch

* Support setVariable

* Support setExpression

* Support watch variables

* Conditional and hit breakpoints

* Support exceptionInfo

* Support goto and gotoTargets

* Support completions

* Support both a URL and UNIX inspector at the same time

* Fix url

* WIP, add timeouts to figure out issue

* Fix messages being dropped from debugger.ts

* Progress

* Fix breakpoints and ref-event-loop

* More fixes

* Fix exit

* Make hovers better

* Fix --hot
2023-08-29 23:44:39 -07:00
Jarred Sumner
c028b206bc Fix assertion failure in spawn-related tests (#4400)
* Clean up some of the event loop code

* Support timeouts

* Defer freeing FilePoll

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-29 21:17:56 -07:00
dave caruso
a846852818 fix(node-fetch): use stream.Readable instead of web streams (#4394)
* fix blobFrom

* fix(node-fetch): use stream.Readable instead of web streams

* uncomment

* comment why
2023-08-29 19:45:16 -07:00
Ai Hoshino
3f4bc625ff parse unix socket path param in http.server (#4390) 2023-08-29 19:39:12 -07:00
Jarred Sumner
5d84ef7780 Rename uws_event_loop to event_loop_handle 2023-08-29 15:31:06 -07:00
Jarred Sumner
a77ed151af [git] Normalize line endings 2023-08-29 15:30:07 -07:00
Jarred Sumner
cf151a256c Enforce unix line endings in git 2023-08-29 15:29:09 -07:00
Dylan Conway
de58e9d583 emit open and call close callback (#4384) 2023-08-29 09:44:45 -07:00
Dylan Conway
07d8623976 fix #4356 (#4386) 2023-08-29 01:49:12 -07:00
Ai Hoshino
c53372c9f3 feat(node:dns): implement dns.reverse. (#4332)
* feat(node:dns): implement `dns.reverse`.
Close: #4299

* fix dns reverse for ipv6

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-28 20:10:33 -07:00
Dylan Conway
d1c2d6b25c use options.fd if provided for fs.Read/WriteStream (#4378)
* use `options.fd` over path

* tests

* fix `@clack/prompts`

* == null
2023-08-28 20:08:08 -07:00
Colin McDonnell
a2aad40171 docs: use table tag 2023-08-28 13:05:23 -07:00
Colin McDonnell
177e02b304 docs: hot reloading with Bun.serve 2023-08-28 12:55:22 -07:00
Colin McDonnell
726f8aa3ef Update nuxi output 2023-08-28 12:24:51 -07:00
Prabhat Sachdeva
d3626287bd remove uws from .gitmodules (#4374) 2023-08-28 10:39:45 -07:00
Jarred Sumner
a2ddfe6913 Bring uSockets & uWebSockets forks into Bun's repository (#4372)
* Move uWebSockets and uSockets forks into Bun's repository

* Update Makefile

* Update settings.json

* Update libuwsockets.cpp

* Remove backends we won't be using

* Update bindings.cpp

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-28 08:38:30 -07:00
Ciro Spaciari
6e4a1f2918 make pending_response and metdata life cycle more clear and make fetch more reliable (#4331)
* make pending_response and metdata life cycle more clear

* typo

* WIP: memory investigation

* check zlib and fix zlib

* use state allocator for metadata

* remove postBodyProcess

* undo some test things

* fix race condition

* fix removing compressed header

* some extra checks

* remove arenas on zlib and comment repoter.assert because of toOwnedSliceZ

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-28 07:21:46 -07:00
Jarred Sumner
ebfaa682f7 More renaming 2023-08-28 04:53:51 -07:00
Jarred Sumner
277e5c0b77 mv src/bun.js/node/syscall.zig -> src/sys.zig 2023-08-28 04:53:18 -07:00
Jarred Sumner
e2a17344dc just kernel32 things (#4354)
* just kernel32 things

* more

* Update linux_c.zig

* Update windows_c.zig

* Add workaround

Workaround https://github.com/ziglang/zig/issues/16980

* Rename http.zig to bun_dev_http_server.zig

* Rename usages

* more

* more

* more

* thanks tigerbeetle

* Rename `JSC.Node.Syscall` -> `bun.sys`

* more

* woops

* more!

* hmm

* it says there are only 37 errors, but that's not true

* populate argv

* it says 32 errors!

* 24 errors

* fix regular build

* 12 left!

* Still 12 left!

* more

* 2 errors left...

* 1 more error

* Add link to Tigerbeetle

* Fix the remainign error

* Fix test timeout

* Update syscall.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-28 04:39:16 -07:00
Ai Hoshino
efe987e8d1 Fix some edge cases in the env param of spawn. (#4364)
Close: #4362
2023-08-27 23:58:31 -07:00
Jarred Sumner
ed5dc5bbf9 @electroid's dap changes (#4367)
* Rework terminal, launch is still WIP

* Use the proper Terminal profile API

* More changes

* progress

---------

Co-authored-by: Ashcon Partovi <ashcon@partovi.net>
2023-08-27 09:03:15 -07:00
Jarred Sumner
36f9d2291c Workaround zig wasm bug 2023-08-26 21:09:08 -07:00
Jarred Sumner
9e653e610c Update WebKit 2023-08-26 03:10:16 -07:00
Jarred Sumner
f16d729c76 Set the timezone in spawn (#4337)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-26 02:35:10 -07:00
Ashcon Partovi
2a9e967fd1 More improvements to debugger support (#4345)
* More fixes for dap

* More changes

* More changes 2

* More fixes

* Fix debugger.ts

* Bun Terminal
2023-08-26 02:34:25 -07:00
Ai Hoshino
910daeff27 Fix the crash when importing a module that does not exist. (#4348)
Close: #4240
2023-08-26 01:14:40 -07:00
Jarred Sumner
e1dacf88d0 don't get too excited but there are at least hundreds of compiler errors when you run this command 2023-08-25 22:05:02 -07:00
Jarred Sumner
d72763dc29 bump! 2023-08-25 21:54:16 -07:00
Jarred Sumner
d98a93c318 Automatically hot reload Bun.serve() (#4344)
* Automatically hot reload Bun.serve()

* Update doc

* Update example

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-25 21:08:41 -07:00
Colin McDonnell
f70bb2497b Fix link 2023-08-25 12:50:13 -07:00
Colin McDonnell
d62b0c3652 Readability tweaks 2023-08-25 12:47:47 -07:00
Jarred Sumner
21b2d5c3a5 Update executables.md 2023-08-25 04:45:41 -07:00
Jarred Sumner
10815a7d43 Update executables.md 2023-08-25 04:33:54 -07:00
Jarred Sumner
f839640c17 Update executables.md 2023-08-25 04:32:20 -07:00
Jarred Sumner
557e912d9a Fix assertion failure with sourcemaps in multi-threaded transpiler (#4321)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-25 04:00:54 -07:00
Jarred Sumner
1e75a978e5 Skip disabled test 2023-08-25 04:00:23 -07:00
Jarred Sumner
95e8c24db1 Update WebKit 2023-08-25 03:56:44 -07:00
Jarred Sumner
755f41fe2a [Inspector] Get firefox to work 2023-08-25 03:56:39 -07:00
Jarred Sumner
9aabe4eea1 Upgrade peechy 2023-08-25 01:43:25 -07:00
Jarred Sumner
90f3bf2796 Update http.md 2023-08-24 23:05:27 -07:00
Jarred Sumner
16b4bf341a Disable minifying "str".length until https://github.com/oven-sh/bun/issues/4217 is fixed 2023-08-24 23:00:53 -07:00
Ashcon Partovi
1480889205 Improved support for debug-adapter-protocol (#4186)
* Improve support for \`debug-adapter-protocol\`

* More improvements, fix formatting in debug console

* Fix attaching

* Prepare for source maps

* Start of source map support, breakpoints work

* Source map support

* add some package.jsons

* wip

* Update package.json

* More fixes

* Make source maps safer if exception occurs

* Check bun version if it fails

* Fix console.log formatting

* Fix source maps partly

* More source map fixes

* Prepare for extension

* watch mode with dap

* Improve preview code

* Prepare for extension 2

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-24 22:53:34 -07:00
Jarred Sumner
f269432d90 Listen on a unix domain socket with Bun.serve() (#4311)
* Update response.zig

* Comment this out for now

* Support unix domain socket in Bun.serve()

* Add test

* add types

* Update JSFetchHeaders.cpp

* comment this test out

* tls unix web socket serve options

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: dave caruso <me@paperdave.net>
2023-08-24 22:49:58 -07:00
Colin McDonnell
73b3fb7b0f Add guides for test runner (#4308) 2023-08-24 22:28:07 -07:00
Ashcon Partovi
2bcbafe7d3 Fix debugger not updating after reload with --hot 2023-08-24 20:09:32 -07:00
Colin McDonnell
f7f734788c Update tsconfig.base.json 2023-08-24 19:54:03 -07:00
Colin McDonnell
2cd1d59387 Update toml import type test 2023-08-24 19:52:53 -07:00
Colin McDonnell
b70210a005 Use noEmit 2023-08-24 19:51:14 -07:00
Code Hz
b9c2309c8a Remove conflict option in tsconfig-for-init.json (#4284)
fix https://github.com/oven-sh/bun/issues/4283
2023-08-24 19:41:23 -07:00
Jarred Sumner
43c4da8c9a Update build-id 2023-08-24 19:39:54 -07:00
Jarred Sumner
8a48e8bb0b Report extra memory more (#4289)
* Report memory allocated in fetch

* Memory size reporting to `Headers`

* Fixup memory reporting allocator

* Make these tests do more

* cleanup some of this

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-24 19:39:00 -07:00
Dylan Conway
097ae4e982 fix build 2023-08-24 19:05:40 -07:00
Alex Lam S.L
213f5bef9d [install] fix stale life-cycle scripts from lockfile (#4307)
fixes #4269
2023-08-24 17:18:51 -07:00
Alex Lam S.L
e115638cba [install] fix crash when installing package that uses loose semver pre-release (#4302)
- also fix parsing of `1.2.3pre+build`

fixes #4266
2023-08-24 17:17:48 -07:00
Ai Hoshino
6e57556fad Fix(node:http): fix URL formatting when using a proxy. (#4297)
Close: #4295
2023-08-24 17:17:18 -07:00
Ai Hoshino
339d2c7f19 Make the server not crash if an error occurs in dev build. (#4300)
Close: #4298
2023-08-24 17:16:51 -07:00
Jarred Sumner
d2bef4fbea Don't inline require/import errors at runtime (#4306)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-24 17:03:05 -07:00
Jason
19aa9d93de update zig to 0.11.0 (#4233)
* WIP

* backup

* more change

* json related error sovled

* number related issue solved

* revert WriterType changed before

* destroy -> free

* jsonStringify related issues solved

* fix mem.free expected []T or *[_]T, passed [*]const u8

* fix expected []T or *[_]T, passed [*:0]const u8

* fix build script

* fix build script, for real

* replace 0.11.0-dev.4006+bf827d0b5 to 0.12.0-dev.161+6a5463951

* fix build on macOS, COPYFILE.DATA -> COPYFILE_DATA

* fix the last destroy on [*]ptr issue

---------

Co-authored-by: Dylan Conway <35280289+dylan-conway@users.noreply.github.com>
2023-08-24 16:13:14 -07:00
jhmaster
55eb4ffe8f Update bun-polyfills & bun-wasm (#4246)
* automate Bun.version & revision polyfills

* polyfill Bun.gc

* bun:jsc module initial polyfills

* update peechy schema

* bun-polyfills: fix some project configs

* bun-wasm: lots of fixes

* bun-polyfills: Bun.Transpiler impl.

* revision hash update
2023-08-24 14:39:28 -07:00
Jarred Sumner
a051a6f620 Fix performance regression in reading from the request body (#4291)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-24 14:36:39 -07:00
Jarred Sumner
9c68abdb8d wip (#4282)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-24 01:32:22 -07:00
Jarred Sumner
ad326b7734 [Inspector] Fix bug with sourcemaps including internal metadata bytes 2023-08-23 22:22:55 -07:00
Colin McDonnell
aa08c35c06 Add Debugger docs and a couple guides (#4281)
* Add debugger docs. Add guides.

* Add files
2023-08-23 18:15:21 -07:00
dave caruso
20d42dfaa3 Fix <const T>() => (#4278) 2023-08-23 17:22:54 -07:00
VietnamecDevelopment
3556fa3b1e Update globals.d.ts (#4276) 2023-08-23 16:25:05 -07:00
Code Hz
5e07fd4fbc Fix ffi type (#4265)
* add readonly so it works with as const

* split ffi type infer to args and returns

* add JSCallback to FFITypeToArgsType

* add read functions

* simplify FFITypeOrString

* fix cstring type

* fix pointer type test

* fix readonly

* add unknown handling

* trigger action

* use Parameters

* add read type test

* add other read function to tests
2023-08-23 15:56:46 -07:00
Jarred Sumner
c60385716b Bunch of streams fixes (#4251)
* Update WebKit

* Don't do async hooks things when async hooks are not enabled

* Smarter scheduling of event loop tasks with the http server

* less exciting approach

* Bump WebKit

* Another approach

* Fix body-stream tests

* Fixes #1886

* Fix UAF in fetch body streaming

* Missing from commit

* Fix leak

* Fix the other leak

* Fix test

* Fix crash

* missing duperef

* Make this code clearer

* Ignore empty chunks

* Fixes #3969

* Delete flaky test

* Update bun-linux-build.yml

* Fix memory issue

* fix result body, and .done status before the last callback, dont touch headers after sent once

* refactor HTTPClientResult

* less flasky corrupted test

* oops

* fix mutex invalid state

* fix onProgressUpdate deinit/unlock

* fix onProgressUpdate deinit/unlock

* oops

* remove verbose

* fix posible null use

* avoid http null

* metadata can still be used onReject after toResponse

* dont leak task.http

* fix flask tests

* less flask close tests

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: cirospaciari <ciro.spaciari@gmail.com>
2023-08-23 14:05:05 -07:00
Quentin
f3266ff436 docs: remove broken DNS link which is also not present in the official docs (#4268) 2023-08-23 10:36:26 -07:00
xxxhussein
b01764b31e Fix more types. (#4273) 2023-08-23 10:35:51 -07:00
Jozef Steinhübl
851763174e ask for bun --revision instead bun -v (#4256) 2023-08-23 00:42:33 -07:00
dave caruso
8518fbb573 fix yield (#4264) 2023-08-22 21:54:59 -07:00
Colin McDonnell
d86084dd8e Fix Bun.inspect types 2023-08-22 14:28:01 -07:00
dave caruso
52802a4c55 fix fsevents and stub for qwikcity (#4247)
* fix test

* ok

* cm

* EE

* remove the hack we didnt need
2023-08-21 23:39:56 -07:00
Dylan Conway
44e4d5852a fix stdin stream unref and resuming (#4250)
* fix stream unref and resuming stream

* fix `child-process-stdio` test
2023-08-21 23:39:41 -07:00
Colin McDonnell
3a45f2c71b Docs and types for v0.8.0 (#4199)
* Improve test documentation

* Update nodejs compat docs with tty

* Add debugger guide

* Document Bun.inspect.custom, improve bun test nav

* Address reviews

* Update Bun.file types

* Add Nuxt guide

* Add tty types
2023-08-21 21:34:03 -07:00
Jarred Sumner
9eeb7bdbff Bun v0.8 2023-08-21 21:26:45 -07:00
Jarred Sumner
ed14b64e65 Make the code generator less duplicative 2023-08-21 21:24:49 -07:00
Jarred Sumner
bca1bcf29c import errors have code set to ERR_MODULE_NOT_FOUND and require errors have code set to MODULE_NOT_FOUND (#4244)
* ResolveMessage

* Fix it

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-21 21:11:27 -07:00
Ciro Spaciari
9027484ae1 fetch(stream) add stream support for compressed and uncompressed data (#4127)
* streams non compressed data in 64kb chunks (at least)

* fmt

* wip remove pause

* fix default streaming and buffering

* fix atomic lags

* fix size

* make chunked encoding work again (WIP streaming chunked)

* WIP: chunked encoding streaming

* fix end of streamings

* working streaming + compression

* add fixes + tests

* fmt + fix proxy

* fix oopsies

* codegen after merge

* fmt + fixes

* more fixes

* more fixes and logs

* avoid double free

* check empty before pop

* check empty on pop

* fix copy to real when complete

* remove unnecessary logs

* better has_schedule_callback swap, body locked size helper, remove isEmpty from unbounded_queue pop

* fix response ref, fix body_size

* add deflate support, fix error throw, add more tests

* codegen after merge

* remove logs, add connection close test

* fix macOS build

* fix redirect error option

* make body_size more clear

* support new Reponse(response)

* toString DOMWrapper objects properly instead of supporting response in Response constructor

* ignore headers with no name, add more tests

* oops

* handle transform with fetch

* add gz image stream test

* remove duplicate test

* fix missing chunk on macOS under pressure

* oops include all OS

* some fixes

* compare buffers instead of sizes

* refactor err.err and protect it
2023-08-21 20:30:34 -07:00
dave caruso
91eacade97 Fix inquirer (#4245) 2023-08-21 19:32:41 -07:00
Jarred Sumner
6a02edef5d Update module_loader.zig 2023-08-21 19:04:18 -07:00
Ai Hoshino
a61953bbfd Fix(bundler): allow generating exe file in nested path. (#4226)
* Fix(bundler): allow generating binary file in nested path.
Close: #4195

* Add read flag for fd.

* refactor
2023-08-21 18:22:37 -07:00
Colin McDonnell
f629365cb7 Fix typo 2023-08-21 17:48:48 -07:00
dave caruso
cdace9bffb Fix crypto.EC constructor (#4242)
* Fix EC constructor

* make js
2023-08-21 16:40:25 -07:00
dave caruso
664119841a Implement napi_ref_threadsafe_function (#4156)
* Implement napi_ref_threadsafe_function

* work on this

* i hate event loops

* little better

* clean
2023-08-21 16:26:07 -07:00
dave caruso
397182b400 feat: Implement Bun.inspect.custom (#4243)
* add Bun.inspect.custom

* test

* Add Types
2023-08-21 16:25:37 -07:00
Jarred Sumner
752e59f23c Fixes #4089 (#4105)
* Fixes #4089

* Update bindings.cpp

* address PR feedback

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-21 16:25:23 -07:00
Jarred Sumner
def5a85d90 40x faster .toString('hex') (#4237)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-21 08:31:17 -07:00
Jarred Sumner
1b8f569792 Fix memory leak in buffer.toString("hex") (#4235)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-21 03:31:33 -07:00
xxxhussein
183b818462 Update README.md (#4232)
Fix typo in README.md
2023-08-21 01:32:08 -07:00
Jarred Sumner
9cf868fef4 Add missing header change 2023-08-21 01:30:45 -07:00
Jarred Sumner
ed803f7d1c Add LazyProperty 2023-08-21 01:30:13 -07:00
Jarred Sumner
c13a27121c Fix BigIntStats generated class
cc @paperdave, code generator script misses a constructor decl when this isn't true
2023-08-21 01:30:01 -07:00
Jarred Sumner
8c23e77e99 Regenerate 2023-08-21 01:29:15 -07:00
Jarred Sumner
c99a9ba33a Implement File 2023-08-21 01:29:06 -07:00
Jarred Sumner
f75b949524 Fixes #1675 (#4230)
* Fixes https://github.com/oven-sh/bun/issues/1675

* Add fallback for Bun.write

* Update blob.zig

* Fix test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-20 21:29:09 -07:00
Jarred Sumner
3de9ce5f30 Implement --inspect-brk (#4222)
* Implement `--inspect-brk`

* Bump WebKit

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-20 19:34:33 -07:00
Jarred Sumner
65280853ac Fix test failures from 3a9a6c63a (#4231)
cc @Hanaasagi

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-20 19:22:55 -07:00
Ai Hoshino
3a9a6c63ac Fix(bundler): use different alias mappings based on the target. (#4163)
* Fix(bundler): use different alias mappings based on the target.
Close: #3844

* chore: reduce duplicated code.

* chore: split to two separate ComptimeStringMap.
2023-08-20 01:52:17 -07:00
Jarred Sumner
360acf5a80 Update BunDebugger.cpp 2023-08-19 22:11:48 -07:00
Jarred Sumner
d432dad666 Introduce bun --inspect-wait
This waits for the inspector to connect before beginning execution
2023-08-19 22:07:35 -07:00
Jarred Sumner
eec5bfb23a misc non-posix fixes 2023-08-19 20:14:29 -07:00
Jarred Sumner
53c755467b Update lockfile.md 2023-08-19 19:10:20 -07:00
Jarred Sumner
039404800f Update lockfile.md 2023-08-19 19:09:10 -07:00
Jarred Sumner
3c4b689050 Update lockfile.md 2023-08-19 19:08:17 -07:00
Omar
394dd86797 Update Dockerfile-distroless (#4210) 2023-08-19 18:48:59 -07:00
Jarred Sumner
62bde005b2 Fix symbol visibility 2023-08-19 18:48:07 -07:00
Jarred Sumner
19054ebc35 [napi] Implement node_api_create_syntax_error, node_api_symbol_for, node_api_throw_syntax_error
These were marked as experimental
2023-08-19 18:34:56 -07:00
Jarred Sumner
507761b463 Fix crash impacting sharp & resvg (#4221)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-19 18:17:16 -07:00
Jarred Sumner
196620183f Fixes #172 (#4220)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-19 17:46:59 -07:00
Jarred Sumner
86ad015147 Add inline sourcemaps when --inspect is enabled (#4213)
* Add inline sourcemaps when --inspect is enabled

* Add some assertions

* Update javascript.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-19 00:20:23 -07:00
Dylan Conway
db09ed15fd tty ReadStream, WriteStream, and readline rawmode (#4179)
* tty `WriteStream`, `ReadStream`, and rawmode

* tests

* refactor prototypes

* fix failing test

* fix test and library usage

* more merge

* fix child_process test

* create pseudo terminal for tty tests

* match node logic

* handle invalid tty

* close descriptors

* move tests to another process

* fix test again

* fix test on linux
2023-08-19 00:11:24 -07:00
Jarred Sumner
bf517d9f8e Fix make headers (again) 2023-08-18 22:14:38 -07:00
Jarred Sumner
e9b684c972 Add HTMLRewriter microbnechmark 2023-08-18 22:14:24 -07:00
Jarred Sumner
e8f0ed3beb Fix make headers 2023-08-18 22:09:27 -07:00
Jarred Sumner
3ca7fde363 prettier 2023-08-18 20:41:54 -07:00
Brúnó Salomon
c2ec47ff32 feat: add self-closing & can-have-content (#4206) 2023-08-18 19:59:23 -07:00
dave caruso
26036a390b Implement BigIntStats (#4208)
* Implement BigIntStats

* changes

* rename test

* comment

* test changes?
2023-08-18 19:59:03 -07:00
Jarred Sumner
943a664224 Remove most C API usages, add debugger pretty printers for Headers, URLSearchParams, FormData, Worker, EventTarget (#4187)
* Add pretty printers for `Headers`, `URLSearchParams`, and `FormData`

* [untested] Add way to code generate getInternalProperties

* bump

* Bump Webkit

* Ref the event loop while loaded

* wip

* checkpoint

* another checkpoint

* The code has been written

* Fixup exports

* Fix all the errors

* Fix bug

* [console.log] Fix bug when printing non-reified types missing values

* Fix loading hash table

* fix plugin

* Fix ref & unref

* auto-unref

* various fixes

* Update bun.zig

* Set toStringTag

* Delete code for macro JSX

* Delete code for `bun dev` HTTP JS

* Move Bun.serve to C++ API

* Delete JSC C API code

* ✂️ 💀 code

* Use JSC C++ for `confirm`, `Crypto`, `prompt`, `alert`

* more dead code

* Update exports.zig

* Use JSC C++ API for FFI

* Remove remaining usages

* Remove remaining usages

* Update ffi.ts

* Update InternalModuleRegistryConstants.h

* draw the rest of the owl

* Update webcore.zig

* bind it

* Fix performance regression in crypto.randomUIUD()

* Update js_parser.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-18 19:58:03 -07:00
Dylan Conway
d0664f8377 fix --bail test 2023-08-18 14:51:55 -07:00
dave caruso
6fd0043f6b Add util.inspect.custom support to util.inspect/Bun.inspect/console.log (#4194)
* start work on util.inspect.custom

* asdf

* finish util inspect custom inspect

* inspect

* fix tests

* revert

* tidy

* revert

* oops

* test

* fix issues
2023-08-17 20:56:52 -07:00
dave caruso
0424fd8f6e Support Nitro (#4098)
* Add formatWithOptions

* tests and tweaks

* adjust

* changes

* hi

* add mark/measure stubs

* stuff

* allow unix absolute paths here

* typo

* rebase

* fix stats
2023-08-17 19:34:05 -07:00
Colin McDonnell
cfbd1373e2 Update Astro guide 2023-08-17 18:38:10 -07:00
dave caruso
f74585ff01 Allow IncomingRequest.req to be overwritten. (#4154)
* Allow IncomingRequest.req to be overwritten.

* add test

* fix test

* yoo
2023-08-17 14:57:43 -07:00
Ai Hoshino
b2f8ef4dff Fix(node:fs): add buffer parameter in fs.read callback. (#4191)
Close: #4178
2023-08-17 14:27:33 -07:00
Brúnó Salomon
b0e76a965d refactor: move HTMLRewriter to c++ bindings (#4193) 2023-08-17 14:25:09 -07:00
Colin McDonnell
cfce38858f Fix description for executables page 2023-08-17 14:07:36 -07:00
Colin McDonnell
540740c129 Add Astro guide (#4110) 2023-08-17 12:51:45 -07:00
xxxhussein
b1356718ad correct guide's bunfig example option (#4192) 2023-08-17 12:13:16 -07:00
Colin McDonnell
b9b50e39d6 Fix broken link 2023-08-16 22:58:36 -07:00
Jarred Sumner
6c3dabd84e Fix leaking .ptr (#4181)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-16 22:10:01 -07:00
Colin McDonnell
d4438e9496 Add solidstart guide (#4182) 2023-08-16 21:30:37 -07:00
Colin McDonnell
56d591b903 Add sveltekit guide (#4180) 2023-08-16 20:52:49 -07:00
Jarred Sumner
0486cea35a bun --inspect (#4158)
* Let the debugger to pause/resume the event loop

* Add initial support for Debug Adapter Protocol

* Add progress

* Update Worker.cpp

* Fix require("console") #3820 (#4073)

* Fix #3820

* Add Module (#4074)

* Set exports to {} in user-constructed CommonJSModuleRecords (#4076)

* feat(bun/test): Implement "toSatisfy" & "toIncludeRepeated" (fwup) (#3651)

* Fix merge issues

* oop

* make codegen

* Fix build issues

---------

Co-authored-by: dave caruso <me@paperdave.net>

* worker tests (#4058)

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>

* feat(bun:test) add support for test.each() and describe.each() (#4047)

* rename callback to func

* update testscope to handle function arguments

* works

* big cleanup

* works in debug, not release

* fix memory issue & update tests

* catch & str test

* write types for each() & switch tests to ts

* rm & typo

* move some code around & support describe

* review changes

* Fix one of the astro segfaults, also fix bun init version (#4079)

* 4->16

* add assertions

* fix version stuff

* Remove unintentional logs from #4043

* Run prettier

* Update main-worker-file.js

* Update SIMDUTF (#4078)

* Fix constructing buffer from a UTF16 string with the Latin1 encoding. (#4086)

Close: #3914

* Add support for `bun --revision` (#4027)

Co-authored-by: Yash Sharma <yashsharma@Yashs-MacBook-Air.local>

* Updates

* Update __global.zig

* remove non-node node-fallbacks (#4082)

* remove non-node node-fallbacks.

* organize the imports

* Fix test

* Sync bun-polyfills branch (#4081)

* bun-polyfills: initial impl. & baseline refactor

* move @types/ws dep from root to /test/

* bun-types: remove ReadableStream.forEach method
(this does not exist, probably added by mistake)

* bun-polyfills: remove extraneous stream utils

* bun-polyfills: add types syncing file

* bun-polyfills: re-arrange global polyfills

* bun-polyfills: fix FileBlob streams types again

* bun-polyfills: sync all of @types/node

* bun-polyfills: typeguard all current polyfills

* bun-polyfills: fix import paths

* bun-polyfills: switch to wasm impl. of farmhash

* bun-polyfills: support default import of bun obj

* bun-polyfills: transpiler placeholder file

* bun-polyfills: loaderless import.meta polyfill

* bun-polyfills: refactor import.meta polyfill

* bun-polyfills: repl entrypoint & todo list index

* bun-types: Add null to return type of Bun.which

* bun-types: match Bun.sha with Bun.hash.SHA512_256

* bun-polyfills: new "repl" package.json script

* bun-polyfills: full refactor of toplevel hashes

* bun-polyfills: these are fixed

* bun-types: NODE_ENV is optional

* bun-polyfills: fix Bun.env types

* bun-types+polyfills: fix HeapSnapshot.version type

* bun-polyfills: fix some web streams type conflicts

* bun-polyfills: update internal FileBlob.slice

* bun-polyfills: fix subproc stdin conversions

* bun-polyfills: better internal fileblob types

* bun-polyfills: try to sync global performance type

* bun-polyfills: working zig wasm polyfills setup

* bun-polyfills: update scripts

* bun-polyfills: fix wasm file location resolution

* bun-polyfills: goodbye farmhash (replaced by zig)

* bun-polyfills: move all Bun.hash polyfills to zig

* bun-polyfills: reimpl. seeding of seeded hashes

* bun-polyfills: impl. undocumented murmur32v2

* bun-polyfills: switch zighash from jsdoc to .d.ts

* bun-types: partial fix of Hash types

* bun-polyfills: documented Hash.murmur32v2

* bun-polyfills: misc updates

* bun-polyfills: enable sourcemaps

* bun-polyfills: handle empty inputs to hash funcs

* bun-types: narrow down hash func types

* bun-polyfills: remove unnecessary bigint casts

* bun-polyfills: impl. Bun.isMainThread

* bun-polyfills: impl. Bun.sleep and fix sleepSync

* bun-polyfills: impl. indexOfLine

* bun-polyfills: impl. Bun.peek.status

* bun-types: fix hashing test

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>

* Add remix guide

* Fix title

* add util.formatWithOptions (#4090)

* Add formatWithOptions

* tests and tweaks

* adjust

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>

* bun test: format description of test.each (#4092)

* bun test: format description

* add tests for tests

* only

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>

* Fixes #4062 (#4106)

* Fixes #4062

* Update encoding.zig

* Use faster C++ impl

* Update wtf-bindings.cpp

* undo

* Fixup

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* zig fmt

* Update remix guide

* fs.zig: create temp files with 0o700, not 0o007 (#4107)

* Handle thundering herd of setInterval (#4109)

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* Fix memory leak in base64url (#4111)

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* run files without extensions (#4113)

* run script without extension

* process stdio write fix

* don't check for trailing slash, var stream

* More lazily initialize these static strings

* Remove assertion

* wip

* Add --inspect flag

* Deprecate loading `node_modules.bun`

* realpath

* regenerate schema

* More

* more

* Update cli.zig

* Debugger JS loads

* have fun

* Most of the code

* Its starting to work.

* more progress

* win some, lose some

* Update dap.ts

* Async Context Tracking

* untested websocket

* Emit Console messages

* Error handling

* errors

* Make profiling work better

* [clap] CLI arguments with optional values ignore positional params

In `bun --inspect foo.js`, `foo.js` should not be the value of `--inspect`. It is a positional parameter. `--inspect=foo`

* Support multiple simultaneous clients, automatically unpause on disconnect

* regenerate

* Update Makefile

* Update WebKit

* Update cli.zig

* Update InternalModuleRegistry+createInternalModuleById.h

* BaseURL

* Update WebKit

* Add web-inspector-bun

* Update build.ts

* formatting, mostly

* Update debugger.ts

* Update InternalModuleRegistryConstants.h

* wrap

* Update test

* Update test

---------

Co-authored-by: Ashcon Partovi <ashcon@partovi.net>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: dave caruso <me@paperdave.net>
Co-authored-by: Tiramify (A.K. Daniel) <94789999+TiranexDev@users.noreply.github.com>
Co-authored-by: Jacques <25390037+jecquas@users.noreply.github.com>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: Ai Hoshino <ambiguous404@gmail.com>
Co-authored-by: Yash Sharma <yashosharma@gmail.com>
Co-authored-by: Yash Sharma <yashsharma@Yashs-MacBook-Air.local>
Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
Co-authored-by: jhmaster <32803471+jhmaster2000@users.noreply.github.com>
Co-authored-by: Adhityaa Chandrasekar <github@adtac.in>
Co-authored-by: Dylan Conway <35280289+dylan-conway@users.noreply.github.com>
2023-08-16 19:40:20 -07:00
Ciro Spaciari
2634c64aa3 Fix prisma linux generation (#4150)
* check

* fmt + fix

* fmt

* ops

* add more targets

* more targets

* oops

* update bun lock and prisma

* manually add openssl

* targets on sqlite
2023-08-16 16:12:02 -07:00
Dylan Conway
af23dab833 Create domjit.test.ts (#4173) 2023-08-15 22:13:13 -07:00
Dylan Conway
9efeef2e24 res.then 2023-08-15 21:51:43 -07:00
dave caruso
67a8b75183 fix this page (#4172) 2023-08-15 19:02:46 -07:00
Dylan Conway
bdaa712357 disable domjit for Buffer.alloc 2023-08-15 19:00:02 -07:00
dave caruso
b682e5bf59 Fix event loop issue with Bun.connect (#4157)
* Fix event loop issue with Bun.connect

* sorry

* add test and fix another edge case
2023-08-15 18:09:11 -07:00
Dylan Conway
17c348ed0a fix make headers 2023-08-15 14:56:21 -07:00
Dylan Conway
f05a38757a fix build 2023-08-15 14:33:45 -07:00
Ai Hoshino
553a471cdf chore: fix method name typo (#4162) 2023-08-15 08:11:11 -07:00
dave caruso
1a6a52314f fix importing too long of strings (#4155) 2023-08-15 01:56:37 -07:00
dave caruso
47450ed12c Make builtins' source origin use a valid url (#4152)
* Make source origin use a valid url

* disable minifyWhiteSpace

* the change
2023-08-14 20:28:18 -07:00
Colin McDonnell
eab7b4c3ea Small docs change 2023-08-14 12:08:33 -07:00
dave caruso
0329061f15 fix makefile (#4148) 2023-08-13 20:43:44 -07:00
Revenity
1e96cbfb02 Update Stric guides (#4137) 2023-08-12 20:03:41 -07:00
dave caruso
78defe7a87 Fix worker event loop ref/unref + leak (#4114)
* make more tests pass

* worker changes

* fix some bugs

* remove this

* progress

* uh

* okay

* remove console log

* a

* comment assert for later

* mergable state

* remove test

* remove test
2023-08-12 13:51:03 -07:00
Ai Hoshino
b94433ce86 Fix using uninitialized variable when formatting config_path. (#4129)
Close: #4128
2023-08-11 22:14:08 -07:00
Jarred Sumner
ca26780b27 Deprecate loading node_modules.bun (#4131)
* Deprecate loading `node_modules.bun`

* realpath

* regenerate schema

* More

* more

* Update cli.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-11 22:13:46 -07:00
jhmaster
117cee5ca5 bun-wasm fixes & improvements (#4126)
* automate Bun.version & revision polyfills

* polyfill Bun.gc

* bun:jsc module initial polyfills

* fixes & improvements to bun-wasm
2023-08-11 18:20:21 -07:00
Jarred Sumner
43ebffedcd Support TypeScript's export type * as Foo from 'bar' (#4125)
* [TypeScript] Support `export type * as Foo from 'bar'`

* Update js_parser.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-11 18:06:48 -07:00
Jarred Sumner
ccb9daf7a4 Fix wasm build 2023-08-11 16:24:29 -07:00
Jarred Sumner
c6d3b375b8 async realpath (#4117)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-10 22:15:07 -07:00
Jarred Sumner
4731a460a2 Remove assertion 2023-08-10 19:58:59 -07:00
Jarred Sumner
99af827f25 More lazily initialize these static strings 2023-08-10 19:56:02 -07:00
Dylan Conway
a6ec7fe9b1 don't check for trailing slash, var stream 2023-08-10 19:06:51 -07:00
Dylan Conway
513a6d0df3 run files without extensions (#4113)
* run script without extension

* process stdio write fix
2023-08-10 19:00:06 -07:00
Jarred Sumner
115704b27b Fix memory leak in base64url (#4111)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-10 16:43:19 -07:00
Jarred Sumner
85b81624dc Handle thundering herd of setInterval (#4109)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-10 15:25:52 -07:00
Adhityaa Chandrasekar
cf12d80f5e fs.zig: create temp files with 0o700, not 0o007 (#4107) 2023-08-10 14:00:13 -07:00
Colin McDonnell
58e74eadb5 Update remix guide 2023-08-10 13:54:17 -07:00
Jarred Sumner
be05b93f39 zig fmt 2023-08-10 13:32:37 -07:00
Jarred Sumner
e25833d009 Fixes #4062 (#4106)
* Fixes #4062

* Update encoding.zig

* Use faster C++ impl

* Update wtf-bindings.cpp

* undo

* Fixup

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-10 13:32:04 -07:00
Jacques
e65535cc05 bun test: format description of test.each (#4092)
* bun test: format description

* add tests for tests

* only

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-10 13:29:53 -07:00
dave caruso
74f9fabd01 add util.formatWithOptions (#4090)
* Add formatWithOptions

* tests and tweaks

* adjust

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-10 13:09:03 -07:00
Colin McDonnell
8d207925d7 Fix title 2023-08-10 12:37:14 -07:00
Colin McDonnell
e0569ac47a Add remix guide 2023-08-10 12:36:54 -07:00
jhmaster
40befd8770 Sync bun-polyfills branch (#4081)
* bun-polyfills: initial impl. & baseline refactor

* move @types/ws dep from root to /test/

* bun-types: remove ReadableStream.forEach method
(this does not exist, probably added by mistake)

* bun-polyfills: remove extraneous stream utils

* bun-polyfills: add types syncing file

* bun-polyfills: re-arrange global polyfills

* bun-polyfills: fix FileBlob streams types again

* bun-polyfills: sync all of @types/node

* bun-polyfills: typeguard all current polyfills

* bun-polyfills: fix import paths

* bun-polyfills: switch to wasm impl. of farmhash

* bun-polyfills: support default import of bun obj

* bun-polyfills: transpiler placeholder file

* bun-polyfills: loaderless import.meta polyfill

* bun-polyfills: refactor import.meta polyfill

* bun-polyfills: repl entrypoint & todo list index

* bun-types: Add null to return type of Bun.which

* bun-types: match Bun.sha with Bun.hash.SHA512_256

* bun-polyfills: new "repl" package.json script

* bun-polyfills: full refactor of toplevel hashes

* bun-polyfills: these are fixed

* bun-types: NODE_ENV is optional

* bun-polyfills: fix Bun.env types

* bun-types+polyfills: fix HeapSnapshot.version type

* bun-polyfills: fix some web streams type conflicts

* bun-polyfills: update internal FileBlob.slice

* bun-polyfills: fix subproc stdin conversions

* bun-polyfills: better internal fileblob types

* bun-polyfills: try to sync global performance type

* bun-polyfills: working zig wasm polyfills setup

* bun-polyfills: update scripts

* bun-polyfills: fix wasm file location resolution

* bun-polyfills: goodbye farmhash (replaced by zig)

* bun-polyfills: move all Bun.hash polyfills to zig

* bun-polyfills: reimpl. seeding of seeded hashes

* bun-polyfills: impl. undocumented murmur32v2

* bun-polyfills: switch zighash from jsdoc to .d.ts

* bun-types: partial fix of Hash types

* bun-polyfills: documented Hash.murmur32v2

* bun-polyfills: misc updates

* bun-polyfills: enable sourcemaps

* bun-polyfills: handle empty inputs to hash funcs

* bun-types: narrow down hash func types

* bun-polyfills: remove unnecessary bigint casts

* bun-polyfills: impl. Bun.isMainThread

* bun-polyfills: impl. Bun.sleep and fix sleepSync

* bun-polyfills: impl. indexOfLine

* bun-polyfills: impl. Bun.peek.status

* bun-types: fix hashing test

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-10 12:17:39 -07:00
Jarred Sumner
6718950a39 Fix test 2023-08-10 12:08:05 -07:00
dave caruso
68ac8c12c2 remove non-node node-fallbacks (#4082)
* remove non-node node-fallbacks.

* organize the imports
2023-08-10 11:57:37 -07:00
Jarred Sumner
28d1676d50 Update __global.zig 2023-08-09 16:50:00 -07:00
Colin McDonnell
883c4d8778 Updates 2023-08-09 13:47:32 -07:00
Yash Sharma
8717303a80 Add support for bun --revision (#4027)
Co-authored-by: Yash Sharma <yashsharma@Yashs-MacBook-Air.local>
2023-08-09 10:43:04 -07:00
Ai Hoshino
385d440694 Fix constructing buffer from a UTF16 string with the Latin1 encoding. (#4086)
Close: #3914
2023-08-09 09:45:50 -07:00
Jarred Sumner
b3019270c9 Update SIMDUTF (#4078) 2023-08-09 09:14:51 -07:00
Jarred Sumner
5d7c77aab0 Update main-worker-file.js 2023-08-08 23:02:45 -07:00
Jarred Sumner
2c70837ae7 Run prettier 2023-08-08 23:01:03 -07:00
Jarred Sumner
bed7ff7dd0 Remove unintentional logs from #4043 2023-08-08 22:59:40 -07:00
dave caruso
450b066cb8 Fix one of the astro segfaults, also fix bun init version (#4079)
* 4->16

* add assertions

* fix version stuff
2023-08-08 22:27:18 -07:00
Jacques
63f58f4026 feat(bun:test) add support for test.each() and describe.each() (#4047)
* rename callback to func

* update testscope to handle function arguments

* works

* big cleanup

* works in debug, not release

* fix memory issue & update tests

* catch & str test

* write types for each() & switch tests to ts

* rm & typo

* move some code around & support describe

* review changes
2023-08-08 22:25:32 -07:00
dave caruso
009fe18fa2 worker tests (#4058)
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-08-08 22:19:46 -07:00
Tiramify (A.K. Daniel)
40d00a961e feat(bun/test): Implement "toSatisfy" & "toIncludeRepeated" (fwup) (#3651)
* Fix merge issues

* oop

* make codegen

* Fix build issues

---------

Co-authored-by: dave caruso <me@paperdave.net>
2023-08-08 22:14:30 -07:00
dave caruso
1941dbbd71 Set exports to {} in user-constructed CommonJSModuleRecords (#4076) 2023-08-08 19:37:36 -07:00
dave caruso
320cdcf97e Fix require("console") #3820 (#4073)
* Fix #3820

* Add Module (#4074)
2023-08-08 18:23:33 -07:00
Dylan Conway
454407003e Update Worker.cpp 2023-08-08 15:08:16 -07:00
Ai Hoshino
511f6bdf79 1. Check if the argument is an empty string in path.format. (#4064)
2. Avoid duplicating '/' at the beginning of the path.
Close: #4005
2023-08-08 07:03:18 -07:00
Jarred Sumner
320ee6b6b7 import bun (#4055)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-08 01:42:44 -07:00
Jarred Sumner
38df5b146f Enable Headers.prototype.getSetCookie
Fixes #4057
2023-08-08 01:18:36 -07:00
Jarred Sumner
25c91aecab Remove printf 2023-08-08 00:31:46 -07:00
dave caruso
5497accbdb Add env option for node:worker_threads (#4052)
* almost works

* env stuff

* test fixes

* wtfmove

* ok

* ok

* ref by default

* it now does the ref stuff by default

* cool
2023-08-07 23:58:38 -07:00
jhmaster
182e600eb7 Fix Bun.hash functions (#4054)
* fix `Bun.hash` functions to behave as expected

* update Bun.hash tests
* properly test the returned hash
* include murmur32v2

* update Bun.hash docs

* run fmt
2023-08-07 23:30:05 -07:00
Dylan Conway
cb873cc081 fix worker.ref() 2023-08-07 22:40:32 -07:00
Jarred Sumner
330d19e344 add bun update to help menu 2023-08-07 21:14:42 -07:00
Dylan Conway
2fe6a965af implement fetching data urls (#4000)
* fetch data urls

* `byteSlice`

* deinit slice

* allocate `mime_type` string if needed

* `content_type_allocated` and uncomment tests

* `str_`

* createAtom and slice decode result
2023-08-07 20:15:53 -07:00
Alex Lam S.L
a32097aa9f implement bun update (#4046)
- analogous to `npm update`
- `bun update <name>` to refresh specified package under `package.json`
- `bun update` to refresh all package to latest versions
2023-08-07 20:11:32 -07:00
Dylan Conway
1239c9460a fix iterating headers with set-cookie (#4048)
* fix iterating headers with `set-cookie`

* a test

* move work to `HTTPHeaderMap::set`

* append set-cookie after sort

* remove compare function
2023-08-07 19:32:23 -07:00
Jarred Sumner
f2f227720b WASM test analyzer (#4043)
* wasm

* WASM test scanner

* Update Makefile

* Update Makefile

* Configurable heap limit

* slightly better error

* Update js_parser.zig

* Update path.test.js

* Update node.mjs

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-07 18:51:16 -07:00
Colin McDonnell
0b183beb51 Improve plugin docs 2023-08-07 14:02:43 -07:00
Ai Hoshino
5ce393aab8 Fix path.normalize edge case. (#4042)
Close: #4041
2023-08-07 06:44:04 -07:00
Jarred Sumner
00a907c7de Fixes #4001 (#4034)
* Avoid a utf8 conversion in isDetached

* Fixes #4001

* hit the long url codepath

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 22:49:10 -07:00
Jarred Sumner
0665733b03 Fixes #4029 and fixes #4022 (#4032)
* Fixes #4029 and Fixes #4022

Fixes #4029

Fixes #4022

* Add test for all the fetches

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 20:39:40 -07:00
Jarred Sumner
70c3371b14 Fixes #4010 (#4031)
* Fixes #4010

* Update websocket_http_client.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 19:30:06 -07:00
Jarred Sumner
0b2be88bac Update build-id 2023-08-06 18:07:15 -07:00
Jarred Sumner
8297fb0d2f Bind require.resolve() (#4030)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 18:06:18 -07:00
Jarred Sumner
04925bb94c Fixes #4020 2023-08-06 17:57:44 -07:00
Yash Sharma
3185ca2d95 Running missing scripts exits with non-0 (#4026)
Co-authored-by: Yash Sharma <yashsharma@Yashs-MacBook-Air.local>
2023-08-06 17:43:24 -07:00
Alex Lam S.L
b93f304c06 [install] handle bun add of existing peerDependencies correctly (#4028) 2023-08-06 17:42:08 -07:00
Jarred Sumner
a9b3d58353 fix nan 2023-08-06 07:55:22 -07:00
Jarred Sumner
cf48379921 Update coverage.md 2023-08-06 07:48:06 -07:00
Jarred Sumner
f8026df821 Update lol-html 2023-08-06 07:35:29 -07:00
Jarred Sumner
fa4e5d033e Fixes #3129 (#4018)
* Fixes #3129

* add CloseEvent

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 07:35:07 -07:00
Jarred Sumner
1462445419 Code coverage for bun test (#3975)
* WIP code coverage initial commit

* almost works

* one approach

* Code Coverage

* Update WebKit

* it works but is not yet accurate

* skip double ascii check

* wrapper

* it works but i'm not sure what to do about blocks

* hide blocks for now

* Update ZigSourceProvider.cpp

* Create coverage.md

* Update nav.ts

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 06:30:23 -07:00
Ai Hoshino
ecdf2ffa6c feat: impl dns.getServers (#3982)
* feat: impl `dns.getServers`
Close: #3981

* check return value of `ares_inet_ntop`
2023-08-06 06:16:54 -07:00
dave caruso
cd0774cd89 Implement --test-name-pattern (#3998)
* Fix end not being emitted all the time

* stuff

* Implement -t

* Undo js_printer changes

* Undo http changes

* Update InternalModuleRegistryConstants.h

* Delete unrelated test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-06 06:13:39 -07:00
Ai Hoshino
cf8650937a Fix(cli/init): support subpath entrypoint. (#4002) 2023-08-05 04:48:22 -07:00
dave caruso
3803d39840 Remove Bun.plugin transpiler hook, encourage usage of --preload instead (#3987)
* Remove Bun.plugin transpiler hook

* one missing case
2023-08-05 04:42:30 -07:00
Colin McDonnell
78081cbb40 Support --dev/-D and support more flags on bun install (#3989) 2023-08-04 20:41:16 -07:00
Dylan Conway
6bdee80cfc fix macro string escaping (#3967)
* handle macro escaping

* remove printer

* use `js_lexer.decodeEscapeSequences`
2023-08-04 19:34:09 -07:00
Jarred Sumner
637a38f394 Fixes #3991
Fixes #3991
2023-08-04 18:54:08 -07:00
Alex Lam S.L
190ba6b743 [install] handle workspace:* correctly (#3994)
- parse as path so it works on unversioned workspaces
- fix missed storage of workspace version

fixes #3985
2023-08-04 18:21:13 -07:00
Jarred Sumner
e2c526708a Update import-meta.md 2023-08-04 17:40:11 -07:00
Jarred Sumner
f06f178862 Fix incorrect docs 2023-08-04 17:38:17 -07:00
Alex Lam S.L
8275b8ccd2 [types] fix blob.json() (#3995) 2023-08-04 17:30:38 -07:00
dave caruso
d196aa2de6 FFI typo (#3973)
* FFI typo

* add tests

* it was a newline
2023-08-04 16:08:50 -07:00
Yifei Wang
bdbc21ff7b Buffer.copy should ignore out-of-range sourceEnd (#3971) 2023-08-04 16:08:25 -07:00
Alex Lam S.L
ff315a3bf2 [install] store resolved workspace path in lockfile (#3974)
- resolve cwd consistently
- speed up package diff
- update `test/bun.lockb`

fixes #3685
fixes #3958
2023-08-04 23:28:42 +03:00
Colin McDonnell
63d265780f Fix types (#3963)
* Fix types

* Add ws module

* Add *.toml module declaration

* Clean up
2023-08-04 12:56:34 -07:00
simylein
18a2e18ae1 feat(hot-clear-screen): clear terminal on hot reload (#3976)
* feat(hot-clear-screen): clear terminal on hot reload

* fix(hot-clear-screen): is now I n the correct place

* fix(hot-clear-screen): enable buffering after terminal clear
2023-08-04 04:01:10 -07:00
Jarred Sumner
76dee9312b Add microbenchmark for private properties 2023-08-03 20:14:17 -07:00
Jarred Sumner
9beccc3305 Fix thread safety issue in async fs functions file paths (#3964)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-03 20:09:05 -07:00
Jarred Sumner
717f0a2f42 Make the test better 2023-08-03 18:23:57 -07:00
Jarred Sumner
c2ebdf812b Test for Module.wrap() 2023-08-03 18:22:45 -07:00
Jarred Sumner
9ab2acced6 Implement Module.wrap() 2023-08-03 18:22:45 -07:00
Jarred Sumner
944fcebc2b Update build-id (#3940)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-03 18:15:55 -07:00
Colin McDonnell
9222316101 Update Node.js compat docs 2023-08-03 17:48:18 -07:00
Colin McDonnell
d10860d272 Add type tests 2023-08-03 17:44:18 -07:00
Colin McDonnell
76fa3076cd Add type tests, update modules.md 2023-08-03 17:41:47 -07:00
Colin McDonnell
112030481f More guides and fixing links (#3960)
* More guides

* WIP

* Updates

* Fix
2023-08-03 16:31:05 -07:00
Dylan Conway
9574db355f allow bundling builtins for browser (#3959)
* Update resolver.zig

* bundle resolve error for non-existent builtins

* tests
2023-08-03 16:27:45 -07:00
Ai Hoshino
a4d996c337 Fix edge case in path.relative. (#3952)
Close: #3924
2023-08-03 15:40:37 -07:00
Ashcon Partovi
08cf0d562a Bunch of fixes (#3516)
* Fix #3497

* Fix #3497

* Run prettier

* Fix package.json

* remove this too

* yeah

* Fix missing tests

* Use native for utf-8-validate

* Add module ID names to builtins

* Defer evaluation of ESM & CJS modules until link time

* Use builtin name for exports in plugins

* Add module IDs to builtins

* Update JSC build with new flag

* WebKit upgrade fixes

* Update WebKit

* prettier

* Upgrade WebKit

* bump

* Update once again

* Add visitAdditionalChildren, remove .fill() usage

* Update process.test.js

* Update fs.test.ts

---------

Co-authored-by: dave caruso <me@paperdave.net>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-03 15:31:55 -07:00
Alex Lam S.L
9a2c3dea88 [install] fix stale bun.lockb on workspaces (#3945)
- handle workspaces under `--production` correctly
- fix `Makefile`
2023-08-03 12:37:29 -07:00
Ai Hoshino
2c9ff9584a Minor optimization: Avoid extra copying when the chunk has only one element. (#3946)
* Optimize the case where there is only one chunk.

* add generated code
2023-08-03 12:35:04 -07:00
Ai Hoshino
30dde62521 Fix the string encoding in path.extname. (#3949)
Close: #3948
2023-08-03 12:34:41 -07:00
Jarred Sumner
928816bef0 SvelteKit compatibility hack 2023-08-02 21:07:39 -07:00
dave caruso
f17655b2eb typo (#3941) 2023-08-02 20:43:39 -07:00
Ashcon Partovi
9f2dcb064d Fix formatting 2023-08-02 19:02:54 -07:00
dave caruso
6c176cb243 Dave/removedeprecation (#3938)
* hide deprecated stuff

* this edit

* hi
2023-08-02 18:57:11 -07:00
dave caruso
e83058cfe7 Fix http write (#3939)
* Fix encoding problem when uploading a binary file.
Close: #3116

* use BufferList

* Finish rebase

---------

Co-authored-by: Hanaasagi <ambiguous404@gmail.com>
2023-08-02 18:56:41 -07:00
dave caruso
aaaaf744a8 Remove module and browser conditions (#3935)
* fix astro compiler

* clean this up

* Update options.zig

---------

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
2023-08-02 18:46:57 -07:00
Jarred Sumner
207c7eb509 Implement node:worker_threads (#3923)
* Start to implement `worker_threads`

* more

* more!!

* more

* Update bundle_v2.zig

* delete outdated tests

* `receiveMessageOnPort`

* props test and export default

* fix merge

* not implemented tests

* individual imports

* `receiveMessageOnPort` tests

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
2023-08-02 18:12:12 -07:00
Ashcon Partovi
505e77c2d0 Implement node:diagnostics_channel (#3934)
* Add types for `node:async_hooks`

* Implement \`node:diagnostics_channel\`
2023-08-02 18:04:24 -07:00
Jarred Sumner
ef6d25a48f Fix 2023-08-02 17:55:42 -07:00
dave caruso
c2a77cf7ec Rewrite built-in modules to use CommonJS over ESM (#3814)
* stfdsafsd

sadffdsa

stuff

finish commonjs stuff

asdf

not done but work

not done but work

not done yet but this is how far i am

remove files

lol

update built files

uncomment everything in events lol

export default

stuff

* afdsafsd

* its not perfect but almost done

* okay

* cool

* remove temp file

* finish rebase

* revert settings.json

* a

* ch-ch-ch-ch-changes

* okay

* remove this check in release for now

* sxdcfghnjm,

* lkjhgf

* fmt

* filename can be null

* Update NodeModuleModule.h

* weee

* fmt

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-02 16:27:36 -07:00
Jarred Sumner
7656b4b17e Fixes #3931 (#3933)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-08-02 16:16:22 -07:00
Ciro Spaciari
25553e62c1 Fix path_watcher (#3920)
* fix callback and onError

* fix main watcher error return

* fixup

* rename to be more clear
2023-08-02 13:00:01 -07:00
Vaughan Rouesnel
4f39d5b54a Update streams.md (#3926) 2023-08-02 12:59:21 -07:00
Ciro Spaciari
d9f162ff95 clean declare structs (#3929) 2023-08-02 12:58:44 -07:00
Dylan Conway
9bbac35fd0 close BroadcastChannel in tests 2023-08-01 19:12:30 -07:00
Ciro Spaciari
eba27540b0 Fix some flaky tests (#3919)
* fix some flask tests

* fix condition on prisma test

* oops
2023-08-01 19:06:08 -07:00
Ciro Spaciari
9cb3f3386e Fix expanding on .env files (#3918)
* fix expanding

* refactor locks

* bound checks

* fix comment

* one more test

* oops
2023-08-01 19:04:05 -07:00
Dylan Conway
6c40d6f2f5 add BroadcastChannel (#3922)
* copy and format

* update `SerializedScriptValue.cpp`

* use `expect().fail()` in message channel tests

* rename `BroadcastChannelIdentifier.h`

* copy registries

* progress and tests

* cleanup

* worker and broadcast channel test

* `BroadcastChannel` ref and unref

* `MessagePort` ref, unref, and hasRef

* remove `SecurityContext.cpp/h`

* add types
2023-08-01 18:40:02 -07:00
Dylan Conway
0ced5520e6 Update worker.test.ts 2023-08-01 18:05:11 -07:00
Jarred Sumner
8aa5892f70 Update types 2023-08-01 16:44:16 -07:00
Jarred Sumner
bd2563ef4c Update JSWorker.cpp 2023-08-01 16:43:48 -07:00
Jarred Sumner
214dc039e0 Implement Worker.prototype.threadId 2023-08-01 16:42:49 -07:00
Emilio Sánchez
e2b39d0807 Fix prisma.md typo (#3921) 2023-08-01 12:03:53 -07:00
Vlad Sirenko
7a8f57c4e5 throw error if node module does not exist (#3913) 2023-07-31 19:41:41 -07:00
Colin McDonnell
8589ba2f17 Update stricjs 2023-07-31 17:07:01 -07:00
Colin McDonnell
dd8fdd87dc Switch table to headings in Nodejs compat page 2023-07-31 16:39:09 -07:00
Colin McDonnell
7b8df184b3 Add env guides 2023-07-31 14:24:08 -07:00
Colin McDonnell
90991da908 Update titles, add Workspaces guide 2023-07-31 13:57:17 -07:00
Colin McDonnell
404b90badc Add ecosystem guides (#3847)
* Add ecosystem guides

* Update titles

* Rename stric

* Add unlink and fetch guides

* Add formdata guide

* Tweak title

* Moar
2023-07-31 12:20:23 -07:00
Jarred Sumner
67599f97ad More logging 2023-07-31 06:50:55 -07:00
Jarred Sumner
8b715dee5b Fixes #1669 2023-07-31 06:39:19 -07:00
Jarred Sumner
f2983e50b7 Add a test for TransformStream 2023-07-31 06:17:56 -07:00
Jarred Sumner
e47a448434 Fixes #2935 2023-07-31 06:03:31 -07:00
xxxhussein
de5890ff20 Update arraybuffer-to-buffer.md (#3906)
Fix title. This page shows how to convert an ArrayBuffer to a Buffer, not a Uint8Array
2023-07-31 04:00:21 -07:00
Jarred Sumner
aae92c76a6 Fix incorrect function 2023-07-31 01:33:39 -07:00
Jarred Sumner
9ecae59bbb Fix memory leak in response.clone(), further reduce memory usage of Request & Response (#3902)
* Atomize respsone.url & response.statusText

* Fix warning

* Atomize Request & Response URLs when possible

* Fix memory leak in response.clone()

bun/bench/snippets on  jarred/atomize
❯ mem bun --smol request-response-clone.mjs
cpu: Apple M1 Max
runtime: bun 0.7.2 (arm64-darwin)

benchmark             time (avg)             (min … max)       p75       p99      p995
-------------------------------------------------------- -----------------------------
req.clone().url     77.3 ns/iter  (40.35 ns … 222.64 ns)  91.53 ns 128.11 ns 172.78 ns
resp.clone().url  162.43 ns/iter    (116 ns … 337.77 ns)  177.4 ns 232.38 ns 262.65 ns

Peak memory usage: 60 MB

bun/bench/snippets on  jarred/atomize
❯ mem bun-0.7.1 --smol request-response-clone.mjs
cpu: Apple M1 Max
runtime: bun 0.7.1 (arm64-darwin)

benchmark             time (avg)             (min … max)       p75       p99      p995
-------------------------------------------------------- -----------------------------
req.clone().url   115.85 ns/iter  (80.35 ns … 247.39 ns) 128.19 ns 181.93 ns 207.23 ns
resp.clone().url  252.32 ns/iter  (202.6 ns … 351.07 ns) 266.56 ns 325.88 ns 334.73 ns

Peak memory usage: 1179 MB

* Update tests

* Update js_ast.zig

* Update test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-30 23:51:43 -07:00
audothomas
2ea7290172 FIx Uint8Array to a ReadableStream code snippet (#3895) 2023-07-30 17:53:22 -07:00
Jarred Sumner
092ada6d2f Micro-optimize LineOffsetTable.generate
5.00 ms  100.0%	0 s	 	bun (81023)
2.00 ms   40.0%	2.00 ms	 	 WTF::HashTableAddResult<WTF::HashTableIterator<WTF::HashTable<WTF::Packed<WTF::StringImpl*>, WTF::Packed<WTF::StringImpl*>, WTF::IdentityExtractor, WTF::DefaultHash<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>>, WTF::Packed<WTF::StringImpl*>, WTF::Packed<WTF::StringImpl*>, WTF::IdentityExtractor, WTF::DefaultHash<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>>> WTF::HashTable<WTF::Packed<WTF::StringImpl*>, WTF::Packed<WTF::StringImpl*>, WTF::IdentityExtractor, WTF::DefaultHash<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>, WTF::HashTraits<WTF::Packed<WTF::StringImpl*>>>::addPassingHashCode<WTF::HashSetTranslatorAdapter<WTF::BufferFromStaticDataTranslator<unsigned char>>, WTF::HashTranslatorCharBuffer<unsigned char> const&, WTF::HashTranslatorCharBuffer<unsigned char> const&>(WTF::HashTranslatorCharBuffer<unsigned char> const&, WTF::HashTranslatorCharBuffer<unsigned char> const&)
2.00 ms   40.0%	2.00 ms	 	 heap.StackFallbackAllocator(1024).free
2.00 ms   40.0%	0 s	 	  em.Allocator.rawFree
2.00 ms   40.0%	0 s	 	   em.Allocator.log2a
2.00 ms   40.0%	0 s	 	    em.Allocator.free__anon_1330765
2.00 ms   40.0%	0 s	 	     em.Allocator.resize__anon_1069235
2.00 ms   40.0%	0 s	 	      array_list.ArrayListAligned(i32,null).toOwnedSlice
2023-07-30 08:27:31 -07:00
Jarred Sumner
e636f1b026 skip flay test 2023-07-30 08:26:41 -07:00
Jarred Sumner
54a2d89bd2 Support bun . to run the entry point (#3891)
* Support `bun .`

* Fix tests

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-30 07:54:17 -07:00
Tiramify (A.K. Daniel)
0ea59b4c93 Update install.md (#3890) 2023-07-30 06:41:51 -07:00
Jarred Sumner
b0d3ea5a43 Fix issue with file loader (#3889)
* Fix issue with file loader

* Update jest-extended.test.js

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-30 05:59:54 -07:00
Jarred Sumner
a9dc5d51e3 Fixes #3884 2023-07-30 04:04:06 -07:00
Jarred Sumner
749194378a Bump 2023-07-30 04:04:06 -07:00
Jarred Sumner
794e657eb2 remove unnecessary move 2023-07-30 04:04:06 -07:00
Jarred Sumner
1db119ec11 Fix memory leak (#3887)
* Fix memory leak

* Remove an extra copy

* Further fixes

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-30 02:03:32 -07:00
Ai Hoshino
413fd28120 Fix coredump when reading an empty file(node:stream:createReadStream) (#3882)
* Fix coredump when reading an empty file.
Close: #3607

* It seems that the fd is closed when `auto_close` is true.
2023-07-30 01:18:13 -07:00
Tiramify (A.K. Daniel)
40a9ba6340 Improv. (#3885) 2023-07-30 01:17:02 -07:00
Jarred Sumner
681be10294 Make bun:jsc memoryUsage more accurate (#3876)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-29 06:18:51 -07:00
0xflotus
dccf82b1c6 docs: fixed small errors (#3879)
* Update cache.md

* Update index.md

* Update macros.md

* Update writing.md
2023-07-29 03:58:45 -07:00
0xflotus
5563be99d3 fix: small error (#3878) 2023-07-29 03:32:24 -07:00
Jhorman Tito
bcb6dc7806 typo spawn.md (#3875) 2023-07-29 00:35:13 -07:00
Jarred Sumner
dae2928620 Update nodejs-apis.md 2023-07-28 23:58:59 -07:00
Jarred Sumner
05ef9ec141 Update nodejs-apis.md 2023-07-28 23:57:02 -07:00
Jarred Sumner
53cc4df191 Defer task destruction 2023-07-28 20:34:57 -07:00
Jarred Sumner
05716ff39b Stat largefile test (#3870)
* Add test for stat on a large file

* Update fs.test.ts

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-28 18:55:04 -07:00
Jarred Sumner
4f914cbfe8 Ignore when printing to stdout errors (#3869)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-28 18:53:44 -07:00
Jarred Sumner
da7c1d84e9 Fix bug with /path/to/absolute/bun.lockb 2023-07-28 18:52:04 -07:00
Dylan Conway
aebec5b329 markBinding 2023-07-28 18:07:28 -07:00
Dylan Conway
c68d9ae634 optional parameter 2023-07-28 18:04:00 -07:00
Jarred Sumner
bd66a9a94c Fixes #3868
Fixes #3868
Fixes #849
2023-07-28 17:53:12 -07:00
Jarred Sumner
1490cdc4ff Fix assertion failure and possible infinite loop when printing as yarn lock files 2023-07-28 17:40:05 -07:00
Jarred Sumner
97009a49bd Mark broken test as todo 2023-07-28 16:59:46 -07:00
Dylan Conway
d432448ac8 fix types and add message channel/port gc test 2023-07-28 16:55:49 -07:00
Dylan Conway
d614fdfaac MessageChannel and MessagePort (#3860)
* copy and format

* copy

* copy

* cleanup

* some tests

* spellcheck

* add types

* don't lock getting contextId

* array buffer test
2023-07-28 16:44:28 -07:00
Jarred Sumner
0a4e476a7c mark tests as todo 2023-07-28 16:24:22 -07:00
Vlad Sirenko
9078b1286d add fork to child_process (#3851)
* add fork to child_process

* fix export

* add test to child_process method `fork`

* fmt fork

* remove only from test
2023-07-28 16:00:43 -07:00
Tiramify (A.K. Daniel)
242d8655d8 feat(bun/test): Impl. expect().pass() & expect().fail() (#3843)
* Impl. pass & fail

* fix

* fix 2

* smol
2023-07-28 15:46:44 -07:00
Ai Hoshino
9b91e3c1a2 fix the chunk boundary (node:stream:createReadStream) (#3853)
* fix the slice boundary.
Close: #3668

* Add more boundary test case.

* fix end is 0.
2023-07-28 15:44:33 -07:00
Jarred Sumner
7a1ebec26f Support file: URLs in fetch (#3858)
* Support file: URLs in `fetch`

* Update url.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-28 15:44:05 -07:00
Ciro Spaciari
e7c80b90b8 fix(tls) exposes native canonicalizeIP and fix rootCertificates (#3866)
* exposes native canonicalizeIP

* remove unintended duplicate

* add tests

* add tests for debug builds

* add rootCertificates test and fix len

* just randomize test ids on prisma

* remove work around and bump usockets with the actual fix

* fix case

* bump uws
2023-07-28 15:43:15 -07:00
Jarred Sumner
e110ccf84d Fixes #3795 (#3856)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-28 01:33:00 -07:00
Jarred Sumner
c2a744f0cc Add todo
cc @cirospaciari
2023-07-28 00:34:54 -07:00
Jarred Sumner
38168f3c85 Update pull_request_template.md 2023-07-28 00:17:47 -07:00
Jarred Sumner
cbaab23f6d Update pull_request_template.md 2023-07-28 00:17:26 -07:00
Jarred Sumner
3e5beb1279 Fix bug with // @bun annotation in main thread (#3855)
* Uncomment test

* Fix bug with // @bun + async transpiler

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 22:30:10 -07:00
Jarred Sumner
70b9bf743c Add Bun.isMainThread 2023-07-27 22:28:28 -07:00
Jarred Sumner
f3153fbee9 Uncomment test 2023-07-27 20:46:25 -07:00
Ciro Spaciari
7fa71dd032 Resolve watch directories outside main thread + async iterator and symlink fixes (#3846)
* linux working pending tests with FSEvents

* add more tests, fix async iterator

* remove unnecessary check

* fix macos symlink on directories

* remove indirection layer

* todos

* fixes and some permission test

* fix opsie and make prisma test more reliable

* rebase with main

* add comptime check for macOS

* oops

* oops2

* fix symlinks cascade on FSEvents

* use JSC.WorkPool

* use withResolver, createFIFO and fix close event on async iterator

* remove unused events

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-07-27 19:23:54 -07:00
Jarred Sumner
52f39d728f Update pull_request_template.md 2023-07-27 18:12:11 -07:00
Jarred Sumner
73eb59019a Update pull_request_template.md 2023-07-27 18:11:28 -07:00
Jarred Sumner
3b24305b7c Update pull_request_template.md 2023-07-27 18:10:49 -07:00
Jarred Sumner
1304779826 Update pull_request_template.md 2023-07-27 18:03:44 -07:00
Jarred Sumner
65d0884361 Update pull_request_template.md 2023-07-27 18:01:01 -07:00
Jarred Sumner
16fdc074ca Update pull_request_template.md 2023-07-27 18:00:03 -07:00
Jarred Sumner
6b35fd847f Create pull_request_template.md 2023-07-27 17:56:11 -07:00
Jarred Sumner
007f357495 Make readFile() async (#3850)
* less leaky

* async readfile

* Update types.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 16:55:49 -07:00
Jarred Sumner
16a7224ce5 Fix hot reloading in canary (#3848)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 15:52:52 -07:00
Jarred Sumner
7c44773f38 Outdated copy 2023-07-27 15:22:53 -07:00
Jarred Sumner
85895bd248 Use putDirectIndex instead of initializeIndex (#3839)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 14:45:32 -07:00
Luigi Pinca
6c2ec2868f Remove no longer needed flag from benchmark documentation (#3845)
`Deno.serve()` was stabilized in version 1.35.0.
2023-07-27 13:27:54 -07:00
Jarred Sumner
704ee13392 Make readdir() async, fix crash in large directory trees (#3838)
* Fix unsafe GC behavior on large arrays returned by fs

* Fix crash in large arrays of strings

* async readdir

* Add tests for large number of files returned by readdir

* Move this down

* Fix encoding edgecase in path.join

* Async stat & lstat

* add test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 04:27:09 -07:00
Jarred Sumner
d7aebc2222 Remove lstat call in fs.watch (#3836)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-27 03:34:18 -07:00
Jarred Sumner
dc0d767f27 Enable Promise.withResolvers()
https://github.com/tc39/proposal-promise-with-resolvers

Thanks @dcrousso
2023-07-26 23:52:57 -07:00
Jarred Sumner
86633e0af4 Start time performance improvements to build tools (#3797)
* Make os.cpus() faster on Linux

* Fix crash

See https://github.com/ziglang/zig/issues/16540

* Handle watcher_count == 0

* Add assertion

* Clean up lifetimes of fs watcher a little

* ✂️

* Use `errdefer`

* Make the error better

* Make os.cpus() more lazy

* Please don't translate-c on the entire C standard library

* immediately closing works correctly is still bug

* ops

* fmt+fixeup

* add back verbose

* free instead of destroy

* remove destroy option for watcher tasks

* flush verbose and add debug log

* fixup files

* use log for debug

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: cirospaciari <ciro.spaciari@gmail.com>
2023-07-26 21:35:49 -07:00
Jarred Sumner
ec2cf38ad8 [fetch] Ignore invalid Content-Encoding header (#3834)
Fixes #3802

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-26 20:24:36 -07:00
Colin McDonnell
34fd4df646 Fix broken anchors 2023-07-26 17:11:15 -07:00
Jarred Sumner
a6d54e5949 Update macro-test.test.ts 2023-07-26 16:56:26 -07:00
Jarred Sumner
664ccec7d3 Disable concurrent transpiler in macros 2023-07-26 16:54:36 -07:00
Dylan Conway
1a558ef753 fix decorator and declare (#3828)
* return the prop if there are decorators

* test and comment
2023-07-26 16:31:08 -07:00
Jarred Sumner
f3200ac0ca Don't hoist bun plugin in concurrent transpiler 2023-07-26 16:06:04 -07:00
Jarred Sumner
011b50589c Concurrent Transpiler (#3816)
* Concurrent Transpiler

* Fix bug with some improts and add jsc alias

* Some comments

* Fix crash

* Update module_loader.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-26 15:36:05 -07:00
Alex Lam S.L
06503663b1 [install] handle workspace:[alias@]range (#3819) 2023-07-26 15:35:47 -07:00
Colin McDonnell
4c89c60867 Add files (#3826) 2023-07-26 14:59:39 -07:00
Colin McDonnell
6bfee02301 Fix typo 2023-07-25 12:27:27 -07:00
Ai Hoshino
0297cb1527 fix the encoding of dirname's return value. (#3799) 2023-07-25 05:49:48 -07:00
Jarred Sumner
4209703b35 Make this other name better 2023-07-25 02:08:51 -07:00
Jarred Sumner
8edeb617a8 Make this name better 2023-07-25 02:08:23 -07:00
Ai Hoshino
130079b558 fix some cases in the dirname function. (#3785)
Close: #3782
2023-07-25 00:41:22 -07:00
Jarred Sumner
8356830727 Trace printing at runtime 2023-07-24 22:00:43 -07:00
Jarred Sumner
5edb756533 Trace module resolution 2023-07-24 21:59:50 -07:00
Jarred Sumner
e402159df1 test gardening 2023-07-24 19:36:53 -07:00
dave caruso
8a0152e129 Merge import.meta.require and require to be the same thing (#3732)
* Merge import.meta.require and require to be the same thing

* support `require` and BunPlugin (runtime plugin)

* plugins

* unused code

* revert launch.json
2023-07-24 19:32:04 -07:00
Jarred Sumner
1f1d0bfcfb Make this test less flaky 2023-07-24 19:18:07 -07:00
Jarred Sumner
4ebf858f43 Less flaky 2023-07-24 19:14:41 -07:00
Jarred Sumner
90ce74a43e Skip test 2023-07-24 19:13:25 -07:00
Jarred Sumner
e1a59d355a slow test is allowed to be slow 2023-07-24 19:11:53 -07:00
Dylan Conway
e154763e4d fix rope string push (#3796)
* push to next next

* couple more tests

* end
2023-07-24 19:08:56 -07:00
Jarred Sumner
ac10a1b633 move this to troubleshooting 2023-07-24 17:16:34 -07:00
Alex Lam S.L
961312eab0 [install] fix workspace override of aliased npm dependency (#3784) 2023-07-24 17:01:43 -07:00
Jarred Sumner
6ca50526d7 bun:sqlite gets 10% faster (#3780)
* bun:sqlite gets 10% faster

❯ bun-debug bun.js # After
[0.03ms] ".env"
cpu: Apple M1 Max
runtime: bun 0.7.1_debug (arm64-darwin)

benchmark                        time (avg)             (min … max)       p75       p99      p995
------------------------------------------------------------------- -----------------------------
SELECT * FROM "Order"         13.65 ms/iter   (12.79 ms … 15.41 ms)  13.69 ms  15.41 ms  15.41 ms
SELECT * FROM "Product"       31.02 µs/iter    (27.08 µs … 1.33 ms)  30.33 µs  42.33 µs  45.25 µs
SELECT * FROM "OrderDetail"   140.2 ms/iter (127.97 ms … 172.31 ms) 144.02 ms 172.31 ms 172.31 ms

bun/bench/sqlite on  jarred/faster-sqlite took 5s
❯ bun bun.js # Before
[0.52ms] ".env"
cpu: Apple M1 Max
runtime: bun 0.7.1 (arm64-darwin)

benchmark                        time (avg)             (min … max)       p75       p99      p995
------------------------------------------------------------------- -----------------------------
SELECT * FROM "Order"         15.44 ms/iter   (14.36 ms … 17.94 ms)  15.59 ms  17.94 ms  17.94 ms
SELECT * FROM "Product"       36.89 µs/iter    (31.54 µs … 3.18 ms)  37.25 µs  49.75 µs  54.88 µs
SELECT * FROM "OrderDetail"  156.63 ms/iter (151.68 ms … 175.93 ms) 157.63 ms 175.93 ms 175.93 ms

* Handle empty just incase

* GCDeferral scope is unnecessary

* Make this code more careful

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-24 17:01:21 -07:00
Colin McDonnell
31976f6af1 Update install method order 2023-07-24 14:40:13 -07:00
Jarred Sumner
967ccb5d50 Upgrade WebKit (#3777)
* Upgrade to latest WebKit

* Upgrade WebKit

* hm

* Fix failing tests

* Delete utf8-encoding-fixture.bin.cmp

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-23 22:37:48 -07:00
Alex Lam S.L
d8135e85ca more tests for #3754 (#3774) 2023-07-23 21:19:10 -07:00
Jarred Sumner
b02f097f4d Fix bugs with connecting to localhost (#3758)
* Fix bugs with connecting to localhost

* Update uws

* More logs

* Allow not setting a hostname

* Make server.hostname & server.protocol faster

* Fixup

* normalize listening host

* Fix test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-23 05:13:48 -07:00
Jarred Sumner
4e852918a3 Raise redirect limit in bundler 2023-07-23 03:59:43 -07:00
Jarred Sumner
c76516fa38 Fixes #3764 2023-07-23 03:58:10 -07:00
Alexander Trefz
ce77266cc5 Update nodejs-apis.md (#3762)
`structuredClone` is implemented as of v0.7
2023-07-23 03:40:46 -07:00
Artur Androsovych
ce9bba9dd5 Update development.md (#3718)
* Update `development.md`

* Update `development.md`
2023-07-22 22:24:59 -07:00
Jarred Sumner
e2e44661c2 Explicitly ref/unref blobs before extracting the value (#3755)
* Explicitly ref/unref blobs before extracting the value

* ✂️

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-22 22:20:10 -07:00
Jarred Sumner
601fd3ead5 in Bun.write(), defer creating the Promise until we're just about to schedule the task 2023-07-22 20:49:35 -07:00
Alex Lam S.L
07e08b086a [install] improve workspace substitution of npm dependencies (#3754)
- respect semver ranges
2023-07-22 20:05:24 -07:00
Jarred Sumner
53eb126898 ref() before creating the JSPromise 2023-07-22 19:56:39 -07:00
Jarred Sumner
6809d08a90 Make zig build obj fail a little later when src/runtime.out.js or src/fallback/out.js doesn't exist 2023-07-22 19:35:00 -07:00
Jarred Sumner
6402967b6d bump! 2023-07-22 17:08:31 -07:00
Jarred Sumner
bfaf095c2e Fixes https://discord.com/channels/876711213126520882/1131175053409656833/1131175053409656833
@tr1ckydev this fixes the issue you ran into, see the diff for an example usage of a Bun.plugin that makes a network request on import.
2023-07-22 16:59:54 -07:00
dave caruso
b17b61b8c6 fix path.format for vite build (#3734)
* fix path.format for vite

* Update path.test.js

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-22 16:45:45 -07:00
Jarred Sumner
27c88c8046 Fixes #3753 2023-07-22 16:42:17 -07:00
Ai Hoshino
04d19d6f6a Fix writeFileSync when the mode is greater than 0o777. (#3747)
Close: #3740
2023-07-22 07:10:36 -07:00
Jarred Sumner
3418feb2e9 Fixes #3744 2023-07-22 04:33:54 -07:00
Jarred Sumner
c6a3467625 Unified event loop (#3741)
* Unified event loop

* Update WebKit, add test for es-module-lexer

* Update README.md

* Use async wasm

* Explicitly set whether concurrenttask should be deinit'd

* Update package.json

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-22 04:31:58 -07:00
Jarred Sumner
636cec03e1 Use WebKit's URL parser in fetch() and bun install (#3730)
* Use WebKit's URL parser in fetch() and `bun install`

* Allocate less memory

* Fix test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-21 23:27:28 -07:00
Ai Hoshino
1ecd9f8a18 handle latin1 in Bun__encoding__toString. (#3739)
Close: #3738
2023-07-21 22:01:26 -07:00
Dylan Conway
2323f5d08d fix #3716 (#3733)
* don't break on comments for process env variables

* break for `\r` and `\n`

* don't parse process env vars
2023-07-21 20:33:15 -07:00
Alex Lam S.L
311dffc690 improve test (#3731)
- minor build diffs
2023-07-22 02:42:30 +03:00
Ciro Spaciari
c4f062dbf4 clean tables before testing (#3721)
* clean tables before testing

* typo
2023-07-21 16:13:04 -07:00
Vaughan Rouesnel
7ac94e5b4c Typo in loaders.md (#3728) 2023-07-21 15:43:34 -07:00
Dylan Conway
aa1ad7f009 string escape edgecase (#3717)
* fix edgecase when joining rope strings with backtick

* bonus bugfix in ts decorator

* Update transpiler.test.js

* Fix test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-07-21 01:35:06 -07:00
Dylan Conway
21bb3b2bdd fix isFIFO (#3715)
* check poll ref flags

* Update WebCoreJSBuiltins.cpp
2023-07-21 00:18:15 -07:00
Jarred Sumner
cd49615e2c fix flaky test
@paperdave we must always use `bunEnv` in the `env` to ensure that the color settings and other stuff doesn't cause bun to produce extraneous stdout input when using console.log

Additionally, the console.log was left in (which is okay)
2023-07-20 21:45:05 -07:00
Jarred Sumner
eb37794a3b Bump 2023-07-20 21:34:42 -07:00
Jarred Sumner
da298635ef Bump 2023-07-20 21:22:49 -07:00
Dylan Conway
218958dbd1 Update async_hooks.node.test.ts 2023-07-20 21:13:11 -07:00
Jarred Sumner
1c6e464a68 bump 2023-07-20 21:08:42 -07:00
dave caruso
9c85465a58 fix process.exit status code handling (#3714) 2023-07-20 19:16:56 -07:00
Jarred Sumner
2eb79afb2a Update sqlite.md 2023-07-20 18:14:34 -07:00
dave caruso
020cf46346 Fix builtins again (#3713) 2023-07-20 17:33:40 -07:00
dave caruso
134c97a282 fix directory caching with workaround (#3710)
* ok

* test
2023-07-20 16:44:43 -07:00
dave caruso
e2c11c4856 fix process.binding (#3711) 2023-07-20 16:25:02 -07:00
Dylan Conway
9ad330d917 Update process.test.js 2023-07-20 15:32:20 -07:00
Jarred Sumner
ef89f03de6 Update text-decoder.test.js 2023-07-20 15:26:06 -07:00
Julian
c383c6cd81 Pass constructor arguments to TextDecoder (#3692)
* Make TextDecoder constructor use options parameter

The constructor now actually sets TextDecoder properties using the
options parameter.

* Defer decoder allocation to end of constructor

* Verify types of TextDecoder options

* TextDecoder throw TypeError on failure

* Tidying
2023-07-20 14:50:54 -07:00
Dylan Conway
68b4a64569 resolveRopeIfNeeded (#3708) 2023-07-20 14:50:23 -07:00
Dylan Conway
8e12999917 set _preload_modules to empty array (#3709) 2023-07-20 14:50:13 -07:00
Jarred Sumner
73e44e16ea Update Dockerfile 2023-07-20 14:49:57 -07:00
Ciro Spaciari
99da0ae54b fix start delay on Worker (#3707)
* fix start delay on Worker

* fmt

* add delay test
2023-07-20 14:49:10 -07:00
Colin McDonnell
4686f5395e Add number types for FFI (#3706) 2023-07-20 11:52:45 -07:00
Jarred Sumner
2dc90f3908 Update worker.test-d.ts 2023-07-19 23:59:37 -07:00
Colin McDonnell
53ad9b922f Docs & types for 0.7 (#3665)
* Docs & types for 0.7

* Tweak

* Update

* Tweaks

* Tweak

* Tweaks

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-07-19 23:59:15 -07:00
Jarred Sumner
0b365781a8 Bump version to Bun v0.7.0 2023-07-19 23:57:41 -07:00
Jarred Sumner
dd46c11273 Support streams in response.formData() & request.formData, introduce Bun.readableStreamToFormData() (#3697)
* codegen

* FormData.from

* Fixes #3225

* Introduce `Bun.readableStreamToFormData`

* Update bun.d.ts

* Add examples

* add

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-19 23:12:06 -07:00
Jarred Sumner
8a13e02473 Fixes #3670 (#3698)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-19 23:04:07 -07:00
Jarred Sumner
ed8be46a7b Inlinebun object from workers 2023-07-19 22:53:28 -07:00
dave caruso
36866c4d79 Fix vite (#3694)
* Fix ServerWebSocket.readyState

* Add create_hash_table to our repo

* Fix #3216
2023-07-19 19:28:53 -07:00
dave caruso
dd58508684 Fix browser bundled string_decoder (#3693)
* Fix #3660

* doc fix
2023-07-19 17:37:20 -07:00
dave caruso
9b6dc49575 Implement AsyncLocalStorage (#3089)
* work to get async local storage working.

* a

* a

* everything but queueMicrotask

* sdfghj

* .

* finish

* tests

* test

* ok

* done

* im so stupid

* Upgrade WebKit

* refactor

* refactor

* changes requested

* oops

* cool

* fix runInAsyncScope
2023-07-19 17:20:00 -07:00
Jarred Sumner
723e9d1ea7 Fix make headers 2023-07-19 16:05:43 -07:00
Ciro Spaciari
f63398ffe4 update root certificates and add tls.rootCertificates (#3688)
* implement tls.rootCertificates

* add test

* bump uws/usockets

* bump uws + .len on certs
2023-07-19 16:02:29 -07:00
Ciro Spaciari
2fbf73535c fix createDecipheriv (#3680)
* fix createDecipheriv

* fix createDecipheriv iv and password validations
2023-07-19 16:01:36 -07:00
dave caruso
ebbbd63ed6 fix #3681 (#3690) 2023-07-19 15:58:07 -07:00
Dylan Conway
bc28ec39cf set did_panic flag (#3687) 2023-07-19 15:39:15 -07:00
Ciro Spaciari
568cadb51e move constants module to cpp (#3683) 2023-07-19 15:39:02 -07:00
Dylan Conway
0dbcb84cbe fix make headers 2023-07-19 15:26:14 -07:00
Jarred Sumner
d74d95d9ab Better error for workspace dependency not found (#3678) 2023-07-20 00:08:52 +03:00
Jarred Sumner
a59ddb131e Fix crash in postMessage that repro'd after ~100,000 messages 2023-07-18 23:09:39 -07:00
Jarred Sumner
8bd2b784a2 more progress on fixing gc issue 2023-07-18 20:49:11 -07:00
Dylan Conway
f494e1b50d add padding bytes 2023-07-18 16:30:58 -07:00
Ciro Spaciari
112f01ca61 feature(constants) add constants/node:constants module and tests(prisma) use prima 5.0.0 + use same connection for postgres, add prisma mssql (disabled for now) (#3672)
* use prima 5.0.0 + use same connection for postgres

* change mongodb test URL

* constants module + mssql prisma test (disabled)
2023-07-18 16:09:18 -07:00
Ciro Spaciari
49231b2cb9 patch checkServerIdentity (#3671) 2023-07-18 16:03:05 -07:00
Jarred Sumner
0179ebcb8c Update workers.md 2023-07-18 05:00:09 -07:00
Alex Lam S.L
1790357021 [jest] execute lifecycle hooks on empty blocks (#3663)
fixes #3494
2023-07-18 04:54:24 -07:00
Jarred Sumner
105919d7ae Clarify 2023-07-18 04:51:29 -07:00
Jarred Sumner
777ee4ecec Fixes #3669 2023-07-18 04:35:04 -07:00
Dylan Conway
661355546a zig upgrade (#3667)
* upgrade

* more fixes

* Bump Zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-18 01:20:20 -07:00
Jarred Sumner
71f1aa1802 Enable postgres prisma test 2023-07-17 23:17:06 -07:00
Jarred Sumner
eaff66b098 Emit writeBarrier in napi_module_register 2023-07-17 23:07:09 -07:00
Jarred Sumner
b760d1da30 Fix potential crash in process.dlopen() 2023-07-17 23:02:33 -07:00
Jarred Sumner
728c8fdcdb Implement process.{stdout, stderr}.{columns, rows, getWindowSize} 2023-07-17 21:21:43 -07:00
Ciro Spaciari
13b54fbdb8 [tls] General compatibility improvements (#3596)
* wip

* subjectaltname

* more progress

* bindings

* fmt

* getCert/getPeerCertificate

* fix checkServerIdentity

* fix checkServerIdentity

* add a lot of TLSSocket functions

* getEphemeralKeyInfo fix and comment

* add alternative for getEphemeralKeyInfo

* add get session and set session

* fix isSessionReused

* get back the raw data for MSSQL

* fixeup

* fixup getSession + tests

* fix doc + fmt

* getFinished/getPeerFinished

* codegen

* fixup

* revert webkit

* more fixes

* ssl helper + revert test oops

* asserts
2023-07-17 19:39:09 -07:00
Dylan Conway
9273e29f0e package json main field extension order (#3664) 2023-07-17 19:26:33 -07:00
Alex Lam S.L
9f031b3642 [install] handle duplicated workspace declarations gracefully (#3662)
fixes #3644
2023-07-17 16:06:31 -07:00
Colin McDonnell
ca3b7fa3c9 Clean up worker docs 2023-07-17 13:10:22 -07:00
Colin McDonnell
8a176913d8 Tweak test docs 2023-07-17 11:42:13 -07:00
Alex Lam S.L
570a44d73a workaround readable-stream compatibility (#3626)
- update `bun link` tests
- update `tests/bun.lockb`
- drop unused import in test
2023-07-17 20:05:01 +03:00
Jarred SUmner
5218a33fb6 Fix flaky process test 2023-07-17 04:51:26 -07:00
Jarred Sumner
58824ea743 Fix test with incorrect text 2023-07-17 04:44:56 -07:00
Jarred Sumner
99de971359 Fix incorrect name 2023-07-17 04:21:00 -07:00
Jarred Sumner
55b5aa3571 Fix speculative crashes in console.log(formData) and console.log(headers) 2023-07-17 04:18:43 -07:00
Jarred Sumner
6ca20424d6 Fix crash in console.log(urlSearchParams) on a URLSearchParams object with a lot of keys 2023-07-17 04:18:43 -07:00
Jarred Sumner
36a25c3580 Fix memory leak in await new Response(latin1String).arrayBuffer() and await Response.json(obj).json() (#3656)
❯ mem bun --smol response-arrayBuffer.mjs
cpu: Apple M1 Max
runtime: bun 0.6.15 (arm64-darwin)

benchmark                                                        time (avg)             (min … max)       p75       p99      p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1)    12.9 µs/iter      (625 ns … 4.18 ms)      1 µs 567.17 µs 711.79 µs
new Response().arrayBuffer() (new string each call, utf16)    12.85 µs/iter     (1.67 µs … 1.56 ms)   2.17 µs 462.75 µs 621.13 µs
new Response().arrayBuffer() (existing string, latin1)         6.53 µs/iter     (6.21 µs … 7.07 µs)   6.64 µs   7.07 µs   7.07 µs

Peak memory usage: 49 MB

bun on  jarred/memory-leak-fix took 2s
❯ mem bun response-arrayBuffer.mjs
cpu: Apple M1 Max
runtime: bun 0.6.15 (arm64-darwin)

benchmark                                                        time (avg)             (min … max)       p75       p99      p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1)     1.2 µs/iter     (1.04 µs … 1.42 µs)   1.22 µs   1.42 µs   1.42 µs
new Response().arrayBuffer() (new string each call, utf16)     2.74 µs/iter     (2.42 µs … 6.37 µs)   2.68 µs   6.37 µs   6.37 µs
new Response().arrayBuffer() (existing string, latin1)       746.37 ns/iter   (643.82 ns … 1.04 µs) 776.11 ns   1.04 µs   1.04 µs

Peak memory usage: 104 MB

bun on  jarred/memory-leak-fix took 2s
❯ mem ~/.bun/bin/bun response-arrayBuffer.mjs
cpu: Apple M1 Max
runtime: bun 0.6.15 (arm64-darwin)

benchmark                                                        time (avg)             (min … max)       p75       p99      p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1)    1.69 µs/iter      (1.56 µs … 2.1 µs)   1.73 µs    2.1 µs    2.1 µs
new Response().arrayBuffer() (new string each call, utf16)     2.65 µs/iter     (2.47 µs … 3.17 µs)   2.69 µs   3.17 µs   3.17 µs
new Response().arrayBuffer() (existing string, latin1)       667.67 ns/iter   (547.67 ns … 1.28 µs) 694.21 ns   1.28 µs   1.28 µs

Peak memory usage: 2735 MB

bun on  jarred/memory-leak-fix took 2s
❯ mem ~/.bun/bin/bun --smol response-arrayBuffer.mjs
cpu: Apple M1 Max
runtime: bun 0.6.15 (arm64-darwin)

benchmark                                                        time (avg)             (min … max)       p75       p99      p995
--------------------------------------------------------------------------------------------------- -----------------------------
new Response().arrayBuffer() (new string each call, latin1)   13.51 µs/iter       (541 ns … 3.2 ms)   1.92 µs 553.42 µs 709.92 µs
new Response().arrayBuffer() (new string each call, utf16)    13.07 µs/iter     (1.71 µs … 3.43 ms)   2.13 µs 451.21 µs 651.67 µs
new Response().arrayBuffer() (existing string, latin1)         6.25 µs/iter     (5.79 µs … 6.81 µs)    6.4 µs   6.81 µs   6.81 µs

Peak memory usage: 292 MB

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-17 04:15:13 -07:00
Jarred Sumner
13b5d9d4de 20% faster deserialize (#3655)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-17 02:22:00 -07:00
Jarred Sumner
fa4db1de42 Document --smol 2023-07-16 23:24:00 -07:00
Jarred Sumner
2a02f3d669 Add --smol to bunfig 2023-07-16 23:23:33 -07:00
Jarred Sumner
75213aad37 Document serialize/deserialize 2023-07-16 23:16:54 -07:00
Jarred Sumner
5856639833 Add serialize snippet 2023-07-16 23:16:38 -07:00
Jarred Sumner
edeb3b48e8 Fix test 2023-07-16 22:46:06 -07:00
Jarred Sumner
3613429dc3 Update workers.md 2023-07-16 22:43:38 -07:00
Jarred Sumner
7917ebd58f Fixes base64url encoding for crypto (#3654)
* Fixes base64url encoding for crypto

* 🍏

* Update nodejs-apis.md

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-16 22:42:19 -07:00
Jarred Sumner
a86d00c672 Update nav.ts 2023-07-16 21:43:22 -07:00
Jarred Sumner
d5c51092c8 rename 2023-07-16 21:40:07 -07:00
Jarred Sumner
6a234e6fce Add structuredClone microbenchmark 2023-07-16 21:17:55 -07:00
Jarred Sumner
dc766eb18a Add --smol flag 2023-07-16 21:17:47 -07:00
Jarred Sumner
209dc981c0 Implement Workers (#3645)
* copy files

* format

* options

* Introduce `Worker`, `onmessage`, `onerror`, and `postMessage` globals

* Stub `Worker.prototype.ref` & `Worker.prototype.unref`

* Update web_worker.zig

* Worker works

* Add "mini" mode

* add wakeup

* Partially fix the keep-alive issue

* clean up refer behavior

* Implement `serialize` & `deserialize` in `bun:jsc` & add polyfill for `node:v8`

* Types & docs

* Update globals.d.ts

* Add mutex

* Fixes

---------

Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-16 21:15:24 -07:00
Jarred Sumner
7fc392b182 Support napi_wrap in constructors (#3614)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-16 20:32:33 -07:00
Jarred Sumner
6baa08313c Fixes #3641 (#3643)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-16 20:32:18 -07:00
Jiri Spac
131ed06020 docs: add one missing line in typescript.md (#3650) 2023-07-16 20:31:54 -07:00
Dylan Conway
e546e4064c structuredClone types 2023-07-14 19:49:15 -07:00
Dylan Conway
c39c11e101 structured clone (#3637)
* copy `SerializedScriptValue`

* format

* make `SerializedScriptValue` compile

* add `transfer` option

* tests

* serialize/deserialize blobs

* tests for blobs

* serialize/deserialize file blobs

* more tests

* small cleanup

* format

* small changes + serialize offset

* slice helper

* map and set test
2023-07-14 19:37:22 -07:00
Colin McDonnell
2551210426 Update docs 2023-07-14 11:33:07 -07:00
Colin McDonnell
43abf2629f Remove fdatasync from types 2023-07-13 17:48:46 -07:00
Colin McDonnell
325147261f Update docs/types for process (#3631)
* Update docs/types for process

* Tweaks

* Tweaks

* Fix types
2023-07-13 17:40:46 -07:00
Tiramify (A.K. Daniel)
044b09afc2 Impl. fix (#3630) 2023-07-13 14:29:24 -07:00
Ashcon Partovi
9eb8eea2a8 Implement ping(), pong(), terminate() for WebSocket client and server (#3257) 2023-07-13 09:39:43 -07:00
Jarred Sumner
04b4157232 Fixes #3629 2023-07-13 02:57:25 -07:00
Jarred Sumner
a02a79e26c Bump WebKit 2023-07-12 20:48:52 -07:00
dave caruso
ae0a724981 Improve our internal typedefs (#3608)
* types

* some more

* yeah

* i think that fixes it

* oop
2023-07-12 15:21:55 -07:00
Tiramify (A.K. Daniel)
0631f87866 feat(bun/test): Implement "bail" option for "bun test" (#3253)
* Implement bun test --bail

* Fixes

* move printSummary() (more readable)

* Fixes 2

* idk why it got deleted

* Fixes 3

* fmt this better

* Update test_command.zig

* Fix "0 files"

* track number of files so bailing out early prints the right number

---------

Co-authored-by: dave caruso <me@paperdave.net>
2023-07-12 13:41:46 -07:00
Jarred Sumner
4e1a81231c Update build-id 2023-07-12 01:37:08 -07:00
Jarred Sumner
b566573977 Fix another crash in Error.captureStackTrace (#3611)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-11 21:01:35 -07:00
Jarred SUmner
666feb3b7e Fix crash on linux when throwing SystemError from C++ 2023-07-11 20:52:10 -07:00
Jarred Sumner
5ea32a976e Update process.test.js 2023-07-11 19:49:41 -07:00
Jarred Sumner
34b0e7a2bb Update ZigGlobalObject.cpp 2023-07-11 19:06:49 -07:00
Jarred Sumner
c5f2280489 Implement process.kill and process._kill 2023-07-11 19:06:01 -07:00
Jarred Sumner
a686b3bfc1 Fixes #3595 2023-07-11 19:00:51 -07:00
dave caruso
a1fb289c96 typo (#3610) 2023-07-11 18:50:34 -07:00
Dylan Conway
8ca2194a37 fix #3597 (#3609)
* fix #3597

* Update http.ts

* initialize to true
2023-07-11 18:49:35 -07:00
Jarred Sumner
03904f73cc Merge branch 'jarred/throw-if' 2023-07-11 17:48:52 -07:00
Jarred Sumner
2106e1d7f6 Tests 2023-07-11 17:48:13 -07:00
Jarred Sumner
854ddaa909 Implement throwIfNoEntry 2023-07-11 17:44:29 -07:00
Colin McDonnell
609f81a746 Add npmrc note 2023-07-11 15:32:52 -07:00
Jarred Sumner
fd4c8fb871 Merge branch 'jarred/fix-http-compression' 2023-07-11 13:09:37 -07:00
Jarred Sumner
bab58b7541 Avoid Object.getPrototypeOf 2023-07-11 13:07:03 -07:00
Dylan Conway
5c8726d602 process signal events (#3569)
* signal events

* simple tests

* ignore SIGSTOP

* better tests

* use `EventEmitter`

* use `Bun__getDefaultGlobal`

* progress

* don't use 'Bun__getDefaultGlobal`

* fix tests

* remove signals from map

* update tests

* don't overwrite event emitter methods

* avoid two lookups

* use `std::once`

* releaseEarly()

* Remove signal handler after use

* Update call-raise.js

* Create process-signal-handler.fixture.js

* Don't register duplicates

* Add missing lock

* another test

* update test

* revert some changes

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-11 12:48:46 -07:00
Dylan Conway
ae7bc37e94 fix iterating stack trace (#3600)
* `i + 1` and remove `defer`

* a test

* fix test
2023-07-11 12:48:32 -07:00
dave caruso
31ab56d362 Fix: console.log with class constructors (#3602)
* Fix console.log with class constructors

* oops

* fix it

* lol

* fix test
2023-07-11 12:48:19 -07:00
simylein
4b333b2d35 docs(sqlite): database prepare types reflect runtime (#3599)
* docs(sqlite): database prepare types reflect runtime

* Update sqlite.d.ts

---------

Co-authored-by: Ashcon Partovi <ashcon@partovi.net>
2023-07-11 09:09:06 -07:00
Hanaasagi
c4c5eb2d32 use Object.getPrototypeOf 2023-07-11 21:31:49 +09:00
Ai Hoshino
e7afae305c Merge branch 'main' into fix-http 2023-07-11 19:35:11 +08:00
Hanaasagi
17031936c8 small fix, check if the method has been reassigned. 2023-07-11 20:32:09 +09:00
dave caruso
b2c576bba2 fix "readable" event being emitted incorrectly (#3475)
* fix "readable" event being emitted incorrectly

* fix impl and add test

* changes

* asdfghj

* esm
2023-07-10 18:25:20 -07:00
Ciro Spaciari
4af4b508a1 feat(crypto) add getCurves (#3598)
* add getCurves

* add nodefallbacks

* update docs

* oops
2023-07-10 17:14:37 -07:00
Hanaasagi
0c2df4ae01 ignore check 2023-07-10 22:33:07 +09:00
Ai Hoshino
cc0d920018 Merge branch 'main' into fix-http 2023-07-10 21:12:00 +08:00
Hanaasagi
438d54f186 add tests 2023-07-10 22:04:39 +09:00
Hanaasagi
c6e1135548 call writeHead before send headers
Close: #3585
2023-07-10 21:35:10 +09:00
Jarred Sumner
ec11170311 Fixes #3588 (#3590)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-10 02:21:03 -07:00
Jarred Sumner
538bcef731 Update globals.d.ts 2023-07-10 01:33:46 -07:00
Jarred Sumner
93b0e94410 trim node:stream a little 2023-07-10 01:26:02 -07:00
Jarred Sumner
963d4311e6 Fixes #3530 (#3587)
* Fixes #3530

* Handle OOM

* Add test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-09 22:36:24 -07:00
Jarred Sumner
2f5e4fffe9 Implement process.memoryUsage() and process.cpuUsage() (#3586)
* Implement process.memoryUsage() and process.cpuUsage()

* Avoid mi_process_info

* Update bench

* Update Process.cpp

* fixup

* More tests + linux fixup

* Skip it for now since it seems less accurate

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-09 21:50:19 -07:00
Jarred Sumner
ca42c820d2 Implement nearly all of process object methods and properties (#3581)
* Add special case

* Make process object load faster

* Fix openStdin

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-09 16:33:49 -07:00
Ai Hoshino
565d1689e9 fix metadata bits of uuid (randomUUID()) (#3583)
* fix uuid version
Close: https://github.com/oven-sh/bun/issues/3575

* add unittest

* small fix

* avoid unnecessary copying
2023-07-09 07:20:52 -07:00
Jarred Sumner
59570fe237 Handle case with TS decorators and export default anonymous class (#3578)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-08 17:41:24 -07:00
Jarred Sumner
aa8b832ef6 Implement process.on("beforeExit", cb) and process.on("exit", cb) (#3576)
* Support `process.on('beforeExit')` and `process.on('exit')`

* [bun:sqlite] Always call sqlite3_close on exit

* Update process.test.js

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-08 14:26:19 -07:00
Jarred Sumner
fa632c3331 Fix bug with decorators not being generated in export default class (#3577)
* Fix bug with decorators not being generated in `export default class`

* Update decorator-export-default-class-fixture.ts

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-08 04:00:55 -07:00
Jarred Sumner
5846ad00ed Add assertion 2023-07-07 22:01:58 -07:00
Jarred Sumner
e26d3821ce Update settings.json 2023-07-07 22:01:43 -07:00
Jarred Sumner
fceacea37c Unmark as TODO 2023-07-07 22:01:02 -07:00
Jarred Sumner
52b7962dae Use BunString in JSBundlerPlugin (#3557)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-07 21:20:30 -07:00
Jarred Sumner
386d8b7836 Update test 2023-07-07 21:20:16 -07:00
Jarred Sumner
67ee498861 Fix potential coercion issue (#3558)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-07 20:12:39 -07:00
Artur Androsovych
42eacaf3a9 Update installation guide in development.md (#3532)
* Update installation guide in `development.md`

* Updates

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2023-07-07 16:24:07 -07:00
Ai Hoshino
c0cf7b4501 fix decoding invalid UTF-8 input (#3563)
* fix decoding invalid UTF-8 input
Close: https://github.com/oven-sh/bun/issues/3562

* add unittest
2023-07-07 15:10:49 -07:00
Colin McDonnell
affd06d05c Update types, partially fix typecheck (#3551)
* Update types

* Remove caret
2023-07-07 15:10:33 -07:00
Jarred Sumner
7ab8d832fb Add obscure HTTP methods (#3553)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-07 00:38:18 -07:00
Jarred Sumner
0ecdbf4793 [node:fs] read, write - support large numbers and BigInt (#3556)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-07 00:33:43 -07:00
Jarred Sumner
284aaec3cd Remove unnecessary @setRuntimeSafety(false) 2023-07-06 23:50:32 -07:00
Dylan Conway
9bebb7f03d add [dir] to default 2023-07-06 20:51:41 -07:00
Jarred Sumner
5c0a5646cd Update list 2023-07-06 17:11:01 -07:00
Jarred Sumner
4d2c86fd5c Add util.toUSVString 2023-07-06 17:08:01 -07:00
Jarred Sumner
d905dbe214 Minify zlib because its huge 2023-07-06 16:50:03 -07:00
Jarred Sumner
038ca83004 Add missing export in url 2023-07-06 16:49:41 -07:00
Colin McDonnell
d377265b67 Update trustedDeps doc 2023-07-06 15:44:48 -07:00
Colin McDonnell
a415f482db Update trustedDeps doc 2023-07-06 15:33:49 -07:00
Ciro Spaciari
954b6fcaf3 refactor (#3543) 2023-07-06 13:55:27 -07:00
Dylan Conway
abe095dd1e fixes #3544 (#3549) 2023-07-06 13:55:00 -07:00
Colin McDonnell
109ebc14fd Various docs updates (#3437)
* Various docs updates

* Add mocks page

* Fix make

* WebKit instructions

* Update instructions

* Updates

* Update nodejs compat table

* Document trusted deps

* Tweak trustedDependencies docs

* Document --exact

* Update test docs

* Tweaks

* Boring

* Remove redundant j

* Undo makefile changes

* Undo makefile changes

* Update page title

* Regen

* Undo changes
2023-07-06 13:02:29 -07:00
Ciro Spaciari
95ddfcc437 fix query without slash (#3547) 2023-07-06 12:01:16 -07:00
Jarred Sumner
ee57935260 Fixes #3537 (#3539)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-06 00:06:43 -07:00
Dylan Conway
6bf8f6f9f2 don't unwrap react below version 18.0.0 (#3538)
* don't unwrap react below version 18

* empty string

* also `react-dom`
2023-07-05 22:23:32 -07:00
Ciro Spaciari
8869bac411 fix callbacks on release version (#3531) 2023-07-05 22:22:56 -07:00
Dylan Conway
f61d9ef476 Update websocket_http_client.zig 2023-07-05 12:45:20 -07:00
Jarred Sumner
3aaec120e7 Fixes #3512 (#3526)
* Fixes #3512

* Fix `clearTimeout` and `clearInterval` not cancelling jobs same-tick

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-05 03:46:10 -07:00
Jarred Sumner
c864976da6 Fixes #3515 (#3523)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-05 01:21:35 -07:00
Jarred Sumner
a7f5a91cfb Fixes #3520 (#3522)
* Fixes #3520

* Update html_rewriter.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-05 00:08:59 -07:00
Ciro Spaciari
75816aa3ab add envs on tests (#3518)
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-07-05 00:08:49 -07:00
Jarred Sumner
cac7dcdc76 Update build-id 2023-07-04 16:59:33 -07:00
Jarred Sumner
9c374eac96 Fix build determinism issue (thanks to @alexlamsl)
cc @dylan-conway this was the cause
2023-07-04 16:59:03 -07:00
Jarred Sumner
b2e28f133e boop 2023-07-04 16:57:46 -07:00
Ciro Spaciari
3a93ddfab3 use sengrid account on nodemailer test (#3517) 2023-07-04 15:41:37 -07:00
Ciro Spaciari
979e999403 [tls] fix servername (#3513)
* fix servername

* add postgres tls tests

* update test packages

* add basic CRUD test
2023-07-04 15:40:26 -07:00
Ai Hoshino
c2755f770c Add alias for readBigUInt64BE ... (#3514)
* Add alias for `readBigUInt64BE` ...
Close: https://github.com/oven-sh/bun/issues/3338

* add some tests for `readBigUint64BE` alias

* format code
2023-07-04 15:38:44 -07:00
Jarred Sumner
31f7f9e2dc reduce count 2023-07-04 04:15:22 -07:00
Jarred Sumner
491e8f7e00 bump 2023-07-04 04:14:06 -07:00
Jarred Sumner
bb96aa5156 Fix crash 2023-07-04 04:07:35 -07:00
Jarred Sumner
f49a308d2c Create readfile-not-found.mjs 2023-07-04 03:48:10 -07:00
Alex Lam S.L
3d0ffc48cb [install] fix run-time module loading (#3510)
- fix version buffer confusion
- improve workaround to handle cached modules

fixes #3507
2023-07-04 02:09:58 -07:00
Jarred Sumner
bc7b5165be less flaky 2023-07-04 01:51:09 -07:00
Jarred Sumner
a76b07a802 cleanup 2023-07-04 01:18:13 -07:00
Jarred SUmner
33bc507f74 Fix napi 2023-07-04 01:04:18 -07:00
Jarred Sumner
3345a7fc3c Allow zero length WebSocket client & server messages (#3488)
* Allow zero length WebSocket client & server messages

* Add test

* Clean this up a little

* Clean up these tests a little

* Hopefully fix the test failure in release build

* Don't copy into the receive buffer

* Less flaky

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-03 20:53:41 -07:00
Jarred Sumner
b26b0d886c Fix napi bug 2023-07-03 15:57:10 -07:00
Ciro Spaciari
034577c9da [fix] patch fs.watch sym link (#3481)
* oopsie

* add tests

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-07-03 14:08:49 -07:00
Jarred Sumner
424717a973 Fixes #3317 2023-07-03 13:47:37 -07:00
Jarred Sumner
e5f93ddf55 Update lifecycle.md 2023-07-03 13:46:20 -07:00
Jarred Sumner
983039a18a Fixes #3508 2023-07-03 13:16:57 -07:00
Ciro Spaciari
a7a01bd52f [tls] add socket parameter, setServername and ALPNprotocols support (#3457)
* add socket parameter support

* refactor #socket

* add test and more fixs

* some fixes

* bump uws

* handlers fix

* more fixes

* fix node net and node tls tests

* fix duplicate port

* fix deinit on CallbackJobs

* cleanup

* add setImmediate repro

* add test to setImmediate

* this is necessary?

* fix prependOnce on native listener

* try to findout the error on nodemailer CI

* show error message

* Update bun.lockb

* prettier

* Use exact versions of packages

* add alpnProtocol support

* update

* emit error when connect fails on net.Socket

* format

* fix _write and cleanup

* fixup

* fix connect, add alpn test

* fix socket.io

* add socket parameter to TLSSocket

* add TLSSocket socket first parameter

* fixup and _start

* remove flask tests

* fmt

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-03 12:19:50 -07:00
Jarred Sumner
48d726bfd0 Update time.md 2023-07-02 23:48:31 -07:00
Jarred Sumner
12a342b6c0 Update time.md 2023-07-02 23:47:48 -07:00
Jarred Sumner
1206352b4a Update time.md 2023-07-02 23:46:08 -07:00
Jarred Sumner
9da9bac30c Update time.md 2023-07-02 23:18:58 -07:00
Jarred Sumner
cd243f40ee Update time.md 2023-07-02 23:10:50 -07:00
Jarred Sumner
000417731b Add time doc 2023-07-02 23:07:33 -07:00
Jarred Sumner
c77518ff93 Update writing.md 2023-07-02 22:57:24 -07:00
Jarred Sumner
f0a795b568 Stub out useFakeTimers and useRealTimers 2023-07-02 22:42:13 -07:00
Jarred Sumner
aa38e51afb Support mocking new Date() & Date.now() in bun:test (#3501)
* Support changing the time

* Bump WebKit

* Update bun.lockb

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-02 22:09:50 -07:00
dave caruso
c21fadf9bc set content-length 0 in some cases (#3503) 2023-07-02 20:24:15 -07:00
Jarred Sumner
0db31c2b43 Fixes #3499 2023-07-02 20:18:21 -07:00
Jarred Sumner
3a0a423bce Add comment 2023-07-02 20:17:25 -07:00
Jarred Sumner
eb90ce50c3 Use fast path for Base64 in btoa (#3504)
* Use fast path for Base64 in `atob`

* Fix utf16, crash on linux

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-02 20:16:52 -07:00
Jarred Sumner
c3f8593f8c [node:buffer] Implement isUtf8 and isAscii (#3498)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-02 18:06:21 -07:00
dave caruso
4cbda049e9 fix zero length env var (#3496) 2023-07-02 10:12:31 -07:00
Jarred Sumner
69396aae01 Fixes #3495 2023-07-02 10:09:52 -07:00
Jarred Sumner
b05879e9e2 Fixes #3489 (#3490)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-02 01:06:40 -07:00
Jarred Sumner
8001038376 Use exact versions in tests 2023-07-01 22:43:59 -07:00
Jarred Sumner
c7cc618376 Fix leak in fd (#3487)
* Fix file descriptor leak

* Skip unnecessary clone

* Don't break --hot

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-01 21:58:06 -07:00
Jarred Sumner
9fecb3dfb9 Bump 2023-07-01 21:10:55 -07:00
Jarred Sumner
617226e584 Make this test less flaky 2023-07-01 21:10:43 -07:00
Jarred Sumner
c72c82b970 Make this test less flaky 2023-07-01 21:08:26 -07:00
Jarred Sumner
6cae6ebafe Make buffer.toString("base64") 4x faster (#3486)
* Add libbase64

* Add bench

* Update licensing.md

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-01 20:02:50 -07:00
Jarred Sumner
a2cca6e292 Update WebCoreJSBuiltins.cpp 2023-07-01 18:31:38 -07:00
Jarred Sumner
01d3b130a9 Update build-id 2023-07-01 17:44:40 -07:00
Jarred Sumner
af46a8ded1 Make this test less flaky 2023-07-01 17:38:19 -07:00
Jarred Sumner
f00e2be548 Use BunString in SystemError (#3485)
* Use `BunString` in SystemError

* Use Bun::toStringRef when we will de-ref strings

* Move `napi_create_error` to C++ to support `code` being a Symbol potentially

* Update blob.zig

* Make this test less flaky

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-01 17:37:44 -07:00
Jarred Sumner
a4fe433db7 Slight fixup 2023-07-01 17:09:59 -07:00
Jarred Sumner
f3833376e7 small cleanup 2023-07-01 17:07:37 -07:00
Ai Hoshino
4720fa1207 [WIP]Fix calling Buffer.toString with (offset, length, encoding) (#3467)
* Allow `toString` to be called with `(offset, length, encoding)`.
Close: #3085

* handle undefined value

* add tests for buffer.xxxSlice

* fix parameters

* fix offset and length
2023-07-01 17:01:52 -07:00
Jarred Sumner
df10252979 Make HTTP Request struct use 8 bytes less memory (#3483)
* Make HTTP Request struct use 8 bytes less memory

* Update server.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-07-01 14:40:05 -07:00
Dylan Conway
c033d55c47 skip private class fields (#3484) 2023-07-01 14:38:38 -07:00
Jarred Sumner
c794ea7ea7 Add test 2023-07-01 13:31:12 -07:00
Alex Lam S.L
02f707f231 [jest] fix lifecycle hook execution order (#3461)
* [jest] fix lifecycle hook execution order

* strip `std.debug.assert()` from release build
2023-07-01 11:44:04 -07:00
dave caruso
d356cd5d48 implement perf_hooks.constants (#3476) 2023-06-30 14:58:38 -07:00
Stijn Van Hulle
b83faf8018 fix: export ClientRequest and OutgoingMessage as part of the node:http package (#3470) 2023-06-30 10:04:46 -07:00
Alex Lam S.L
2a73d3c793 [install] handle workspace: specifier correctly (#3474)
fixes #3430
2023-06-30 10:03:53 -07:00
Jarred Sumner
039bbc68ad Add missing "prependListener" function 2023-06-29 21:24:55 -07:00
dave caruso
b9460087e3 Fixes node:http and node:stream so ytdl-core works. (#3452)
* fix crash in readablestate

* make node:https request+get actually use https

* use a native readablestream in IncomingMessage

* tweaks

* fix abort crash

* emit close by default

* remove abort. this isnt a real function

* add validate functions, fixup some other requested changes. not done yet

* Update WebCoreJSBuiltins.cpp

* Update JSReadableState.cpp

* Add some missing exports

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-29 20:36:18 -07:00
Jarred Sumner
c42a00f9df Fixes #3462 (#3465)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-29 20:14:12 -07:00
Dylan Conway
76b9cae259 handle multiple redirects 2023-06-29 17:19:16 -07:00
Jarred Sumner
70a87e1181 Make node:os tmpdir more consistent with Node.js 2023-06-29 16:37:38 -07:00
Dylan Conway
7af757d104 add setters for Agent properties (#3460)
* make `Agent` properties public

* back to private, added setters

* change properties to public
2023-06-29 15:47:00 -07:00
Dylan Conway
9c66fdc703 [bundler] avoid printing unnecessary declarations (#3456)
* skip declarations without values

* tests

* deoptimize cjs when decls are needed
2023-06-29 14:51:24 -07:00
dave caruso
fec0d15c4f cant believe i missed this (#3453) 2023-06-29 08:53:44 -07:00
Jarred Sumner
853e377159 Revert "[jest] fix lifecycle hook execution order (#3447)" (#3455)
This reverts commit 182e8aa139.
2023-06-29 08:30:21 -07:00
Jarred Sumner
8984c81961 Prevent integer overflow 2023-06-28 21:57:31 -07:00
Jarred Sumner
c6f6db95ff Ref the strings 2023-06-28 21:56:45 -07:00
Jarred Sumner
8b2c72300c Another test 2023-06-28 21:56:26 -07:00
Jarred Sumner
8481f2922f Add GC test for errors 2023-06-28 21:45:16 -07:00
Jarred Sumner
68e6fe00a4 Use bun.String for ZigException (#3451)
* Use `bun.String` for `ZigException`

* woopsie

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-28 21:11:06 -07:00
Dylan Conway
3258bed1c0 use main field over module for runtime (#3448)
* use main field over module for runtime

* move flag to `Resolver`

* set `prefer_module_field` in `initWithModuleGraph`
2023-06-28 19:28:53 -07:00
Jarred Sumner
32d9abcc03 Fix bad test 2023-06-28 19:20:41 -07:00
dave caruso
0cee640199 export resolve6 from dns/promises (#3450) 2023-06-28 17:45:18 -07:00
Alex Lam S.L
182e8aa139 [jest] fix lifecycle hook execution order (#3447) 2023-06-28 16:27:15 -07:00
Jarred Sumner
945093ee7e bump! 2023-06-28 16:22:46 -07:00
Jarred Sumner
086ca176be Make these tests do more 2023-06-28 16:19:58 -07:00
Jarred Sumner
292647bd53 Introduce await Bun.file(path).exists() (#3446)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-28 16:09:08 -07:00
Jarred Sumner
42ded70336 [node:http] Stub _implicitHeader fn 2023-06-28 13:55:58 -07:00
Jarred Sumner
3d5573921e Error.prototype.stack gets sourcemapped stacktraces and introduce Error.appendStackTrace (#3441)
* Fix potential crash when reading sourcemapped stack traces

* Format & sourcemap Error.prototype.stack

* prevent double sourcemapping

* Introduce Error.appendStackTrace

* Fix source url

* hide private stack traces in non-debug builds

* fixes #3443

* Bump WebKit

* Fix test failure in vm.test

* Support new() & add test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-28 13:53:09 -07:00
Jarred Sumner
43752ec3f0 Fix assertion failure in escapeHTML with UTF-16 text (#3436)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-28 11:27:31 -07:00
Silas Rech
e6e3d9e368 Fix .randomInt() export (#3438) 2023-06-28 11:27:02 -07:00
Alex Lam S.L
0de5bb22af [install] workaround run-time module loading issue (#3432) 2023-06-28 01:20:59 -07:00
Dylan Conway
f670c0fc18 don't overwrite __esModule 2023-06-27 18:23:56 -07:00
Dylan Conway
09994d6067 add __esModule 2023-06-27 17:34:31 -07:00
Benjamin Ryan
f81d084f5c [bun:sqlite] enable FTS5 on linux build (#3431)
* [bun:sqlite] enable FTS5 on linux build

* prettier
2023-06-27 17:27:06 -07:00
Jarred Sumner
940c9a8185 Fix some checks 2023-06-27 16:16:47 -07:00
Dylan Conway
28d7507a5d add todo comment 2023-06-27 14:55:13 -07:00
Jarred Sumner
4f34d48029 getIfPropertyExists is safer than getDirect (#3391)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-27 13:42:25 -07:00
Dylan Conway
c78aa5a60f fix macros 2023-06-27 13:23:01 -07:00
Revenity
7ba4ae11c9 Update Stric page in Ecosystem (#3399) 2023-06-27 12:37:57 -07:00
Jarred Sumner
5376b5b5d6 Add builtin exports list 2023-06-27 10:29:22 -07:00
Ashcon Partovi
3ec6c9e4fb Fix docker tag on release 2023-06-27 09:10:43 -07:00
Jarred Sumner
2eb885c1d8 Regenerate 2023-06-27 08:24:35 -07:00
Ai Hoshino
1c46d88728 Fix node:util.callbackify (#3428)
* remove the incorrect parameters
Close: https://github.com/oven-sh/bun/issues/3424

* fix error code

* add callbackify tests

* fix function type

* ensure `done` is called when error occurred
2023-06-27 08:23:25 -07:00
Jarred Sumner
d220d9ee5a Update NodeModuleModule.cpp 2023-06-27 08:21:04 -07:00
Jarred Sumner
e77f593b76 Update build-id 2023-06-27 08:14:34 -07:00
Alex Lam S.L
b305309e64 minor build diffs (#3427) 2023-06-27 14:05:59 +03:00
Jarred Sumner
c96f3b303b Fix default export of "module" module 2023-06-26 20:39:15 -07:00
dave caruso
ecb0bd39b6 fix #3412 (#3422) 2023-06-26 19:27:12 -07:00
Dylan Conway
4e4cae0fc3 webpack test and add empty prototype prop to module (#3421) 2023-06-26 19:16:59 -07:00
Jarred Sumner
4be15cff02 Tweak the ramSize setting because /= 1024 is causing CI to fail on arm64 when there's only 8 GB of ram 2023-06-26 19:07:54 -07:00
Jarred Sumner
f839cf1ce3 Update crypto.mjs 2023-06-26 19:07:54 -07:00
Jarred Sumner
1e6a41b5cf change the text from "error" to "warn" 2023-06-26 19:07:54 -07:00
Dylan Conway
1ed1723a2f Update bundle_v2.zig (#3420) 2023-06-26 19:00:55 -07:00
Peter Weinberg
7a0b1656c7 docs: add troubleshooting section to installation page (#3389)
* docs: add troubleshooting section to installation page

* Add note for unzip

* Update msg in install.sh

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2023-06-26 18:25:33 -07:00
Jarred Sumner
28f27f733b [bun install] Implement --exact flag (#3409)
* [bun install] Implement `--exact` flag

* Rename to --save-exact

* Rename --exact to --save-exact

* Update bun-add.test.ts

* We're going with --exact as the flag name

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-26 15:51:57 -07:00
Jarred Sumner
a5100ad380 Fix .rejects 2023-06-26 15:49:26 -07:00
Silas Rech
16598555f1 .randomInt() support (#3357)
* Add initial .randomInt() fallback

* Add basic .randomInt() test

* Attempt creating a native implementation

* Switch to JSC.wrapWithHasContainer

* Switch to .jsNumberFromUint64(), it seems like using just .jsNumber() causes the number to overflow in some cases

* Regenerate out folder after rebasing
2023-06-26 15:35:48 -07:00
Jarred Sumner
a732999da5 Runtime support for __esModule annotations (#3393)
* Runtime support for `__esModule` annotations

* Ignore `__esModule` annotation when `"type": "module"` is set

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-26 12:49:20 -07:00
Dylan Conway
6d01e6e367 test moved to node-module-module.test.js 2023-06-26 12:09:18 -07:00
Jarred Sumner
50e872fc76 Implement writev & readv (#3419)
* [node:fs] Implement `writev` and `readv`

* writev & readv tests

* cast to const type

* woops

* cast

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-26 11:56:53 -07:00
Alex Lam S.L
318879d174 [install] support trustedDependencies (#3288)
* [install] support trustedDependencies

closes #2073

* use `strings.indexOfChar()`

* use hashes instead of strings

* utilise `inline else`
2023-06-26 11:55:26 -07:00
Dylan Conway
ec3ed67bc9 implement _nodeModulePaths and require.main.paths (#3411)
* tests in progress

* add `require.main.paths`, add every dir up to root

* remove imports
2023-06-26 08:12:37 -07:00
Jarred Sumner
76626ac54b Fix test failures in import.meta (#3403)
* Fix test failures in import.meta

* regenerate

* Use bound functions for `import.meta.require` and `import.meta.require.resolve` and `Module.createRequire`

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 19:48:56 -07:00
Jarred Sumner
116bcf4245 Fixes #3334 (#3401)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 18:49:16 -07:00
Jarred Sumner
f2285a6d71 Use bun.String in mkdir (#3404)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 17:54:55 -07:00
Jarred Sumner
e682ffb61c Update schema.zig 2023-06-25 17:54:21 -07:00
Jarred Sumner
9ebb25427a remove very old stuff 2023-06-25 17:51:24 -07:00
Jarred Sumner
66195ffeed Update WebKit 2023-06-25 17:50:12 -07:00
Brúnó Salomon
662335d81a chore: update lol-html version (#3356)
* chore: update lol-html version

* add tests

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-06-25 16:48:03 -07:00
Tiago Teixeira
d8817c2d32 Add support for install with --frozen-lockfile (#3365)
* Add support for install with --frozen-lockfile

* Add test

* Add test for frozenLockfile in config file
2023-06-25 16:43:39 -07:00
Jarred Sumner
15ac08474e fixup 2023-06-25 16:40:51 -07:00
Jarred Sumner
fdfbb18531 Support reading embedded files in compiled executables (#3405)
* Support reading embedded files in compiled executables

* 💅

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 16:32:27 -07:00
Ciro Spaciari
3ed28f2828 [fs.watch] fix reference/deinit (#3396)
* fix js reference

* fix close  oops

* refactor + hasPendingActivity

* fmt

* fix race conditions

* fixup

* add test calling close on error event

* fix close inside close + test

* cleanup
2023-06-25 16:16:25 -07:00
Ai Hoshino
fcf9f0a7ee Fix the parameters of WriteStream constructor. (#3402)
* Fix the parameters of the `WriteStream` constructor.
Close: https://github.com/oven-sh/bun/issues/3395

* test append mode in `createWriteStream`

* fix lint

* wait first stream finished
2023-06-25 16:15:56 -07:00
Alex Lam S.L
33903ea892 [install] fix hang in bun install --production (#3406) 2023-06-26 01:43:58 +03:00
Jarred Sumner
5bd94b8f47 Add process.mainModule 2023-06-25 11:43:54 -07:00
Jarred Sumner
aa5432e162 FIx launch.json cwd 2023-06-25 11:33:13 -07:00
Jarred Sumner
c4c714f10b Speculative fix for regression causing a hang with install --production (#3400)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 04:52:43 -07:00
Jarred Sumner
f8abd167d8 Revert "make these strings lazy"
This reverts commit 777f98bd10.
2023-06-25 04:17:07 -07:00
Jarred Sumner
777f98bd10 make these strings lazy 2023-06-25 03:32:10 -07:00
Jarred Sumner
30798c7078 Make timeout longer 2023-06-25 03:32:10 -07:00
Jarred Sumner
bc7719fc28 Reliability bugfix for WebSocket (#3394)
* Rewrite elementLengthLatin1IntoUTF8

* Update SIMDUTF

* Make `elementLengthLatin1IntoUTF8` faster

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-25 02:58:49 -07:00
Jarred Sumner
ff63555143 Rewrite Bun's runtime CommonJS loader (#3379)
* wip changes for CommonJS

* this rewrite is almost complete

* even more code

* wip

* Remove usages of `import.meta.require` from builtins

* Remove usages of require

* Regenerate

* ✂️ builtin rewrite commonjs in printer

* Use lazy custom getters for import.meta

* fixups

* Remove depd

* ugh

* still crashing

* fixup undici

* comment out import.meta.require.resolve temporarily

not a real solution but it stops the crashes

* Redo import.meta.primordials

* Builtins now have a `builtin://` protocol in source origin

* Seems to work?

* Finsih getting rid of primordials

* switcharoo

* No more function

* just one more bug

* Update launch.json

* Implement `require.main`

* ✂️

* Bump WebKit

* Fixup import cycles

* Fixup improt cycles

* export more things

* Implement `createCommonJSModule` builtin

* More exports

* regenerate

* i broke some stuff

* some of these tests work now

* We lost the encoding

* Sort of fix zlib

* Sort of fix util

* Update events.js

* bump

* bump

* bump

* Fix missing export in fs

* fix some bugs with builtin esm modules (stream, worker_threads, events). its not perfect yet.

* fix some other internal module bugs

* oops

* fix some extra require default stuff

* uncomment this file but it crsahes on my machine

* tidy code here

* fixup tls exports

* make simdutf happier

* Add hasPrefix binding

* Add test for `require.main`

* Fix CommonJS evaluation order race condition

* Make node:http load faster

* Add missing exports to tls.js

* Use the getter

* Regenerate builtins

* Fix assertion failure in Bun.write()

* revamp dotEnv parser (#3347)

- fixes `strings.indexOfAny()`
- fixes OOB array access

fixes #411
fixes #2823
fixes #3042

* fix tests for `expect()` (#3384)

- extend test job time-out for `darwin-aarch64`

* `expect().resolves` and `expect().rejects` (#3318)

* Move expect and snapshots to their own files

* expect().resolves and expect().rejects

* Fix promise being added to unhandled rejection list

* Handle timeouts in expect(<promise>)

* wip merge

* Fix merge issue

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* fixup min/memcopy (#3388)

* Fix crash in builtins

* Don't attempt to evaluate modules with no source code

* Update WebCoreJSBuiltins.cpp

* Update WebCoreJSBuiltins.cpp

* Update WebCoreJSBuiltins.cpp

* Fix crash

* cleanup

* Fix test

cc @paperdave

* Fixup Undici

* Fix issue in node:http

* Create util-deprecate.mjs

* Fix several bugs

* Use the identifier

* Support error.code in `util.deprecate`

* make the CJs loader slightly more resilient

* Update WebCoreJSBuiltins.cpp

* Fix macros

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: dave caruso <me@paperdave.net>
Co-authored-by: Alex Lam S.L <alexlamsl@gmail.com>
Co-authored-by: Ashcon Partovi <ashcon@partovi.net>
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
2023-06-24 06:02:16 -07:00
Ciro Spaciari
069b42a7cc [feat] fs.watch (#3249)
* initial support

* add types

* fix comment

* fix types

* bigfix up

* more fixes

* fix some encoding support for watch

* fix rename event

* fixup

* fix latin1

* add fs_events, still failing some tests

* fixuup

* remove unecesary check

* readd tests ops

* this is necessary? just testing CI/CD weird errors

* just use dupe here

* cleanup and fix deinit

* fix zig upgrade
2023-06-23 23:24:34 -07:00
dave caruso
ceec1afec2 Add vi.spyOn and clean up some mock function binding calls (#3376)
* Add vi.spyOn and clean up some binding calls

* add vi.restoreAllMocks

* remove junk file

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2023-06-23 23:24:05 -07:00
dave caruso
5ae8e5d773 Make node-fallbacks build as esm not cjs / Fix node-fetch (#3377)
* Make node-fallbacks build as esm not cjs.

* fix stuff
2023-06-23 23:23:39 -07:00
Ciro Spaciari
4ff920c915 fixup min/memcopy (#3388) 2023-06-23 18:19:00 -07:00
Ashcon Partovi
217501e180 expect().resolves and expect().rejects (#3318)
* Move expect and snapshots to their own files

* expect().resolves and expect().rejects

* Fix promise being added to unhandled rejection list

* Handle timeouts in expect(<promise>)

* wip merge

* Fix merge issue

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-22 22:27:00 -07:00
Alex Lam S.L
ae4b65c52e fix tests for expect() (#3384)
- extend test job time-out for `darwin-aarch64`
2023-06-22 20:13:26 -07:00
Alex Lam S.L
ca1fe3c602 revamp dotEnv parser (#3347)
- fixes `strings.indexOfAny()`
- fixes OOB array access

fixes #411
fixes #2823
fixes #3042
2023-06-22 17:05:54 -07:00
Jarred Sumner
4a13a53058 CommonJS bun build cannot use import.meta (#3378)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-22 01:06:50 -07:00
Dylan Conway
5fa13625a1 upgrade zig to v0.11.0-dev.3737+9eb008717 (#3374)
* progress

* finish `@memset/@memcpy` update

* Update build.zig

* change `@enumToInt` to `@intFromEnum` and friends

* update zig versions

* it was 1

* add link to issue

* add `compileError` reminder

* fix merge

* format

* upgrade to llvm 16

* Revert "upgrade to llvm 16"

This reverts commit cc930ceb1c.

---------

Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-21 23:38:18 -07:00
Jarred Sumner
bfb322d618 Revert "Update Github action runners"
This reverts commit 69f558db8e.
2023-06-21 19:52:53 -07:00
dave caruso
43865a3e29 finish implementing JSMockFunction prototype + lots of expect test organizing (#3304)
* mock tests

* fix mistake

* stuff

* partially implement mock return promises

* lot of housecleaning on jest tests

* document / rename internalFields in jsmockfunction

* finish implementing JSMockFunction prototype

* cleanup

* more progress

* everything is done

* remove demo.test.js

* finish rebase

* requested changes

* fix compile error
2023-06-21 12:59:56 -07:00
Andreas Pfurtscheller
b691212c6e Update module resolution order docs (#3372)
If I'm reading and interpreting [these lines](69f558db8e/src/options.zig (L605-L627)) correct, the module resolution order [in the current docs](https://bun.sh/docs/runtime/modules#resolution) is outdated.

This change will fix the order.
2023-06-21 12:08:05 -07:00
Ashcon Partovi
69f558db8e Update Github action runners 2023-06-21 11:14:41 -07:00
Jarred Sumner
9befbf02f1 Update WebKit 2023-06-20 21:32:19 -07:00
Jarred Sumner
f81c7f10f6 Fix crash with .env files that are exactly 159 bytes long (#3369)
* Fix crash with .env files that are exactly 158 bytes and a newline character

* Update env_loader.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-20 21:17:32 -07:00
Jarred Sumner
b9c950bfb7 Improve error message for error.DependencyLoop (#3368)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-20 19:29:47 -07:00
Dylan Conway
6a1fbef8fd record jsx factory symbols in classic mode (#3360)
* record jsx factory symbols

* merge factory/fragment when more than one part

* update test

* use existing functions, use, `memberListToComponentsIfDifferent`

* missing file

* fix defaults
2023-06-20 19:29:20 -07:00
Dylan Conway
5006435234 enable asymmetric matchers in expect.toEqual, expect.toStrictEqual, and expect.toHaveProperty (#3367)
* add asymmetric matchers to `deepEquals`

* fix comparison of a few jstypes

* clean up and tests

* fix merge

* improve `expect.any` for primitives
2023-06-20 19:06:58 -07:00
Colin McDonnell
adb451eec6 Docs for DOM testing and FileSink (#3330)
* Update websocket docs & jsdoc

* Add info about user-specific data in ws

* Document FileSink

* Docs for happydom test

* Updates
2023-06-20 18:57:37 -07:00
Jarred Sumner
62639081c1 [JSTranspiler] Make scan and scanImports more careful with GC 2023-06-20 18:55:14 -07:00
Jarred Sumner
570ef07170 woops 2023-06-20 18:06:28 -07:00
Jarred Sumner
83d7ec728f Clone SourceOrigin string 2023-06-20 17:12:47 -07:00
Jarred Sumner
9f301e13c5 Cleanup fs.utimesSync (#3363)
* Fix UB in fs.utimesSync when passing a number with an integer greater than i32

* Fix make headers

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-20 00:31:07 -07:00
Jarred Sumner
f1b1dbf5cd prettier 2023-06-20 00:02:14 -07:00
Keyhan Vakil
bdbb637b3d implement more of V8's stack trace API (#3359)
- fix source map positions for getLineNumber / getColumnNumber
- fix return value getting coerced to a string
- implement CallFrame.p.toString
- add tests for getFunction, getThis, isConstructor, isNative, toString,
  getLineNumber, getColumnNumber

still not implemented:
- isPromiseAll/getPromiseIndex
- getEvalOrigin
- getScriptHash
- getPosition
- getEnclosingColumnNumber/getEnclosingLineNumber
- isAsync
- accessing Error.stack should call prepareStackTrace

still broken:
- isEval: often returns false when it should return true
- isToplevel: often returns true when it should return false

Refs: https://v8.dev/docs/stack-trace-api
Refs: v8/src/objects/call-site-info.cc
Fixes: https://github.com/oven-sh/bun/issues/2883
2023-06-19 23:28:40 -07:00
Tiramify (A.K. Daniel)
e9e0e05156 feat(bun/test): Impl. "toBeArray", "toBeArrayOfSize" & "toBeTypeOf" (#3316)
* Implement toBeArray, toBeArrayOfSize, toBeTypeOf

* fix typos/variable names

* Add testcases for regex and dates

* little fix

* i didn't paste that...
2023-06-19 22:39:44 -07:00
Jarred Sumner
7d94a49ef4 Fix bug that breaks bunx prisma init when node is not installed (#3362)
* tweak cjs

* Handle more cases, add a test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-19 22:34:22 -07:00
Jarred Sumner
cbd6d24d34 Move this code up a bit 2023-06-19 00:33:14 -07:00
Jarred Sumner
b951c1f89e Press the secret "use less RAM" button 2023-06-18 23:30:01 -07:00
Jarred Sumner
b78b2a3031 Update esbuild-test.js 2023-06-18 21:57:52 -07:00
Jarred Sumner
7dcf8b2186 Make the esbuild integration test more thorough 2023-06-18 21:57:40 -07:00
Jarred Sumner
8a5b8f1fca Make more tests fail 2023-06-18 21:07:38 -07:00
Jarred Sumner
8ad9e5755d Add missing ucs2 alias 2023-06-18 21:05:05 -07:00
Jarred Sumner
fdb7940c4e Fix a bunch of bugs (#3352)
* Fix a bunch of bugs

* undo that one

* Fix crash in readdir()

* woops

* woops

* Add comment

* ✂️

* Make `readlink()` and `realpath` use much less memory

* Update BunString.cpp

* woopsie

* Unnecessary

* Don't commit these

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-18 10:47:42 -07:00
Alex Lam S.L
873f615358 minor build diffs (#3349) 2023-06-18 03:45:41 -07:00
Ciro Spaciari
b2af1984ed [eventsource] SSE Client (#3074)
* fix flush

* remove logs

* add HTTP/1.1 eventsource

* fix parse spec

* multiple data in one event

* get lastEventId for reconnection

* fix parsing add reconnect

* fix reconnection retry

* add retry option

* move eventsource to builtins

* remove duplicate interface on globals.d.ts

* move test to TS

* fmt

* allow no Content-Length or Transfer Encoding

* udpate builtins

* hardcoded

* merge

* revert /src/out

* updated

* Update .gitignore

* Make the tests fail

* Cleanup EventSource getter

* fixup

* fixup TS

* fmt

* update builtins

* fix tests

* Clear existing timeouts

* Add `ref` and `unref` methods

* Use `super` to make prototype pollution slightly harder

* Reduce test timeout

* Regenerate builtins

* prettier + ref/unref

* Outdated

* forgot to commit this

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-17 20:54:50 -07:00
Tiramify (A.K. Daniel)
065713aeca Add types for toBeOdd & toBeEven (#3344) 2023-06-17 14:05:28 -07:00
Luigi Pinca
68c092aef2 Set the publishToSelf option to true (#3343)
All messages sent by the clients are expected to be received by all
clients. Without the `publishToSelf` option a message is not sent back
to the sender and the benchmark hangs.
2023-06-17 14:05:11 -07:00
Dylan Conway
9b8054ae11 don't remove const if referenced before declaration (#3337) 2023-06-16 21:11:57 -07:00
Jarred Sumner
0591c6b4bb Fix make headers jun 15 edition 2023-06-15 23:00:57 -07:00
Kabir Goel
4a22fcd93c Fix typo in run.md (#3331) 2023-06-15 15:03:46 -07:00
Jarred Sumner
dc06caccaa Tweak CommonJS output (#3320)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-15 01:18:23 -07:00
Ciro Spaciari
e6d4b3a89a [Bun.serve] fix Bun.serve argument check (#3314)
* fixup checks

* throw when tls is not a object also fix socket

* fix error message

* null or undefined on tls option in Bun.serve or sockets should not throw

* add tests

* fix tests and socket validation

* remove unnecessary check

* add listen tests
2023-06-14 19:29:36 -07:00
Jarred Sumner
0f131a976e Update build-id 2023-06-14 08:37:33 -07:00
Jarred Sumner
7f535a20a2 Workaround issue with module.require = 2023-06-14 08:35:51 -07:00
Jarred Sumner
bac7526c03 Make Bun.argv the same as process.argv (#3310)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-14 04:01:28 -07:00
Jarred Sumner
c2a83f87d8 Remove redudant put 2023-06-14 03:25:43 -07:00
Jarred Sumner
333b3f6beb Prepare to support webkit debug build assertions 2023-06-14 03:24:39 -07:00
dave caruso
b7ff3b0745 document Bun.argv in typedefs (#3302) 2023-06-14 01:48:51 -07:00
Colin McDonnell
a1bb79f440 mock type changes (#3305)
* Update mock types and set bun-types@latest in bun init

* Remove mockfn methods from toplevel mock

* Remove comments
2023-06-13 22:28:31 -07:00
xxxhussein
171ba6327d fix TS5096 (#3256) 2023-06-13 17:42:29 -07:00
Jarred Sumner
2ab797ff75 lol 2023-06-13 10:54:51 -07:00
Jarred Sumner
bdb1b7124a Fix crash in CJS (#3294)
* Fix crash in CJS

* Add std.heap.ArenaAllocator

* Use our arena allocator

* Reduce JS parser memory usage and make HMR faster

* Write some comments

* fix test failure & clean up this code

* Update javascript.zig

* make arena usage safer

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-13 09:15:05 -07:00
Jarred Sumner
b93bdbb124 Add test 2023-06-13 07:29:02 -07:00
Alex Lam S.L
c8d06f04d3 workaround quote escape issues for bun run (#3290)
fixes #53
2023-06-13 05:38:10 -07:00
Dylan Conway
067a0235e4 handle unwrapping require in any expression (#3292) 2023-06-12 21:43:45 -07:00
Jarred Sumner
dbb2416542 Make mocks use FunctionPrototype (#3291)
* Make mocks use FunctionPrototype

* Fix static methods

* Fix types

* Update JSMockFunction.cpp

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-12 19:55:07 -07:00
dave caruso
51c093e24e typo in readline (#3286) 2023-06-12 07:41:54 -07:00
Keyhan Vakil
50a18b6bac doc: minor fixes (#3278)
* `bun link` only modifies `package.json` when `--save` is passed.
* clang-15 is a separate package from llvm-15.
2023-06-11 09:26:46 -07:00
Keyhan Vakil
9a8d9b5e91 add --save argument to install (#3277) 2023-06-11 07:10:55 -07:00
Jarred Sumner
ef65f3c305 Support using WTF::StringImpl from Zig (#3279)
* Fix `make headers`

* [JS parser] Fix bug with printing non-ascii import paths in ascii mode

* Introduce `bun.String`

* Add test for non-ascii imports & entry points

* Add comment

* Fix build issue

* Support HTTP server

* Make it print the same

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-11 05:26:37 -07:00
Jarred Sumner
02eafd5019 Make cold bun install use 2x less memory (#3271)
* Make cold `bun install` use 2x less memory

In this benchmark: https://github.com/orogene/orogene/blob/main/BENCHMARKS.md

This brings us from around 2.7 GB to 1.2 GB of memory

* Address comments

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-10 15:38:09 -07:00
Luigi Pinca
04cd6a82b8 Fix benchmark (#3276) 2023-06-10 11:39:26 -07:00
Jarred Sumner
a2ec2ea397 Fixes #3250 (#3269)
* Fixes #3250

We must call `EVP_MD_CTX_cleanup` because `EVP_MD_CTX` containers pointers inside to allocated memory

* Fix leak

* Update sha.zig

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-10 02:26:48 -07:00
paperluigis
f51878a8ec Fix wording and code example in docs for Bun.sleepSync (#3270) 2023-06-10 01:03:30 -07:00
Alex Lam S.L
f18423cf45 [install] fix lockfile fallback for life cycle scripts (#3265) 2023-06-09 21:02:37 -07:00
Dylan Conway
68b9731db2 Update writing.md (#3264) 2023-06-09 19:46:29 -07:00
Dylan Conway
76cf465cc2 toMatchObject and some asymmetric matchers (#3260)
* `toMatchObject` progress

* add `expect.stringContaining()`

* add `expect.stringMatching()`

* print asymmetric matchers

* cleanup

* return before printing if constructor value isn't there

* move matcher logic to cpp

* pretty format and tests

* fix formatting for snapshots

* format `stringContaining` and `stringMatching` like jest

* better test

* remove commented tests

* remove old property matcher code

* add types

* make sure all props are matched in arrays

* add `Bun.deepMatch`
2023-06-09 19:26:36 -07:00
Jarred Sumner
0f018ea215 Fixes #3206 (#3262)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-09 18:22:32 -07:00
Colin McDonnell
a8dc41cd9f Fix jest.fn type 2023-06-09 18:08:36 -07:00
Alex Lam S.L
dbcaa02d89 [install] fix life cycle scripts execution (#3235)
[install] fix life cycle scripts execution
- scripts from dependencies did not run during re-installation
- `bun.lockb` now contains data on life cycle scripts
- handle prior lockfile format by reading missing info from every `package.json`
- suppress spurious log output from tests
2023-06-10 03:30:43 +03:00
Colin McDonnell
e6b1574046 Clean up types 2023-06-09 17:23:06 -07:00
Colin McDonnell
5df26a6a9b Improve types for mocks (#3261)
* Add jest.fn to types

* Fix type-tests
2023-06-09 17:10:19 -07:00
Colin McDonnell
fc3331628e Clean up comments in types 2023-06-09 16:45:41 -07:00
Colin McDonnell
0ec70119f2 Add types for mocks 2023-06-09 16:44:29 -07:00
Jarred Sumner
bf518222d4 Implement mocks in bun:test (#3252)
* wip

* wip

* most of the code for mocks in bun:test

* finishing up

* Implement `toHaveBeenCalled` and `toHaveBeenCalledTimes(1)`

* Test

* visit

* results, not returnValues

* exact

* Update jest.zig

* A couple more tests

* Add jest.fn

* support resetting mocks

* Implement spyOn

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-09 16:38:06 -07:00
ytakhs
6565bd89d5 Fix to retain a newline after removing a package (#3231) 2023-06-09 08:42:38 -07:00
Ashcon Partovi
99485bec4c Fix tests that pass but generate annotation 2023-06-09 05:53:23 -07:00
Ashcon Partovi
0eb5103642 Fix missing JSC.markBinding 2023-06-09 05:40:44 -07:00
James Liu
edd03341b1 docs: add missing right parenthesis in example code (#3245)
add missing right parenthesis in example code in `HTTP server` section
2023-06-09 05:20:37 -07:00
Alex Lam S.L
1d2f06b37e replace sudo usage in GitHub Actions (#3254) 2023-06-09 11:33:22 +03:00
dave caruso
870e5ac1dc improve stream types (#3240) 2023-06-07 14:45:14 -07:00
Jarred Sumner
7e296a1adc [breaking][bun:sqlite] .values() returns [] instead of null for queries returning 0 results (#3219)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-06 23:52:23 -07:00
Jarred Sumner
b9a705f84b add buffer label (#3220)
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2023-06-06 23:51:05 -07:00
Colin McDonnell
d265ed80d2 Docs for Bun.password and ws publish (#3227)
* Update websocket docs & jsdoc

* Document Bun.password

* Update hash encoding docs

* Fix typos

* Add info about user-specific data in ws

* Update outdated websocket jsdoc

* Replace usages of req.url

* Remove log
2023-06-06 23:50:43 -07:00
dave caruso
fa3cfd34cb yeah (#3229) 2023-06-06 23:48:13 -07:00
Colin McDonnell
bcd67c3455 Bun.passwordSync -> Bun.password.{method}Sync (#3228)
* Bun.passwordSync -> Bun.password.{method}Sync

* Update jsdoc

* Updates
2023-06-06 23:44:40 -07:00
30672 changed files with 462487 additions and 91229 deletions

8
.editorconfig Normal file
View File

@@ -0,0 +1,8 @@
# https://EditorConfig.org
root = true
[*]
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf

22
.gitattributes vendored
View File

@@ -1,3 +1,22 @@
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.jsx text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.tsx text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.ts text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.c text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.cpp text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.cc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.zig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.rs text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.h text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.mjs text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.mts text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
.vscode/launch.json linguist-generated
src/api/schema.d.ts linguist-generated
fixture.*.c linguist-generated
@@ -5,7 +24,6 @@ src/api/schema.js linguist-generated
src/bun.js/bindings/sqlite/sqlite3.c linguist-vendored
src/bun.js/bindings/sqlite/sqlite3_local.h linguist-vendored
*.lockb binary diff=lockb
*.zig text eol=lf
src/bun.js/bindings/simdutf.cpp linguist-vendored
src/bun.js/bindings/simdutf.h linguist-vendored
@@ -31,3 +49,5 @@ src/bun.js/bindings/ZigGeneratedClasses+lazyStructureHeader.h linguist-generated
src/bun.js/bindings/ZigGeneratedClasses+lazyStructureImpl.h linguist-generated
docs/**/* linguist-documentation
packages/bun-uws/fuzzing/seed-corpus/**/* linguist-generated

View File

@@ -1,35 +0,0 @@
name: 📥 Install Problem
description: Report an issue during install or upgrade
labels: [bug, install]
body:
- type: markdown
attributes:
value: |
Thank you for submitting a bug report. It helps make Bun better.
If you need help or support using Bun, and are not reporting an issue, please
join our [Discord](https://discord.gg/CXdq2DP29u) server, where you can ask questions in the [`#help`](https://discord.gg/32EtH6p7HN) forum.
Please try to include as much information as possible.
- type: input
attributes:
label: What platform is your computer?
description: |
For MacOS and Linux: copy the output of `uname -mprs`
For Windows: copy the output of `"$([Environment]::OSVersion | ForEach-Object VersionString) $(if ([Environment]::Is64BitOperatingSystem) { "x64" } else { "x86" })"` in the PowerShell console
- type: textarea
attributes:
label: How did you attempt to install or upgrade?
description: Please provide the commands you ran to install or upgrade.
validations:
required: true
- type: textarea
attributes:
label: What do you see instead?
description: If possible, please provide text instead of a screenshot.
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: Is there anything else you think we should know?

View File

@@ -14,7 +14,7 @@ body:
- type: input
attributes:
label: What version of Bun is running?
description: Copy the output of `bun -v`
description: Copy the output of `bun --revision`
- type: input
attributes:
label: What platform is your computer?

62
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,62 @@
### What does this PR do?
<!-- **Please explain what your changes do**, example: -->
<!--
This adds a new flag --bail to bun test. When set, it will stop running tests after the first failure. This is useful for CI environments where you want to fail fast.
-->
- [ ] Documentation or TypeScript types (it's okay to leave the rest blank in this case)
- [ ] Code changes
### How did you verify your code works?
<!-- **For code changes, please include automated tests**. Feel free to uncomment the line below -->
<!-- I wrote automated tests -->
<!-- If JavaScript/TypeScript modules or builtins changed:
- [ ] I ran `make js` and committed the transpiled changes
- [ ] I or my editor ran Prettier on the changed files (or I ran `bun fmt`)
- [ ] I included a test for the new code, or an existing test covers it
-->
<!-- If Zig files changed:
- [ ] I checked the lifetime of memory allocated to verify it's (1) freed and (2) only freed when it should be
- [ ] I or my editor ran `zig fmt` on the changed files
- [ ] I included a test for the new code, or an existing test covers it
- [ ] JSValue used outside outside of the stack is either wrapped in a JSC.Strong or is JSValueProtect'ed
-->
<!-- If new methods, getters, or setters were added to a publicly exposed class:
- [ ] I added TypeScript types for the new methods, getters, or setters
-->
<!-- If dependencies in tests changed:
- [ ] I made sure that specific versions of dependencies are used instead of ranged or tagged versions
-->
<!-- If functions were added to exports.zig or bindings.zig
- [ ] I ran `make headers` to regenerate the C header file
-->
<!-- If \*.classes.ts files were added or changed:
- [ ] I ran `make codegen` to regenerate the C++ and Zig code
-->
<!-- If a new builtin ESM/CJS module was added:
- [ ] I updated Aliases in `module_loader.zig` to include the new module
- [ ] I added a test that imports the module
- [ ] I added a test that require() the module
-->

View File

@@ -36,7 +36,7 @@ jobs:
arch: aarch64
build_arch: arm64
runner: linux-arm64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-linux-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-linux-arm64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-arm64-lto"
build_machine_arch: aarch64

View File

@@ -46,7 +46,7 @@ jobs:
arch: x86_64
build_arch: amd64
runner: big-ubuntu
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-linux-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-linux-amd64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-amd64-lto"
build_machine_arch: x86_64
- cpu: nehalem
@@ -54,7 +54,7 @@ jobs:
arch: x86_64
build_arch: amd64
runner: big-ubuntu
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-linux-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-linux-amd64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-amd64-lto"
build_machine_arch: x86_64
@@ -187,12 +187,17 @@ jobs:
unzip bun-${{matrix.tag}}.zip
cd bun-${{matrix.tag}}
chmod +x bun
sudo mv bun /usr/local/bin/bun
bun --version
pwd >> $GITHUB_PATH
./bun --version
- id: test
name: Test (node runner)
env:
SMTP_SENDGRID_SENDER: ${{ secrets.SMTP_SENDGRID_SENDER }}
TLS_MONGODB_DATABASE_URL: ${{ secrets.TLS_MONGODB_DATABASE_URL }}
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
sudo apt-get update && sudo apt-get install -y openssl
bun install
bun install --cwd test
bun install --cwd packages/bun-internal-test

View File

@@ -117,7 +117,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
# - cpu: haswell
@@ -126,7 +126,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
# - cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
# - cpu: haswell
@@ -144,7 +144,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
- cpu: native
@@ -152,7 +152,7 @@ jobs:
tag: bun-darwin-aarch64
obj: bun-obj-darwin-aarch64
artifact: bun-obj-darwin-aarch64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-arm64-lto.tar.gz"
runner: macos-arm64
dependencies: true
compile_obj: true
@@ -173,9 +173,9 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install ccache rust llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix ccache)/bin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix ccache)/bin" >> $GITHUB_PATH
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2
@@ -257,7 +257,7 @@ jobs:
# package: bun-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: haswell
# arch: x86_64
# tag: bun-darwin-x64
@@ -265,14 +265,14 @@ jobs:
# package: bun-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
- cpu: native
arch: aarch64
tag: bun-darwin-aarch64
obj: bun-obj-darwin-aarch64
package: bun-darwin-aarch64
artifact: bun-obj-darwin-aarch64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-arm64-lto.tar.gz"
runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -291,8 +291,8 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install rust ccache llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2
@@ -397,7 +397,7 @@ jobs:
runs-on: ${{ matrix.runner }}
needs: [macOS]
if: github.event_name == 'pull_request' && github.repository_owner == 'oven-sh'
timeout-minutes: 10
timeout-minutes: 30
outputs:
failing_tests: ${{ steps.test.outputs.failing_tests }}
failing_tests_count: ${{ steps.test.outputs.failing_tests_count }}
@@ -426,10 +426,14 @@ jobs:
unzip ${{matrix.tag}}.zip
cd ${{matrix.tag}}
chmod +x bun
sudo mv bun /usr/local/bin/bun
bun --version
pwd >> $GITHUB_PATH
./bun --version
- id: test
name: Test (node runner)
env:
SMTP_SENDGRID_SENDER: ${{ secrets.SMTP_SENDGRID_SENDER }}
TLS_MONGODB_DATABASE_URL: ${{ secrets.TLS_MONGODB_DATABASE_URL }}
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install

View File

@@ -117,7 +117,7 @@ jobs:
obj: bun-obj-darwin-x64-baseline
runner: macos-11
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: true
compile_obj: false
# - cpu: haswell
@@ -126,7 +126,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
- cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
obj: bun-obj-darwin-x64-baseline
runner: macos-11
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: false
compile_obj: true
# - cpu: haswell
@@ -144,7 +144,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
# - cpu: native
@@ -152,7 +152,7 @@ jobs:
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# runner: macos-arm64
# dependencies: true
# compile_obj: true
@@ -173,9 +173,9 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install ccache rust llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix ccache)/bin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix ccache)/bin" >> $GITHUB_PATH
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: ccache (dependencies)
uses: hendrikmuhs/ccache-action@v1.2
@@ -258,7 +258,7 @@ jobs:
package: bun-darwin-x64
runner: macos-11
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: haswell
# arch: x86_64
# tag: bun-darwin-x64
@@ -266,14 +266,14 @@ jobs:
# package: bun-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: native
# arch: aarch64
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# package: bun-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -292,8 +292,8 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install ccache rust llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: ccache (link)
uses: hendrikmuhs/ccache-action@v1.2
@@ -430,10 +430,14 @@ jobs:
unzip ${{matrix.tag}}.zip
cd ${{matrix.tag}}
chmod +x bun
sudo mv bun /usr/local/bin/bun
bun --version
pwd >> $GITHUB_PATH
./bun --version
- id: test
name: Test (node runner)
env:
SMTP_SENDGRID_SENDER: ${{ secrets.SMTP_SENDGRID_SENDER }}
TLS_MONGODB_DATABASE_URL: ${{ secrets.TLS_MONGODB_DATABASE_URL }}
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install

View File

@@ -117,7 +117,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
- cpu: haswell
@@ -126,7 +126,7 @@ jobs:
obj: bun-obj-darwin-x64
runner: macos-11
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: true
compile_obj: false
# - cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
- cpu: haswell
@@ -144,7 +144,7 @@ jobs:
obj: bun-obj-darwin-x64
runner: macos-11
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: false
compile_obj: true
# - cpu: native
@@ -152,7 +152,7 @@ jobs:
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-arm64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-arm64-lto.tar.gz"
# runner: macos-arm64
# dependencies: true
# compile_obj: true
@@ -173,8 +173,8 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install rust ccache llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: Download WebKit
if: matrix.compile_obj
@@ -260,7 +260,7 @@ jobs:
# package: bun-darwin-x64
# runner: macos-11
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
- cpu: haswell
arch: x86_64
tag: bun-darwin-x64
@@ -268,14 +268,14 @@ jobs:
package: bun-darwin-x64
runner: macos-11
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: native
# arch: aarch64
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# package: bun-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/may20/bun-webkit-macos-arm64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-5/bun-webkit-macos-arm64-lto.tar.gz"
# runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -294,8 +294,8 @@ jobs:
BUN_DEPS_OUT_DIR: ${{runner.temp}}/bun-deps
run: |
brew install rust ccache llvm@15 pkg-config coreutils libtool cmake libiconv automake openssl@1.1 ninja gnu-sed pkg-config esbuild --force
echo "export PATH=$(brew --prefix coreutils)/libexec/gnubin:\$PATH" >> $GITHUB_ENV
echo "export PATH=$(brew --prefix llvm@15)/bin:\$PATH" >> $GITHUB_ENV
echo "$(brew --prefix coreutils)/libexec/gnubin" >> $GITHUB_PATH
echo "$(brew --prefix llvm@15)/bin" >> $GITHUB_PATH
brew link --overwrite llvm@15
- name: Download WebKit
env:
@@ -432,10 +432,14 @@ jobs:
unzip ${{matrix.tag}}.zip
cd ${{matrix.tag}}
chmod +x bun
sudo mv bun /usr/local/bin/bun
bun --version
pwd >> $GITHUB_PATH
./bun --version
- id: test
name: Test (node runner)
env:
SMTP_SENDGRID_SENDER: ${{ secrets.SMTP_SENDGRID_SENDER }}
TLS_MONGODB_DATABASE_URL: ${{ secrets.TLS_MONGODB_DATABASE_URL }}
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install

View File

@@ -1,4 +1,4 @@
name: bun-release-canary
name: bun-release-types-canary
concurrency: release-canary
on:
push:

View File

@@ -156,8 +156,8 @@ jobs:
with:
images: oven/bun
tags: |
type=match,pattern=(bun-v)?(\d.\d.\d),group=2,value=${{ env.TAG }}
type=match,pattern=(bun-v)?(\d.\d),group=2,value=${{ env.TAG }}
type=match,pattern=(bun-v)?(\d+.\d+.\d+),group=2,value=${{ env.TAG }}
type=match,pattern=(bun-v)?(\d+.\d+),group=2,value=${{ env.TAG }}
- id: login
name: Login to Docker
uses: docker/login-action@v2

View File

@@ -1,7 +1,7 @@
name: zig-fmt
env:
ZIG_VERSION: 0.11.0-dev.2571+31738de28
ZIG_VERSION: 0.12.0-dev.163+6780a6bbf
on:
pull_request:
@@ -28,7 +28,7 @@ jobs:
run: |
curl https://ziglang.org/builds/zig-linux-x86_64-${{env.ZIG_VERSION}}.tar.xz -L -o zig.tar.xz
tar -xf zig.tar.xz
sudo mv zig-linux-x86_64-${{env.ZIG_VERSION}}/zig /usr/local/bin
echo "$(pwd)/zig-linux-x86_64-${{env.ZIG_VERSION}}" >> $GITHUB_PATH
- name: Run zig fmt
id: fmt
run: |

12
.gitignore vendored
View File

@@ -96,6 +96,8 @@ packages/bun-wasm/*.cjs
packages/bun-wasm/*.map
packages/bun-wasm/*.js
packages/bun-wasm/*.d.ts
packages/bun-wasm/*.d.cts
packages/bun-wasm/*.d.mts
*.bc
src/fallback.version
@@ -121,3 +123,13 @@ cold-jsc-start
cold-jsc-start.d
/test.ts
src/js/out/modules*
src/js/out/functions*
src/js/out/tmp
src/js/out/DebugPath.h
make-dev-stats.csv
.uuid
tsconfig.tsbuildinfo

15
.gitmodules vendored
View File

@@ -48,13 +48,6 @@ ignore = dirty
depth = 1
shallow = true
fetchRecurseSubmodules = false
[submodule "src/deps/uws"]
path = src/deps/uws
url = https://github.com/Jarred-Sumner/uWebSockets
ignore = dirty
depth = 1
shallow = true
fetchRecurseSubmodules = true
[submodule "src/deps/tinycc"]
path = src/deps/tinycc
url = https://github.com/Jarred-Sumner/tinycc.git
@@ -68,4 +61,10 @@ fetchRecurseSubmodules = false
[submodule "src/deps/zstd"]
path = src/deps/zstd
url = https://github.com/facebook/zstd.git
ignore = dirty
ignore = dirty
[submodule "src/deps/base64"]
path = src/deps/base64
url = https://github.com/aklomp/base64.git
ignore = dirty
depth = 1
shallow = true

View File

@@ -6,7 +6,7 @@ module.exports = {
quoteProps: "preserve",
overrides: [
{
files: "README.md",
files: ["*.md"],
options: {
printWidth: 80,
},

View File

@@ -0,0 +1,21 @@
// I would have made this a bash script but there isn't an easy way to track
// time in bash sub-second cross platform.
import fs from "fs";
const start = Date.now() + 5;
const result = Bun.spawnSync(process.argv.slice(2), {
stdio: ["inherit", "inherit", "inherit"],
});
const end = Date.now();
const diff = (Math.max(Math.round(end - start), 0) / 1000).toFixed(3);
const success = result.exitCode === 0;
try {
const line = `${new Date().toISOString()}, ${success ? "success" : "fail"}, ${diff}\n`;
if (fs.existsSync(".scripts/make-dev-stats.csv")) {
fs.appendFileSync(".scripts/make-dev-stats.csv", line);
} else {
fs.writeFileSync(".scripts/make-dev-stats.csv", line);
}
} catch {
// Ignore
}
process.exit(result.exitCode);

3
.scripts/write-versions.sh Normal file → Executable file
View File

@@ -7,11 +7,9 @@ LIBARCHIVE_VERSION=$(git rev-parse HEAD:./src/deps/libarchive)
PICOHTTPPARSER_VERSION=$(git rev-parse HEAD:./src/deps/picohttpparser)
BORINGSSL_VERSION=$(git rev-parse HEAD:./src/deps/boringssl)
ZLIB_VERSION=$(git rev-parse HEAD:./src/deps/zlib)
UWS_VERSION=$(git rev-parse HEAD:./src/deps/uws)
LOLHTML=$(git rev-parse HEAD:./src/deps/lol-html)
TINYCC=$(git rev-parse HEAD:./src/deps/tinycc)
C_ARES=$(git rev-parse HEAD:./src/deps/c-ares)
USOCKETS=$(cd src/deps/uws/uSockets && git rev-parse HEAD)
rm -rf src/generated_versions_list.zig
echo "// AUTO-GENERATED FILE. Created via .scripts/write-versions.sh" >src/generated_versions_list.zig
@@ -20,7 +18,6 @@ echo "pub const boringssl = \"$BORINGSSL_VERSION\";" >>src/generated_versions_li
echo "pub const libarchive = \"$LIBARCHIVE_VERSION\";" >>src/generated_versions_list.zig
echo "pub const mimalloc = \"$MIMALLOC_VERSION\";" >>src/generated_versions_list.zig
echo "pub const picohttpparser = \"$PICOHTTPPARSER_VERSION\";" >>src/generated_versions_list.zig
echo "pub const uws = \"$UWS_VERSION\";" >>src/generated_versions_list.zig
echo "pub const webkit = \"$WEBKIT_VERSION\";" >>src/generated_versions_list.zig
echo "pub const zig = @import(\"std\").fmt.comptimePrint(\"{}\", .{@import(\"builtin\").zig_version});" >>src/generated_versions_list.zig
echo "pub const zlib = \"$ZLIB_VERSION\";" >>src/generated_versions_list.zig

View File

@@ -15,11 +15,14 @@
"${workspaceFolder}/src/bun.js/bindings/webcore/",
"${workspaceFolder}/src/bun.js/bindings/sqlite/",
"${workspaceFolder}/src/bun.js/bindings/webcrypto/",
"${workspaceFolder}/src/bun.js/modules/",
"${workspaceFolder}/src/js/builtins/",
"${workspaceFolder}/src/js/out",
"${workspaceFolder}/src/deps/boringssl/include/",
"${workspaceFolder}/src/deps",
"${workspaceFolder}/src/deps/uws/uSockets/src"
"${workspaceFolder}/src/napi/*",
"${workspaceFolder}/packages/bun-usockets/src",
"${workspaceFolder}/packages/"
],
"browse": {
"path": [
@@ -31,6 +34,8 @@
"${workspaceFolder}/src/bun.js/WebKit/WebKitBuild/Release/WTF/Headers/**",
"${workspaceFolder}/src/bun.js/WebKit/WebKitBuild/Release/bmalloc/Headers/**",
"${workspaceFolder}/src/bun.js/bindings/*",
"${workspaceFolder}/src/bun.js/bindings/*",
"${workspaceFolder}/src/napi/*",
"${workspaceFolder}/src/bun.js/bindings/sqlite/",
"${workspaceFolder}/src/bun.js/bindings/webcrypto/",
"${workspaceFolder}/src/bun.js/bindings/webcore/",
@@ -39,7 +44,9 @@
"${workspaceFolder}/src/bun.js/modules/*",
"${workspaceFolder}/src/deps",
"${workspaceFolder}/src/deps/boringssl/include/",
"${workspaceFolder}/src/deps/uws/uSockets/src"
"${workspaceFolder}/packages/bun-usockets/",
"${workspaceFolder}/packages/bun-uws/",
"${workspaceFolder}/src/napi"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ".vscode/cppdb"

43
.vscode/launch.json generated vendored
View File

@@ -4,8 +4,6 @@
// it makes our tests very slow
// But it helps catch memory bugs
// SIGHUP must be ignored or the debugger will pause when a spawned subprocess exits:
// { "initCommands": ["process handle -p false -s false -n false SIGHUP"] }
"version": "0.2.0",
"configurations": [
{
@@ -14,13 +12,13 @@
"name": "bun test [file]",
"program": "bun-debug",
"args": ["test", "${file}"],
"cwd": "${fileDirname}",
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1",
"BUN_GARBAGE_COLLECTOR_LEVEL": "2"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -29,12 +27,12 @@
"name": "bun test [file] (fast)",
"program": "bun-debug",
"args": ["test", "${file}"],
"cwd": "${fileDirname}",
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
@@ -44,11 +42,11 @@
"name": "bun test [file] (verbose)",
"program": "bun-debug",
"args": ["test", "${file}"],
"cwd": "${fileDirname}",
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -57,12 +55,12 @@
"name": "bun test [file] --watch",
"program": "bun-debug",
"args": ["test", "--watch", "${file}"],
"cwd": "${fileDirname}",
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -71,12 +69,12 @@
"name": "bun test [file] --only",
"program": "bun-debug",
"args": ["test", "--only", "${file}"],
"cwd": "${fileDirname}",
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -91,7 +89,6 @@
"BUN_DEBUG_QUIET_LOGS": "1",
"BUN_GARBAGE_COLLECTOR_LEVEL": "2"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -100,12 +97,12 @@
"name": "bun test [*] (fast)",
"program": "bun-debug",
"args": ["test"],
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -114,12 +111,12 @@
"name": "bun test [*] --only",
"program": "bun-debug",
"args": ["test", "--only"],
// The cwd here must be the same as in CI. Or you will cause test failures that only happen in CI.
"cwd": "${workspaceFolder}/test",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -127,13 +124,12 @@
"request": "launch",
"name": "bun run [file]",
"program": "bun-debug",
"args": ["run", "${file}"],
"args": ["run", "${file}", "${file}"],
"cwd": "${fileDirname}",
"env": {
"FORCE_COLOR": "1",
"BUN_DEBUG_QUIET_LOGS": "1"
"NODE_ENV": "development"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -148,7 +144,6 @@
"BUN_DEBUG_QUIET_LOGS": "1",
"BUN_GARBAGE_COLLECTOR_LEVEL": "2"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -161,7 +156,6 @@
"env": {
"FORCE_COLOR": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -174,7 +168,6 @@
"env": {
"FORCE_COLOR": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -187,7 +180,6 @@
"env": {
"FORCE_COLOR": "1"
},
"initCommands": ["process handle -p false -s false -n false SIGHUP"],
"console": "internalConsole"
},
{
@@ -209,9 +201,7 @@
"console": "internalConsole",
"env": {
"BUN_CONFIG_MINIFY_WHITESPACE": "1"
},
// SIGHUP must be ignored or the debugger will pause when a spawned subprocess exits.
"initCommands": ["process handle -p false -s false -n false SIGHUP"]
}
},
{
"type": "lldb",
@@ -235,7 +225,6 @@
"console": "internalConsole",
"env": {}
},
{
"type": "lldb",
"request": "launch",
@@ -318,7 +307,7 @@
"name": "bun install",
"program": "bun-debug",
"args": ["install"],
"cwd": "${workspaceFolder}",
"cwd": "${fileDirname}",
"console": "internalConsole",
"env": {
"BUN_DEBUG_QUIET_LOGS": "1"

View File

@@ -2,11 +2,13 @@
"git.autoRepositoryDetection": "openEditors",
"search.quickOpen.includeSymbols": false,
"search.seedWithNearestWord": true,
"search.smartCase": false,
"search.smartCase": true,
"search.exclude": {},
"search.followSymlinks": false,
"search.useIgnoreFiles": true,
"zig.buildOnSave": false,
// We do this until we upgrade to latest Zig so that zls doesn't break our code.
"zig.formattingProvider": "extension",
"zig.buildArgs": ["obj", "-Dfor-editor"],
"zig.buildOption": "build",
"zig.buildFilePath": "${workspaceFolder}/build.zig",
@@ -77,7 +79,8 @@
"src/deps/tinycc": true,
"src/deps/zstd": true,
"test/snippets/package-json-exports/_node_modules_copy": true,
"src/js/out": true
"src/js/out": true,
"src/packages/bun-uws/fuzzing/seed-corpus/": true
},
"C_Cpp.files.exclude": {
"**/.vscode": true,

View File

@@ -47,34 +47,18 @@ TODO: document this (see [`bindings.zig`](src/bun.js/bindings/bindings.zig) and
Copy from examples like `Subprocess` or `Response`.
### ESM modules
### ESM Modules and Builtins JS
Bun implements ESM modules in a mix of native code and JavaScript.
Several Node.js modules are implemented in JavaScript and loosely based on browserify polyfills.
The ESM modules in Bun are located in [`src/bun.js/*.exports.js`](src/bun.js/). Unlike other code in Bun, these files are NOT transpiled. They are loaded directly into the JavaScriptCore VM. That means `require` does not work in these files. Instead, you must use `import.meta.require`, or ideally, not use require/import other files at all.
Builtin modules in Bun are located in [`src/js`](src/js/). These files are transpiled and support a JavaScriptCore-only syntax for internal slots, which is explained further in [`src/js/README.md`](src/js/README.md).
Native C++ modules are in `src/bun.js/modules/`.
The module loader is in [`src/bun.js/module_loader.zig`](src/bun.js/module_loader.zig).
### JavaScript Builtins
TODO: update this with the new build process that uses TypeScript and `$` instead of `@`.
JavaScript builtins are located in [`src/js/builtins/*.ts`](src/js/builtins).
These files support a JavaScriptCore-only syntax for internal slots. `@` is used to access an internal slot. For example: `new @Array(123)` will create a new `Array` similar to `new Array(123)`, except if a library modifies the `Array` global, it will not affect the internal slot (`@Array`). These names must be allow-listed in `BunBuiltinNames.h` (though JavaScriptCore allowlists some names by default).
They can not use or reference ESM-modules. The files that end with `*Internals.js` are automatically loaded globally. Most usage of internals right now are the stream implementations (which share a lot of code from Safari/WebKit) and ImportMetaObject (which is how `require` is implemented in the runtime)
To regenerate the builtins:
```sh
make clean-bindings && make generate-builtins && make bindings -j10
```
It is recommended that you have ccache installed or else you will spend a lot of time waiting for the bindings to compile.
### Memory management in Bun's JavaScript runtime
TODO: fill this out (for now, use `JSC.Strong` in most cases)

View File

@@ -10,9 +10,9 @@ ARG ARCH=x86_64
ARG BUILD_MACHINE_ARCH=x86_64
ARG TRIPLET=${ARCH}-linux-gnu
ARG BUILDARCH=amd64
ARG WEBKIT_TAG=may20
ARG WEBKIT_TAG=2023-aug3-5
ARG ZIG_TAG=jul1
ARG ZIG_VERSION="0.11.0-dev.2571+31738de28"
ARG ZIG_VERSION="0.12.0-dev.163+6780a6bbf"
ARG WEBKIT_BASENAME="bun-webkit-linux-$BUILDARCH"
ARG ZIG_FOLDERNAME=zig-linux-${BUILD_MACHINE_ARCH}-${ZIG_VERSION}
@@ -20,7 +20,7 @@ ARG ZIG_FILENAME=${ZIG_FOLDERNAME}.tar.xz
ARG WEBKIT_URL="https://github.com/oven-sh/WebKit/releases/download/$WEBKIT_TAG/${WEBKIT_BASENAME}.tar.gz"
ARG ZIG_URL="https://ziglang.org/builds/${ZIG_FILENAME}"
ARG GIT_SHA=""
ARG BUN_BASE_VERSION=0.6
ARG BUN_BASE_VERSION=1.0
FROM bitnami/minideb:bullseye as bun-base
@@ -284,7 +284,8 @@ ARG CPU_TARGET
ENV CPU_TARGET=${CPU_TARGET}
COPY Makefile ${BUN_DIR}/Makefile
COPY src/deps/uws ${BUN_DIR}/src/deps/uws
COPY packages/bun-uws ${BUN_DIR}/packages/bun-uws
COPY packages/bun-usockets ${BUN_DIR}/packages/bun-usockets
COPY src/deps/zlib ${BUN_DIR}/src/deps/zlib
COPY src/deps/boringssl/include ${BUN_DIR}/src/deps/boringssl/include
COPY src/deps/libuwsockets.cpp ${BUN_DIR}/src/deps/libuwsockets.cpp
@@ -293,7 +294,28 @@ COPY src/deps/_libusockets.h ${BUN_DIR}/src/deps/_libusockets.h
WORKDIR $BUN_DIR
RUN cd $BUN_DIR && \
make uws && rm -rf src/deps/uws Makefile
make uws && rm -rf packages/bun-uws Makefile
FROM bun-base as base64
ARG DEBIAN_FRONTEND
ARG GITHUB_WORKSPACE
ARG ZIG_PATH
# Directory extracts to "bun-webkit"
ARG WEBKIT_DIR
ARG BUN_RELEASE_DIR
ARG BUN_DEPS_OUT_DIR
ARG BUN_DIR
ARG CPU_TARGET
ENV CPU_TARGET=${CPU_TARGET}
COPY Makefile ${BUN_DIR}/Makefile
COPY src/deps/base64 ${BUN_DIR}/src/deps/base64
WORKDIR $BUN_DIR
RUN cd $BUN_DIR && \
make base64 && rm -rf src/deps/base64 Makefile
FROM bun-base as picohttp
@@ -556,6 +578,7 @@ ENV JSC_BASE_DIR=${WEBKIT_DIR}
ENV LIB_ICU_PATH=${WEBKIT_DIR}/lib
COPY --from=zlib ${BUN_DEPS_OUT_DIR}/*.a ${BUN_DEPS_OUT_DIR}/
COPY --from=base64 ${BUN_DEPS_OUT_DIR}/*.a ${BUN_DEPS_OUT_DIR}/
COPY --from=libarchive ${BUN_DEPS_OUT_DIR}/*.a ${BUN_DEPS_OUT_DIR}/
COPY --from=boringssl ${BUN_DEPS_OUT_DIR}/*.a ${BUN_DEPS_OUT_DIR}/
COPY --from=lolhtml ${BUN_DEPS_OUT_DIR}/*.a ${BUN_DEPS_OUT_DIR}/

209
Makefile
View File

@@ -6,8 +6,6 @@ BUN_AUTO_UPDATER_REPO = Jarred-Sumner/bun-releases-for-updater
CMAKE_CXX_COMPILER_LAUNCHER_FLAG :=
# 'make' command will trigger the help target
.DEFAULT_GOAL := help
@@ -20,7 +18,7 @@ CPU_TARGET ?= native
MARCH_NATIVE = -mtune=$(CPU_TARGET)
NATIVE_OR_OLD_MARCH =
MMD_IF_LOCAL =
MMD_IF_LOCAL =
DEFAULT_MIN_MACOS_VERSION=
ARCH_NAME :=
DOCKER_BUILDARCH =
@@ -40,7 +38,7 @@ NATIVE_OR_OLD_MARCH = -march=nehalem
endif
MIN_MACOS_VERSION ?= $(DEFAULT_MIN_MACOS_VERSION)
BUN_BASE_VERSION = 0.6
BUN_BASE_VERSION = 1.0
CI ?= false
@@ -52,6 +50,8 @@ endif
BUN_OR_NODE = $(shell which bun 2>/dev/null || which node 2>/dev/null)
CXX_VERSION=c++2a
TRIPLET = $(OS_NAME)-$(ARCH_NAME)
PACKAGE_NAME = bun-$(TRIPLET)
@@ -349,10 +349,10 @@ LINUX_INCLUDE_DIRS := $(ALL_JSC_INCLUDE_DIRS) \
-I$(ZLIB_INCLUDE_DIR)
UWS_INCLUDE_DIR := -I$(BUN_DEPS_DIR)/uws/uSockets/src -I$(BUN_DEPS_DIR)/uws/src -I$(BUN_DEPS_DIR)
UWS_INCLUDE_DIR := -I$(BUN_DIR)/packages/bun-usockets/src -I$(BUN_DIR)/packages -I$(BUN_DEPS_DIR)
INCLUDE_DIRS := $(UWS_INCLUDE_DIR) -I$(BUN_DEPS_DIR)/mimalloc/include -I$(BUN_DEPS_DIR)/zstd/include -Isrc/napi -I$(BUN_DEPS_DIR)/boringssl/include -I$(BUN_DEPS_DIR)/c-ares/include
INCLUDE_DIRS := $(UWS_INCLUDE_DIR) -I$(BUN_DEPS_DIR)/mimalloc/include -I$(BUN_DEPS_DIR)/zstd/include -Isrc/napi -I$(BUN_DEPS_DIR)/boringssl/include -I$(BUN_DEPS_DIR)/c-ares/include -Isrc/bun.js/modules
ifeq ($(OS_NAME),linux)
@@ -401,6 +401,7 @@ CLANG_FLAGS = $(INCLUDE_DIRS) \
-DSTATICALLY_LINKED_WITH_BMALLOC=1 \
-DBUILDING_WITH_CMAKE=1 \
-DBUN_SINGLE_THREADED_PER_VM_ENTRY_SCOPE=1 \
-DNAPI_EXPERIMENTAL=ON \
-DNDEBUG=1 \
-DNOMINMAX \
-DIS_BUILD \
@@ -453,7 +454,8 @@ MINIMUM_ARCHIVE_FILES = -L$(BUN_DEPS_OUT_DIR) \
-ldecrepit \
-lssl \
-lcrypto \
-llolhtml
-llolhtml \
-lbase64
ARCHIVE_FILES_WITHOUT_LIBCRYPTO = $(MINIMUM_ARCHIVE_FILES) \
-larchive \
@@ -553,18 +555,12 @@ tinycc:
PYTHON=$(shell which python 2>/dev/null || which python3 2>/dev/null || which python2 2>/dev/null)
.PHONY: builtins
builtins:
NODE_ENV=production bun src/js/builtins/codegen/index.ts --minify
.PHONY: esm
esm:
NODE_ENV=production bun src/js/build-esm.ts
.PHONY: generate-builtins
generate-builtins: builtins
js: # to rebundle js (rebuilding binary not needed to reload js code)
NODE_ENV=production bun src/js/_codegen/index.ts
esm-debug:
BUN_DEBUG_QUIET_LOGS=1 NODE_ENV=production bun-debug src/js/build-esm.ts
BUN_TYPES_REPO_PATH ?= $(realpath packages/bun-types)
@@ -665,8 +661,8 @@ else
PKGNAME_NINJA := ninja-build
endif
.PHONY: require
require:
.PHONY: assert-deps
assert-deps:
@echo "Checking if the required utilities are available..."
@if [ $(CLANG_VERSION) -lt "15" ]; then echo -e "ERROR: clang version >=15 required, found: $(CLANG_VERSION). Install with:\n\n $(POSIX_PKG_MANAGER) install llvm@15"; exit 1; fi
@cmake --version >/dev/null 2>&1 || (echo -e "ERROR: cmake is required."; exit 1)
@@ -678,10 +674,24 @@ require:
@which $(LIBTOOL) > /dev/null || (echo -e "ERROR: libtool is required. Install with:\n\n $(POSIX_PKG_MANAGER) install libtool"; exit 1)
@which ninja > /dev/null || (echo -e "ERROR: Ninja is required. Install with:\n\n $(POSIX_PKG_MANAGER) install $(PKGNAME_NINJA)"; exit 1)
@which pkg-config > /dev/null || (echo -e "ERROR: pkg-config is required. Install with:\n\n $(POSIX_PKG_MANAGER) install pkg-config"; exit 1)
@which rustc > /dev/null || (echo -e "ERROR: rustc is required." exit 1)
@which cargo > /dev/null || (echo -e "ERROR: cargo is required." exit 1)
@test $(shell cargo --version | awk '{print $$2}' | cut -d. -f2) -gt 57 || (echo -e "ERROR: cargo version must be at least 1.57."; exit 1)
@echo "You have the dependencies installed! Woo"
init-submodules:
git submodule update --init --recursive --progress --depth=1 --checkout
# the following allows you to run `make submodule` to update or init submodules. but we will exclude webkit
# unless you explicity clone it yourself (a huge download)
SUBMODULE_NAMES=$(shell cat .gitmodules | grep 'path = ' | awk '{print $$3}')
ifeq ("$(wildcard src/bun.js/WebKit/.git)", "")
SUBMODULE_NAMES := $(filter-out src/bun.js/WebKit, $(SUBMODULE_NAMES))
endif
.PHONY: init-submodules
init-submodules: submodule # (backwards-compatibility alias)
.PHONY: submodule
submodule: ## to init or update all submodules
git submodule update --init --recursive --progress --depth=1 --checkout $(SUBMODULE_NAMES)
.PHONY: build-obj
build-obj:
@@ -697,44 +707,46 @@ dev-build-obj-wasm:
.PHONY: dev-wasm
dev-wasm: dev-build-obj-wasm
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \
-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/libmimalloc.a.wasm \
packages/debug-bun-freestanding-wasm32/bun-wasm.o $(OPTIMIZATION_LEVEL) --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \
-g2 -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/$(MIMALLOC_FILE).wasm \
packages/debug-bun-freestanding-wasm32/bun-wasm.o --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \
-o packages/debug-bun-freestanding-wasm32/bun-wasm.wasm
cp packages/debug-bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm
cp packages/debug-bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm
.PHONY: build-obj-wasm
build-obj-wasm:
$(ZIG) build bun-wasm -Doptimize=ReleaseFast -Dtarget=wasm32-freestanding
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \
-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/libmimalloc.a.wasm \
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \
-s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/$(MIMALLOC_FILE).wasm \
packages/bun-freestanding-wasm32/bun-wasm.o $(OPTIMIZATION_LEVEL) --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \
-o packages/bun-freestanding-wasm32/bun-wasm.wasm
cp packages/bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm
cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm
.PHONY: build-obj-wasm-small
build-obj-wasm-small:
$(ZIG) build bun-wasm -Doptimize=ReleaseSmall -Dtarget=wasm32-freestanding
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \
-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/libmimalloc.a.wasm \
$(ZIG) build bun-wasm -Doptimize=ReleaseFast -Dtarget=wasm32-freestanding
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \
-Oz -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/$(MIMALLOC_FILE).wasm \
packages/bun-freestanding-wasm32/bun-wasm.o -Oz --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \
-o packages/bun-freestanding-wasm32/bun-wasm.wasm
cp packages/bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm
cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm
.PHONY: wasm
wasm: api build-obj-wasm-small
@rm -rf packages/bun-wasm/*.{d.ts,js,wasm,cjs,mjs,tsbuildinfo}
wasm: api mimalloc-wasm build-obj-wasm-small
@rm -rf packages/bun-wasm/*.{d.ts,d.cts,d.mts,js,wasm,cjs,mjs,tsbuildinfo}
@cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm
@cp src/api/schema.d.ts packages/bun-wasm/schema.d.ts
@cp src/api/schema.js packages/bun-wasm/schema.js
@cd packages/bun-wasm && $(NPM_CLIENT) run tsc -- -p .
@$(ESBUILD) --sourcemap=external --external:fs --define:process.env.NODE_ENV='"production"' --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=esm --minify 2> /dev/null
@cp packages/bun-wasm/index.d.ts packages/bun-wasm/index.d.cts
@mv packages/bun-wasm/index.d.ts packages/bun-wasm/index.d.mts
@bun build --sourcemap=external --external=fs --outdir=packages/bun-wasm --target=browser --minify ./packages/bun-wasm/index.ts
@mv packages/bun-wasm/index.js packages/bun-wasm/index.mjs
@mv packages/bun-wasm/index.js.map packages/bun-wasm/index.mjs.map
@$(ESBUILD) --sourcemap=external --external:fs --define:process.env.NODE_ENV='"production"' --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=cjs --minify --platform=node 2> /dev/null
@$(ESBUILD) --sourcemap=external --external:fs --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=cjs --minify --platform=node 2> /dev/null
@mv packages/bun-wasm/index.js packages/bun-wasm/index.cjs
@mv packages/bun-wasm/index.js.map packages/bun-wasm/index.cjs.map
@rm -rf packages/bun-wasm/*.tsbuildinfo
@@ -748,17 +760,17 @@ build-obj-safe:
UWS_CC_FLAGS = -pthread -DLIBUS_USE_OPENSSL=1 -DUWS_HTTPRESPONSE_NO_WRITEMARK=1 -DLIBUS_USE_BORINGSSL=1 -DWITH_BORINGSSL=1 -Wpedantic -Wall -Wextra -Wsign-conversion -Wconversion $(UWS_INCLUDE) -DUWS_WITH_PROXY
UWS_CXX_FLAGS = $(UWS_CC_FLAGS) -std=$(CXX_VERSION) -fno-exceptions -fno-rtti
UWS_LDFLAGS = -I$(BUN_DEPS_DIR)/boringssl/include -I$(ZLIB_INCLUDE_DIR)
USOCKETS_DIR = $(BUN_DEPS_DIR)/uws/uSockets/
USOCKETS_SRC_DIR = $(BUN_DEPS_DIR)/uws/uSockets/src/
USOCKETS_DIR = $(BUN_DIR)/packages/bun-usockets
USOCKETS_SRC_DIR = $(USOCKETS_DIR)/src
usockets:
rm -rf $(BUN_DEPS_DIR)/uws/uSockets/*.o $(BUN_DEPS_DIR)/uws/uSockets/**/*.o $(BUN_DEPS_DIR)/uws/uSockets/*.a $(BUN_DEPS_DIR)/uws/uSockets/*.bc
cd $(USOCKETS_DIR) && $(CC_WITH_CCACHE) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CFLAGS) $(UWS_CC_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.c) $(wildcard $(USOCKETS_SRC_DIR)/**/*.c)
cd $(USOCKETS_DIR) && $(CXX_WITH_CCACHE) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CXXFLAGS) $(UWS_CXX_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.cpp) $(wildcard $(USOCKETS_SRC_DIR)/**/*.cpp)
rm -rf $(USOCKETS_DIR)/*.i $(USOCKETS_DIR)/*.bc $(USOCKETS_DIR)/*.o $(USOCKETS_DIR)/*.s $(USOCKETS_DIR)/*.ii $(USOCKETS_DIR)/*.s
cd $(USOCKETS_DIR) && $(CC_WITH_CCACHE) -I$(USOCKETS_SRC_DIR) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CFLAGS) $(UWS_CC_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.c) $(wildcard $(USOCKETS_SRC_DIR)/**/*.c)
cd $(USOCKETS_DIR) && $(CXX_WITH_CCACHE) -I$(USOCKETS_SRC_DIR) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CXXFLAGS) $(UWS_CXX_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.cpp) $(wildcard $(USOCKETS_SRC_DIR)/**/*.cpp)
cd $(USOCKETS_DIR) && $(AR) rcvs $(BUN_DEPS_OUT_DIR)/libusockets.a $(USOCKETS_DIR)/*.{o,bc}
uws: usockets
$(CXX_WITH_CCACHE) -O2 $(EMIT_LLVM_FOR_RELEASE) -fPIC -I$(BUN_DEPS_DIR)/uws/uSockets/src $(CLANG_FLAGS) $(CFLAGS) $(UWS_CXX_FLAGS) $(UWS_LDFLAGS) $(PLATFORM_LINKER_FLAGS) -c -I$(BUN_DEPS_DIR) $(BUN_DEPS_OUT_DIR)/libusockets.a $(BUN_DEPS_DIR)/libuwsockets.cpp -o $(BUN_DEPS_OUT_DIR)/libuwsockets.o
$(CXX_WITH_CCACHE) -O2 $(EMIT_LLVM_FOR_RELEASE) -fPIC -I$(USOCKETS_SRC_DIR) $(CLANG_FLAGS) $(CFLAGS) $(UWS_CXX_FLAGS) $(UWS_LDFLAGS) $(PLATFORM_LINKER_FLAGS) -c -I$(BUN_DEPS_DIR) $(BUN_DEPS_OUT_DIR)/libusockets.a $(BUN_DEPS_DIR)/libuwsockets.cpp -o $(BUN_DEPS_OUT_DIR)/libuwsockets.o
.PHONY: sign-macos-x64
sign-macos-x64:
@@ -888,7 +900,8 @@ check-glibc-version-dependency:
ifeq ($(OS_NAME),darwin)
zig-win32:
$(ZIG) build -Dtarget=x86_64-windows
# Hardened runtime will not work with debugging
bun-codesign-debug:
@@ -932,6 +945,7 @@ headers:
$(ZIG) translate-c src/bun.js/bindings/headers.h > src/bun.js/bindings/headers.zig
$(BUN_OR_NODE) misctools/headers-cleaner.js
$(ZIG) fmt src/bun.js/bindings/headers.zig
$(CLANG_FORMAT) -i src/bun.js/bindings/ZigGeneratedCode.cpp
.PHONY: jsc-bindings-headers
jsc-bindings-headers: headers
@@ -1076,17 +1090,30 @@ test/wiptest/run: test/wiptest/run.o
release-bin-dir:
echo $(PACKAGE_DIR)
.PHONY: dev-obj-track
dev-obj-track:
bun .scripts/make-dev-timer.ts $(ZIG) build obj -freference-trace -Dcpu="$(CPU_TARGET)"
.PHONY: dev-obj-notrack
dev-obj-notrack:
$(ZIG) build obj -freference-trace -Dcpu="$(CPU_TARGET)"
.PHONY: dev-obj
dev-obj:
$(ZIG) build obj -freference-trace -Dcpu="$(CPU_TARGET)"
ifeq ($(shell which bun),)
dev-obj : dev-obj-notrack
else
dev-obj : dev-obj-track
endif
.PHONY: dev-obj-linux
dev-obj-linux:
$(ZIG) build obj -Dtarget=x86_64-linux-gnu -Dcpu="$(CPU_TARGET)"
.PHONY: dev
dev: mkdir-dev esm dev-obj link
mkdir-dev:
mkdir -p $(DEBUG_PACKAGE_DIR)
@@ -1170,10 +1197,12 @@ jsc-build-mac-compile:
-DPORT="JSCOnly" \
-DENABLE_STATIC_JSC=ON \
-DENABLE_SINGLE_THREADED_VM_ENTRY_SCOPE=ON \
-DCMAKE_BUILD_TYPE=relwithdebuginfo \
-DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \
-DCMAKE_BUILD_TYPE=Release \
-DUSE_THIN_ARCHIVES=OFF \
-DBUN_FAST_TLS=ON \
-DENABLE_FTL_JIT=ON \
-DUSE_BUN_JSC_ADDITIONS=ON \
-G Ninja \
$(CMAKE_FLAGS_WITHOUT_RELEASE) \
-DPTHREAD_JIT_PERMISSIONS_API=1 \
@@ -1192,9 +1221,11 @@ jsc-build-mac-compile-lto:
-DPORT="JSCOnly" \
-DENABLE_STATIC_JSC=ON \
-DENABLE_SINGLE_THREADED_VM_ENTRY_SCOPE=ON \
-DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \
-DCMAKE_BUILD_TYPE=Release \
-DUSE_THIN_ARCHIVES=OFF \
-DBUN_FAST_TLS=ON \
-DUSE_BUN_JSC_ADDITIONS=ON \
-DCMAKE_C_FLAGS="-flto=full" \
-DCMAKE_CXX_FLAGS="-flto=full" \
-DENABLE_FTL_JIT=ON \
@@ -1219,6 +1250,8 @@ jsc-build-mac-compile-debug:
-DUSE_THIN_ARCHIVES=OFF \
-DENABLE_FTL_JIT=ON \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DUSE_BUN_JSC_ADDITIONS=ON \
-DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \
-G Ninja \
$(CMAKE_FLAGS_WITHOUT_RELEASE) \
-DPTHREAD_JIT_PERMISSIONS_API=1 \
@@ -1237,11 +1270,13 @@ jsc-build-linux-compile-config:
cmake \
-DPORT="JSCOnly" \
-DENABLE_STATIC_JSC=ON \
-DCMAKE_BUILD_TYPE=relwithdebuginfo \
-DCMAKE_BUILD_TYPE=Release \
-DUSE_THIN_ARCHIVES=OFF \
-DUSE_BUN_JSC_ADDITIONS=ON \
-DENABLE_FTL_JIT=ON \
-DENABLE_REMOTE_INSPECTOR=ON \
-DJSEXPORT_PRIVATE=WTF_EXPORT_DECLARATION \
-DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \
-USE_VISIBILITY_ATTRIBUTE=1 \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-G Ninja \
@@ -1256,7 +1291,7 @@ jsc-build-linux-compile-config:
jsc-build-linux-compile-build:
mkdir -p $(WEBKIT_RELEASE_DIR) && \
cd $(WEBKIT_RELEASE_DIR) && \
CFLAGS="$(CFLAGS) -Wl,--whole-archive -ffat-lto-objects" CXXFLAGS="$(CXXFLAGS) -Wl,--whole-archive -ffat-lto-objects" \
CFLAGS="$(CFLAGS) -Wl,--whole-archive -ffat-lto-objects" CXXFLAGS="$(CXXFLAGS) -Wl,--whole-archive -ffat-lto-objects" -DUSE_BUN_JSC_ADDITIONS=ON \
cmake --build $(WEBKIT_RELEASE_DIR) --config relwithdebuginfo --target jsc
@@ -1353,16 +1388,16 @@ mimalloc:
mimalloc-wasm:
cd $(BUN_DEPS_DIR)/mimalloc; emcmake cmake -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; emmake make;
rm -rf $(BUN_DEPS_DIR)/mimalloc/CMakeCache* $(BUN_DEPS_DIR)/mimalloc/CMakeFiles
cd $(BUN_DEPS_DIR)/mimalloc; emcmake cmake -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -GNinja -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=OFF .; emmake cmake --build .;
cp $(BUN_DEPS_DIR)/mimalloc/$(MIMALLOC_INPUT_PATH) $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE).wasm
# alias for link, incase anyone still types that
.PHONY: bun-link-lld-debug
bun-link-lld-debug: link
# link a debug build of bun
.PHONY: link
link:
link: ## link a debug build of bun
$(CXX) $(BUN_LLD_FLAGS_DEBUG) $(DEBUG_FLAGS) $(SYMBOLS) \
-g \
$(DEBUG_BIN)/bun-debug.o \
@@ -1457,7 +1492,7 @@ generate-classes:
generate-sink:
bun src/bun.js/scripts/generate-jssink.js
$(CLANG_FORMAT) -i src/bun.js/bindings/JSSink.cpp src/bun.js/bindings/JSSink.h
$(WEBKIT_DIR)/Source/JavaScriptCore/create_hash_table src/bun.js/bindings/JSSink.cpp > src/bun.js/bindings/JSSinkLookupTable.h
./src/bun.js/scripts/create_hash_table src/bun.js/bindings/JSSink.cpp > src/bun.js/bindings/JSSinkLookupTable.h
$(SED) -i -e 's/#include "Lookup.h"//' src/bun.js/bindings/JSSinkLookupTable.h
$(SED) -i -e 's/namespace JSC {//' src/bun.js/bindings/JSSinkLookupTable.h
$(SED) -i -e 's/} \/\/ namespace JSC//' src/bun.js/bindings/JSSinkLookupTable.h
@@ -1691,7 +1726,7 @@ sizegen:
# Linux uses bundled SQLite3
ifeq ($(OS_NAME),linux)
sqlite:
$(CC) $(EMIT_LLVM_FOR_RELEASE) $(CFLAGS) $(INCLUDE_DIRS) -DSQLITE_ENABLE_COLUMN_METADATA= -DSQLITE_MAX_VARIABLE_NUMBER=250000 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 -DSQLITE_ENABLE_JSON1=1 $(SRC_DIR)/sqlite/sqlite3.c -c -o $(SQLITE_OBJECT)
$(CC) $(EMIT_LLVM_FOR_RELEASE) $(CFLAGS) $(INCLUDE_DIRS) -DSQLITE_ENABLE_COLUMN_METADATA= -DSQLITE_MAX_VARIABLE_NUMBER=250000 -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 -DSQLITE_ENABLE_FTS5=1 -DSQLITE_ENABLE_JSON1=1 $(SRC_DIR)/sqlite/sqlite3.c -c -o $(SQLITE_OBJECT)
endif
picohttp:
@@ -1787,7 +1822,7 @@ endif
endif
.PHONY: build-unit
build-unit: ## to build your unit tests
build-unit: # to build your unit tests
@rm -rf zig-out/bin/$(testname)
@mkdir -p zig-out/bin
zig test $(realpath $(testpath)) \
@@ -1805,7 +1840,7 @@ build-unit: ## to build your unit tests
cp zig-out/bin/$(testname) $(testbinpath)
.PHONY: run-all-unit-tests
run-all-unit-tests: ## to run your unit tests
run-all-unit-tests: # to run your unit tests
@rm -rf zig-out/bin/__main_test
@mkdir -p zig-out/bin
zig test src/main.zig \
@@ -1825,15 +1860,11 @@ run-all-unit-tests: ## to run your unit tests
run-unit:
@zig-out/bin/$(testname) $(ZIG)
.PHONY: help
help: ## to print this help
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {gsub("\\\\n",sprintf("\n%22c",""), $$2);printf "\033[36m%-20s\033[0m \t\t%s\n", $$1, $$2}' $(MAKEFILE_LIST)
.PHONY: test
test: build-unit run-unit
.PHONY: integration-test-dev
integration-test-dev: ## to run integration tests
integration-test-dev: # to run integration tests
USE_EXISTING_PROCESS=true TEST_SERVER_URL=http://localhost:3000 node test/scripts/browser.js
copy-install:
@@ -1847,6 +1878,10 @@ copy-to-bun-release-dir-bin:
PACKAGE_MAP = --pkg-begin async_io $(BUN_DIR)/src/io/io_darwin.zig --pkg-begin bun $(BUN_DIR)/src/bun_redirect.zig --pkg-end --pkg-end --pkg-begin javascript_core $(BUN_DIR)/src/jsc.zig --pkg-begin bun $(BUN_DIR)/src/bun_redirect.zig --pkg-end --pkg-end --pkg-begin bun $(BUN_DIR)/src/bun_redirect.zig --pkg-end
.PHONY: base64
base64:
cd $(BUN_DEPS_DIR)/base64 && make clean && rm -rf CMakeCache.txt CMakeFiles && cmake $(CMAKE_FLAGS) . && make
cp $(BUN_DEPS_DIR)/base64/libbase64.a $(BUN_DEPS_OUT_DIR)/libbase64.a
.PHONY: cold-jsc-start
cold-jsc-start:
@@ -1865,30 +1900,54 @@ cold-jsc-start:
misctools/cold-jsc-start.cpp -o cold-jsc-start
.PHONY: vendor-without-npm
vendor-without-npm: node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive lolhtml sqlite usockets uws tinycc c-ares zstd
vendor-without-npm: node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive lolhtml sqlite usockets uws tinycc c-ares zstd base64
.PHONY: vendor-without-check
vendor-without-check: npm-install vendor-without-npm
.PHONY: vendor
vendor: require init-submodules vendor-without-check
vendor: assert-deps submodule vendor-without-check
.PHONY: vendor-dev
vendor-dev: require init-submodules npm-install-dev vendor-without-npm
vendor-dev: assert-deps submodule npm-install-dev vendor-without-npm
.PHONY: bun
bun: vendor identifier-cache build-obj bun-link-lld-release bun-codesign-release-local
.PHONY: regenerate-bindings
regenerate-bindings:
@make clean-bindings builtins
.PHONY: cpp
cpp: ## compile src/js/builtins + all c++ code then link
@make clean-bindings js
@make bindings -j$(CPU_COUNT)
@make link
.PHONY: cpp
cpp-no-link:
@make clean-bindings js
@make bindings -j$(CPU_COUNT)
.PHONY: zig
zig: ## compile zig code then link
@make mkdir-dev dev-obj link
.PHONY: zig-no-link
zig-no-link:
@make mkdir-dev dev-obj
.PHONY: dev
dev: # combo of `make cpp` and `make zig`
@make cpp-no-link zig-no-link -j2
@make link
.PHONY: setup
setup: vendor-dev identifier-cache clean-bindings
make jsc-check
make bindings -j$(CPU_COUNT)
make jsc-check dev
@echo ""
@echo "Development environment setup complete"
@echo "Run \`make dev\` to build \`bun-debug\`"
@echo "First build complete!"
@echo "\"bun-debug\" is available at $(DEBUG_BIN)/bun-debug"
@echo ""
.PHONY: help
help: ## to print this help
@echo "For detailed build instructions, see https://bun.sh/docs/project/development"
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {gsub("\\\\n",sprintf("\n%22c",""), $$2);printf "\033[36m%-20s\033[0m \t\t%s\n", $$1, $$2}' $(MAKEFILE_LIST)

View File

@@ -24,7 +24,7 @@
## What is Bun?
> **Bun is still under development.** Use it to speed up your development workflows or run simpler production code in resource-constrained environments like serverless functions. We're working on more complete Node.js compatibility and integration with existing frameworks. Join the [Discord](https://bun.sh/discord) and watch the [GitHub repository](https://github.com/oven-sh/bun) to keeps tabs on future releases.
> **Bun is still under development.** Use it to speed up your development workflows or run simpler production code in resource-constrained environments like serverless functions. We're working on more complete Node.js compatibility and integration with existing frameworks. Join the [Discord](https://bun.sh/discord) and watch the [GitHub repository](https://github.com/oven-sh/bun) to keep tabs on future releases.
Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a single executable called `bun`.
@@ -123,7 +123,6 @@ bun upgrade --canary
- [HTMLRewriter](https://bun.sh/docs/api/html-rewriter)
- [Testing](https://bun.sh/docs/api/test)
- [Utils](https://bun.sh/docs/api/utils)
- [DNS](https://bun.sh/docs/api/dns)
- [Node-API](https://bun.sh/docs/api/node-api)
## Contributing

View File

@@ -0,0 +1,30 @@
// https://github.com/nodejs/node/issues/34493
import { AsyncLocalStorage } from "async_hooks";
const asyncLocalStorage = new AsyncLocalStorage();
// let fn = () => Promise.resolve(2).then(() => new Promise(resolve => queueMicrotask(resolve)));
let fn = () => /test/.test("test");
let runWithExpiry = async (expiry, fn) => {
let iterations = 0;
while (Date.now() < expiry) {
await fn();
iterations++;
}
return iterations;
};
console.log(`Performed ${await runWithExpiry(Date.now() + 1000, fn)} iterations to warmup`);
let withAls;
await asyncLocalStorage.run(123, async () => {
withAls = await runWithExpiry(Date.now() + 45000, fn);
console.log(`Performed ${withAls} iterations (with ALS enabled)`);
});
asyncLocalStorage.disable();
let withoutAls = await runWithExpiry(Date.now() + 45000, fn);
console.log(`Performed ${withoutAls} iterations (with ALS disabled)`);
console.log("ALS penalty: " + Math.round((1 - withAls / withoutAls) * 10000) / 100 + "%");

View File

@@ -3,6 +3,6 @@
"module": "index.ts",
"type": "module",
"devDependencies": {
"bun-types": "^0.5.0"
"bun-types": "^0.7.0"
}
}
}

View File

@@ -10,7 +10,7 @@ To run in Bun:
```bash
# so it doesn't run the vitest one
bun wiptest expect-to-equal.test.js
bun test expect-to-equal.test.js
```
To run in Jest:

View File

@@ -43,7 +43,7 @@ pub fn main() anyerror!void {
var position = try std.fmt.parseInt(u32, position_str, 10);
const filepath = try std.fs.path.resolve(allocator, &.{basepath});
var file = try std.fs.openFileAbsolute(filepath, .{ .write = true });
var ms = @truncate(u64, (try std.fmt.parseInt(u128, args[args.len - 1], 10)) * std.time.ns_per_ms);
var ms = @as(u64, @truncate((try std.fmt.parseInt(u128, args[args.len - 1], 10)) * std.time.ns_per_ms));
std.debug.assert(ms > 0);
// std.debug.assert(std.math.isFinite(position));
var prng = std.rand.DefaultPrng.init(0);
@@ -125,30 +125,30 @@ pub fn main() anyerror!void {
);
};
counters[counter].timestamp = @truncate(u64, @intCast(u128, std.time.nanoTimestamp()) / (std.time.ns_per_ms / 10));
counters[counter].timestamp = @as(u64, @truncate(@as(u128, @intCast(std.time.nanoTimestamp())) / (std.time.ns_per_ms / 10)));
counters[counter].rotate = rotate % 360;
counters[counter].percent = std.math.mod(f64, std.math.round(((progress_bar + 1.0) / destination_count) * 1000) / 1000, 100) catch 0;
counters[counter].color_values[0] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][0] + 1) % 256)) * 0.8));
counters[counter].color_values[1] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][1] + 1) % 256)) * 0.8));
counters[counter].color_values[2] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][2] + 1) % 256)) * 0.8));
counters[counter].color_values[0] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[1] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[2] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[3] = (colors[0][0] + 1) % 256;
counters[counter].color_values[4] = (colors[0][1] + 1) % 256;
counters[counter].color_values[5] = (colors[0][2] + 1) % 256;
counters[counter].color_values[6] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][0] + 1) % 256)) * 0.8));
counters[counter].color_values[7] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][1] + 1) % 256)) * 0.8));
counters[counter].color_values[8] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][2] + 1) % 256)) * 0.8));
counters[counter].color_values[6] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[7] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[8] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[9] = (colors[1][0] + 1) % 256;
counters[counter].color_values[10] = (colors[1][1] + 1) % 256;
counters[counter].color_values[11] = (colors[1][2] + 1) % 256;
counters[counter].color_values[12] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][0] + 1) % 256)) * 0.8));
counters[counter].color_values[13] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][1] + 1) % 256)) * 0.8));
counters[counter].color_values[14] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][2] + 1) % 256)) * 0.8));
counters[counter].color_values[12] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[13] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[14] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[15] = (colors[2][0] + 1) % 256;
counters[counter].color_values[16] = (colors[2][1] + 1) % 256;
counters[counter].color_values[17] = (colors[2][2] + 1) % 256;
counters[counter].color_values[18] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][0] + 1) % 256)) * 0.8));
counters[counter].color_values[19] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][1] + 1) % 256)) * 0.8));
counters[counter].color_values[20] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][2] + 1) % 256)) * 0.8));
counters[counter].color_values[18] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[19] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[20] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[21] = (colors[3][0] + 1) % 256;
counters[counter].color_values[22] = (colors[3][1] + 1) % 256;
counters[counter].color_values[23] = (colors[3][2] + 1) % 256;
@@ -203,7 +203,7 @@ pub fn main() anyerror!void {
_ = try recorder.wait();
all_timestamps[0] = wrote.len;
for (counters) |count, i| {
for (counters, 0..) |count, i| {
all_timestamps[i + 1] = count.timestamp;
}

View File

@@ -43,7 +43,7 @@ pub fn main() anyerror!void {
var position = try std.fmt.parseInt(u32, position_str, 10);
const filepath = try std.fs.path.resolve(allocator, &.{basepath});
var file = try std.fs.openFileAbsolute(filepath, .{ .write = true });
var ms = @truncate(u64, (try std.fmt.parseInt(u128, args[args.len - 1], 10)) * std.time.ns_per_ms);
var ms = @as(u64, @truncate((try std.fmt.parseInt(u128, args[args.len - 1], 10)) * std.time.ns_per_ms));
std.debug.assert(ms > 0);
// std.debug.assert(std.math.isFinite(position));
var prng = std.rand.DefaultPrng.init(0);
@@ -112,30 +112,30 @@ pub fn main() anyerror!void {
\\
++ SIMULATE_LONG_FILE;
counters[counter].timestamp = @truncate(u64, @intCast(u128, std.time.nanoTimestamp()) / (std.time.ns_per_ms / 10));
counters[counter].timestamp = @as(u64, @truncate(@as(u128, @intCast(std.time.nanoTimestamp())) / (std.time.ns_per_ms / 10)));
counters[counter].rotate = rotate % 360;
counters[counter].percent = std.math.mod(f64, std.math.round(((progress_bar + 1.0) / destination_count) * 1000) / 1000, 100) catch 0;
counters[counter].color_values[0] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][0] + 1) % 256)) * 0.8));
counters[counter].color_values[1] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][1] + 1) % 256)) * 0.8));
counters[counter].color_values[2] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][2] + 1) % 256)) * 0.8));
counters[counter].color_values[0] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[1] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[2] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[0][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[3] = (colors[0][0] + 1) % 256;
counters[counter].color_values[4] = (colors[0][1] + 1) % 256;
counters[counter].color_values[5] = (colors[0][2] + 1) % 256;
counters[counter].color_values[6] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][0] + 1) % 256)) * 0.8));
counters[counter].color_values[7] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][1] + 1) % 256)) * 0.8));
counters[counter].color_values[8] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][2] + 1) % 256)) * 0.8));
counters[counter].color_values[6] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[7] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[8] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[1][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[9] = (colors[1][0] + 1) % 256;
counters[counter].color_values[10] = (colors[1][1] + 1) % 256;
counters[counter].color_values[11] = (colors[1][2] + 1) % 256;
counters[counter].color_values[12] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][0] + 1) % 256)) * 0.8));
counters[counter].color_values[13] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][1] + 1) % 256)) * 0.8));
counters[counter].color_values[14] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][2] + 1) % 256)) * 0.8));
counters[counter].color_values[12] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[13] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[14] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[2][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[15] = (colors[2][0] + 1) % 256;
counters[counter].color_values[16] = (colors[2][1] + 1) % 256;
counters[counter].color_values[17] = (colors[2][2] + 1) % 256;
counters[counter].color_values[18] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][0] + 1) % 256)) * 0.8));
counters[counter].color_values[19] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][1] + 1) % 256)) * 0.8));
counters[counter].color_values[20] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][2] + 1) % 256)) * 0.8));
counters[counter].color_values[18] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][0] + 1) % 256))) * 0.8)));
counters[counter].color_values[19] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][1] + 1) % 256))) * 0.8)));
counters[counter].color_values[20] = @as(u32, @intFromFloat(std.math.round(@as(f64, @floatFromInt(((colors[3][2] + 1) % 256))) * 0.8)));
counters[counter].color_values[21] = (colors[3][0] + 1) % 256;
counters[counter].color_values[22] = (colors[3][1] + 1) % 256;
counters[counter].color_values[23] = (colors[3][2] + 1) % 256;
@@ -190,7 +190,7 @@ pub fn main() anyerror!void {
_ = try recorder.wait();
all_timestamps[0] = wrote.len;
for (counters) |count, i| {
for (counters, 0..) |count, i| {
all_timestamps[i + 1] = count.timestamp;
}

View File

@@ -5,4 +5,4 @@
"jsx": "react-jsx",
"paths": {}
}
}
}

View File

@@ -1,11 +1,33 @@
# `install` benchmark
Requires [`hyperfine`](https://github.com/sharkdp/hyperfine)
Requires [`hyperfine`](https://github.com/sharkdp/hyperfine). The goal of this benchmark is to compare installation performance of Bun with other package managers _when caches are hot_.
```
### With lockfile, online mode
To run the benchmark with the standard "install" command for each package manager:
```sh
$ hyperfine --prepare 'rm -rf node_modules' --warmup 1 --runs 3 'bun install' 'pnpm install' 'yarn' 'npm install'
```
### With lockfile, offline mode
Even though all packages are cached, some tools may hit the npm API during the version resolution step. (This is not the same as re-downloading a package.) To entirely avoid network calls, the other package managers require `--prefer-offline/--offline` flag. To run the benchmark using "offline" mode:
```sh
$ hyperfine --prepare 'rm -rf node_modules' --runs 1 'bun install' 'pnpm install --prefer-offline' 'yarn --offline' 'npm install --prefer-offline'
```
### Without lockfile, offline mode
To run the benchmark with offline mode but without lockfiles:
```sh
$ hyperfine --prepare 'rm -rf node_modules' --warmup 1 'rm bun.lockb && bun install' 'rm pnpm-lock.yaml && pnpm install --prefer-offline' 'rm yarn.lock && yarn --offline' 'rm package-lock.json && npm install --prefer-offline'
```
##
To check that the app is working as expected:
```

View File

@@ -1,4 +1,4 @@
import { bench, run } from "../node_modules/mitata/src/cli.mjs";
import { bench, run } from "mitata";
bench("noop", function () {});
bench("async function(){}", async function () {});

View File

@@ -0,0 +1,29 @@
import { bench, run } from "./runner.mjs";
import { Buffer } from "node:buffer";
import crypto from "node:crypto";
const bigBuffer = Buffer.from("hello world".repeat(10000));
const converted = bigBuffer.toString("base64");
const uuid = crypto.randomBytes(16);
bench(`Buffer(${bigBuffer.byteLength}).toString('base64')`, () => {
return bigBuffer.toString("base64");
});
bench(`Buffer(${uuid.byteLength}).toString('base64')`, () => {
return uuid.toString("base64");
});
bench(`Buffer(${bigBuffer.byteLength}).toString('hex')`, () => {
return bigBuffer.toString("hex");
});
bench(`Buffer(${uuid.byteLength}).toString('hex')`, () => {
return uuid.toString("hex");
});
bench(`Buffer(${bigBuffer.byteLength}).toString('ascii')`, () => {
return bigBuffer.toString("ascii");
});
await run();

3
bench/snippets/cp-r.mjs Normal file
View File

@@ -0,0 +1,3 @@
import { cp } from "fs/promises";
await cp(process.argv[2], process.argv[3], { recursive: true });

31
bench/snippets/cp.mjs Normal file
View File

@@ -0,0 +1,31 @@
import { mkdirSync, writeFileSync } from "fs";
import { bench, run } from "./runner.mjs";
import { cp } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
const hugeDirectory = (() => {
const root = join(tmpdir(), "huge");
const base = join(root, "directory", "for", "benchmarks", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
mkdirSync(base, {
recursive: true,
});
for (let i = 0; i < 1000; i++) {
writeFileSync(join(base, "file-" + i + ".txt"), "Hello, world! " + i);
}
return root;
})();
const hugeFilePath = join(tmpdir(), "huge-file-0.txt");
const hugeText = "Hello, world!".repeat(1000000);
writeFileSync(hugeFilePath, hugeText);
var hugeCopyI = 0;
bench("cp -r (1000 files)", async b => {
await cp(hugeDirectory, join(tmpdir(), "huge-copy" + hugeCopyI++), { recursive: true });
});
bench("cp 1 " + ((hugeText.length / 1024) | 0) + " KB file", async b => {
await cp(hugeFilePath, join(tmpdir(), "huge-file" + hugeCopyI++));
});
await run();

View File

@@ -1,12 +1,6 @@
// so it can run in environments without node module resolution
import { bench, run } from "../node_modules/mitata/src/cli.mjs";
var crypto = globalThis.crypto;
if (!crypto) {
crypto = await import("node:crypto");
}
import crypto from "node:crypto";
var foo = new Uint8Array(65536);
bench("crypto.getRandomValues(65536)", () => {
crypto.getRandomValues(foo);
@@ -22,4 +16,8 @@ bench("crypto.randomUUID()", () => {
return crypto.randomUUID()[2];
});
bench("crypto.randomInt()", () => {
return crypto.randomInt(0, 100);
});
await run();

View File

@@ -0,0 +1,12 @@
import { bench, run } from "./runner.mjs";
var err = new Error();
bench("Error.captureStackTrace(err)", () => {
Error.captureStackTrace(err);
});
bench("Error.prototype.stack", () => {
new Error().stack;
});
await run();

View File

@@ -0,0 +1,65 @@
// This is a stress test of some internals in How Bun does the module.exports assignment.
// If it crashes or throws then this fails
import("./runner.mjs").then(({ bench, run }) => {
bench("Object.defineProperty(module, 'exports', { get() { return 42; } })", () => {
Object.defineProperty(module, "exports", {
get() {
return 42;
},
set() {
throw new Error("bad");
},
configurable: true,
});
if (module.exports !== 42) throw new Error("bad");
if (!Object.getOwnPropertyDescriptor(module, "exports").get) throw new Error("bad");
});
bench("Object.defineProperty(module.exports = {})", () => {
Object.defineProperty(module, "exports", {
value: { abc: 123 },
});
if (!module.exports.abc) throw new Error("bad");
if (Object.getOwnPropertyDescriptor(module, "exports").value !== module.exports) throw new Error("bad");
});
bench("module.exports = {}", () => {
module.exports = { abc: 123 };
if (!module.exports.abc) throw new Error("bad");
if (Object.getOwnPropertyDescriptor(module, "exports").value !== module.exports) throw new Error("bad");
});
run().then(() => {
module.exports = {
a: 1,
};
console.log(
module?.exports,
require.cache[module.id].exports,
module?.exports === require.cache[module.id],
__dirname,
Object.keys(require(module.id)),
require(module.id),
);
module.exports = function lol() {
return 42;
};
console.log(module.exports, module.exports());
queueMicrotask(() => {
console.log(
module?.exports,
require.cache[module.id].exports,
module?.exports === require.cache[module.id]?.exports,
__dirname,
Object.keys(require(module.id)),
require(module.id),
);
});
});
});

View File

@@ -0,0 +1,80 @@
import { bench, run } from "../node_modules/mitata/src/cli.mjs";
// This is a benchmark of the performance impact of using private properties.
bench("Polyfillprivate", () => {
"use strict";
var __classPrivateFieldGet =
(this && this.__classPrivateFieldGet) ||
function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet =
(this && this.__classPrivateFieldSet) ||
function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value;
};
var _Foo_state, _Foo_inc;
class Foo {
constructor() {
_Foo_state.set(this, 1);
_Foo_inc.set(this, 13);
}
run() {
let n = 1000000;
while (n-- > 0) {
__classPrivateFieldSet(
this,
_Foo_state,
__classPrivateFieldGet(this, _Foo_state, "f") + __classPrivateFieldGet(this, _Foo_inc, "f"),
"f",
);
}
return n;
}
}
(_Foo_state = new WeakMap()), (_Foo_inc = new WeakMap());
new Foo().run();
});
bench("NativePrivates", () => {
class Foo {
#state = 1;
#inc = 13;
run() {
let n = 1000000;
while (n-- > 0) {
this.#state += this.#inc;
}
return n;
}
}
new Foo().run();
});
bench("ConventionalPrivates", () => {
class Foo {
_state = 1;
_inc = 13;
run() {
let n = 1000000;
while (n-- > 0) {
this._state += this._inc;
}
return n;
}
}
new Foo().run();
});
await run();

View File

@@ -0,0 +1,33 @@
import { bench, run } from "./runner.mjs";
import { performance } from "perf_hooks";
bench("process.memoryUsage()", () => {
process.memoryUsage();
});
bench("process.memoryUsage.rss()", () => {
process.memoryUsage.rss();
});
bench("process.cpuUsage()", () => {
process.cpuUsage();
});
const init = process.cpuUsage();
bench("process.cpuUsage(delta)", () => {
process.cpuUsage(init);
});
bench("performance.now()", () => {
performance.now();
});
bench("process.hrtime()", () => {
process.hrtime();
});
bench("process.hrtime.bigint()", () => {
process.hrtime.bigint();
});
await run();

View File

@@ -0,0 +1,17 @@
import { bench, run } from "./runner.mjs";
import { readFileSync, existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
bench(`readFileSync(/tmp/404-not-found)`, () => {
try {
readFileSync("/tmp/404-not-found");
} catch (e) {}
});
bench(`readFile(/tmp/404-not-found)`, async () => {
try {
await readFile("/tmp/404-not-found");
} catch (e) {}
});
await run();

View File

@@ -1,4 +1,10 @@
import { realpathSync } from "node:fs";
const count = parseInt(process.env.ITERATIONS || "1", 10) || 1;
const arg = process.argv[process.argv.length - 1];
for (let i = 0; i < count; i++) realpathSync(arg);
import { bench, run } from "./runner.mjs";
bench("realpathSync x " + count, () => {
for (let i = 0; i < count; i++) realpathSync(arg, "utf-8");
});
await run();

View File

@@ -0,0 +1,15 @@
// This mostly exists to check for a memory leak in response.clone()
import { bench, run } from "./runner.mjs";
const req = new Request("http://localhost:3000/");
const resp = await fetch("http://example.com");
bench("req.clone().url", () => {
return req.clone().url;
});
bench("resp.clone().url", () => {
return resp.clone().url;
});
await run();

View File

@@ -0,0 +1,136 @@
// This snippet mostly exists to reproduce a memory leak
//
import { bench, run } from "mitata";
const obj = {
"id": 1296269,
"node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
"name": "Hello-World",
"full_name": "octocat/Hello-World",
"owner": {
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false,
},
"private": false,
"html_url": "https://github.com/octocat/Hello-World",
"description": "This your first repo!",
"fork": false,
"url": "https://api.github.com/repos/octocat/Hello-World",
"archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
"assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
"blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
"branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
"collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
"comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
"commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
"compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
"contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
"contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
"deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
"downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
"events_url": "https://api.github.com/repos/octocat/Hello-World/events",
"forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
"git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
"git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
"git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
"git_url": "git:github.com/octocat/Hello-World.git",
"issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
"issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
"issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
"keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
"labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
"languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
"merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
"milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
"notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
"pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
"releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
"ssh_url": "git@github.com:octocat/Hello-World.git",
"stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
"statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
"subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
"subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
"tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
"teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
"trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
"clone_url": "https://github.com/octocat/Hello-World.git",
"mirror_url": "git:git.example.com/octocat/Hello-World",
"hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",
"svn_url": "https://svn.github.com/octocat/Hello-World",
"homepage": "https://github.com",
"language": null,
"forks_count": 9,
"stargazers_count": 80,
"watchers_count": 80,
"size": 108,
"default_branch": "master",
"open_issues_count": 0,
"is_template": false,
"topics": ["octocat", "atom", "electron", "api"],
"has_issues": true,
"has_projects": true,
"has_wiki": true,
"has_pages": false,
"has_downloads": true,
"has_discussions": false,
"archived": false,
"disabled": false,
"visibility": "public",
"pushed_at": "2011-01-26T19:06:43Z",
"created_at": "2011-01-26T19:01:12Z",
"updated_at": "2011-01-26T19:14:43Z",
"permissions": {
"admin": false,
"push": false,
"pull": true,
},
"security_and_analysis": {
"advanced_security": {
"status": "enabled",
},
"secret_scanning": {
"status": "enabled",
},
"secret_scanning_push_protection": {
"status": "disabled",
},
},
};
// Force the string to be 8bit
const str = String.fromCharCode(
...JSON.stringify(obj)
.split("")
.map(a => a.charCodeAt(0)),
);
var i = 0;
bench("new Response().arrayBuffer() (new string each call, latin1)", async () => {
return await new Response(str + i++).arrayBuffer();
});
bench("new Response().arrayBuffer() (new string each call, utf16)", async () => {
return await new Response(str + i++ + "😊").arrayBuffer();
});
bench("new Response().arrayBuffer() (existing string, latin1)", async () => {
return await new Response(str).arrayBuffer();
});
await run();

View File

@@ -0,0 +1,123 @@
// This snippet mostly exists to reproduce a memory leak
import { bench, run } from "mitata";
const obj = {
"id": 1296269,
"node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
"name": "Hello-World",
"full_name": "octocat/Hello-World",
"owner": {
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false,
},
"private": false,
"html_url": "https://github.com/octocat/Hello-World",
"description": "This your first repo!",
"fork": false,
"url": "https://api.github.com/repos/octocat/Hello-World",
"archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
"assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
"blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
"branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
"collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
"comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
"commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
"compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
"contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
"contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
"deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
"downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
"events_url": "https://api.github.com/repos/octocat/Hello-World/events",
"forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
"git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
"git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
"git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
"git_url": "git:github.com/octocat/Hello-World.git",
"issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
"issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
"issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
"keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
"labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
"languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
"merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
"milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
"notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
"pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
"releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
"ssh_url": "git@github.com:octocat/Hello-World.git",
"stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
"statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
"subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
"subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
"tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
"teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
"trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
"clone_url": "https://github.com/octocat/Hello-World.git",
"mirror_url": "git:git.example.com/octocat/Hello-World",
"hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",
"svn_url": "https://svn.github.com/octocat/Hello-World",
"homepage": "https://github.com",
"language": null,
"forks_count": 9,
"stargazers_count": 80,
"watchers_count": 80,
"size": 108,
"default_branch": "master",
"open_issues_count": 0,
"is_template": false,
"topics": ["octocat", "atom", "electron", "api"],
"has_issues": true,
"has_projects": true,
"has_wiki": true,
"has_pages": false,
"has_downloads": true,
"has_discussions": false,
"archived": false,
"disabled": false,
"visibility": "public",
"pushed_at": "2011-01-26T19:06:43Z",
"created_at": "2011-01-26T19:01:12Z",
"updated_at": "2011-01-26T19:14:43Z",
"permissions": {
"admin": false,
"push": false,
"pull": true,
},
"security_and_analysis": {
"advanced_security": {
"status": "enabled",
},
"secret_scanning": {
"status": "enabled",
},
"secret_scanning_push_protection": {
"status": "disabled",
},
},
};
bench("Response.json(obj)", async () => {
return Response.json(obj);
});
bench("Response.json(obj).json()", async () => {
return await Response.json(obj).json();
});
await run();

View File

@@ -0,0 +1 @@
for (let i = 0; i < 9999999; i++) new Request("http://aaaaaaaaaaaaaaaaaaaaa");

View File

@@ -0,0 +1,37 @@
import { bench, run } from "./runner.mjs";
const blob = new Blob(["<p id='foo'>Hello</p>"]);
bench("prepend", async () => {
await new HTMLRewriter()
.on("p", {
element(element) {
element.prepend("Hello");
},
})
.transform(new Response(blob))
.text();
});
bench("append", async () => {
await new HTMLRewriter()
.on("p", {
element(element) {
element.append("Hello");
},
})
.transform(new Response(blob))
.text();
});
bench("getAttribute", async () => {
await new HTMLRewriter()
.on("p", {
element(element) {
element.getAttribute("id");
},
})
.transform(new Response(blob))
.text();
});
await run();

View File

@@ -0,0 +1,128 @@
import { serialize, deserialize } from "node:v8";
import { bench, run } from "./runner.mjs";
const obj = {
"id": 1296269,
"node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
"name": "Hello-World",
"full_name": "octocat/Hello-World",
"owner": {
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false,
},
"private": false,
"html_url": "https://github.com/octocat/Hello-World",
"description": "This your first repo!",
"fork": false,
"url": "https://api.github.com/repos/octocat/Hello-World",
"archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
"assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
"blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
"branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
"collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
"comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
"commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
"compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
"contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
"contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
"deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
"downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
"events_url": "https://api.github.com/repos/octocat/Hello-World/events",
"forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
"git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
"git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
"git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
"git_url": "git:github.com/octocat/Hello-World.git",
"issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
"issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
"issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
"keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
"labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
"languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
"merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
"milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
"notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
"pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
"releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
"ssh_url": "git@github.com:octocat/Hello-World.git",
"stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
"statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
"subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
"subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
"tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
"teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
"trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
"clone_url": "https://github.com/octocat/Hello-World.git",
"mirror_url": "git:git.example.com/octocat/Hello-World",
"hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",
"svn_url": "https://svn.github.com/octocat/Hello-World",
"homepage": "https://github.com",
"language": null,
"forks_count": 9,
"stargazers_count": 80,
"watchers_count": 80,
"size": 108,
"default_branch": "master",
"open_issues_count": 0,
"is_template": false,
"topics": ["octocat", "atom", "electron", "api"],
"has_issues": true,
"has_projects": true,
"has_wiki": true,
"has_pages": false,
"has_downloads": true,
"has_discussions": false,
"archived": false,
"disabled": false,
"visibility": "public",
"pushed_at": "2011-01-26T19:06:43Z",
"created_at": "2011-01-26T19:01:12Z",
"updated_at": "2011-01-26T19:14:43Z",
"permissions": {
"admin": false,
"push": false,
"pull": true,
},
"security_and_analysis": {
"advanced_security": {
"status": "enabled",
},
"secret_scanning": {
"status": "enabled",
},
"secret_scanning_push_protection": {
"status": "disabled",
},
},
};
bench("serialize", () => {
serialize(obj);
});
const serialized = serialize(obj);
bench("deserialize", () => {
deserialize(serialized);
});
if (typeof Bun !== "undefined") {
if (!Bun.deepEquals(obj, deserialize(serialized))) {
throw new Error("not equal");
}
}
await run();

View File

@@ -0,0 +1,39 @@
var testArray = [
{
description: "Random description.",
testNumber: 123456789,
testBoolean: true,
testObject: {
testString: "test string",
testNumber: 12345,
},
testArray: [
{
myName: "test name",
myNumber: 123245,
},
],
},
{
description: "Random description.",
testNumber: 123456789,
testBoolean: true,
testObject: {
testString: "test string",
testNumber: 12345,
},
testArray: [
{
myName: "test name",
myNumber: 123245,
},
],
},
];
import { bench, run } from "./runner.mjs";
bench("structuredClone(array)", () => structuredClone(testArray));
bench("structuredClone(123)", () => structuredClone(123));
bench("structuredClone({a: 123})", () => structuredClone({ a: 123 }));
await run();

View File

@@ -0,0 +1,60 @@
import { bench, run } from "./runner.mjs";
function deprecateUsingClosure(fn, msg, code) {
if (process.noDeprecation === true) {
return fn;
}
var realFn = fn;
var wrapper = () => {
return fnToWrap.apply(this, arguments);
};
var deprecater = () => {
if (process.throwDeprecation) {
var err = new Error(msg);
if (code) err.code = code;
throw err;
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
fnToWrap = realFn;
return realFn.apply(this, arguments);
};
var fnToWrap = deprecater;
return wrapper;
}
function deprecateOriginal(fn, msg) {
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
const deprecatedy = deprecateUsingClosure(() => {}, "This is deprecated", "DEP0001");
const deprecatedy2 = deprecateOriginal(() => {}, "This is deprecated");
bench("deprecateUsingClosure", () => {
deprecatedy(Math.random() + 1);
});
bench("deprecateOriginal", () => {
deprecatedy2(Math.random() + 1);
});
await run();

View File

@@ -0,0 +1,20 @@
import { group } from "mitata";
import { bench, run } from "./runner.mjs";
const sizes = [
["small (63 bytes)", 63],
["medium (4096 bytes)", 4096],
["large (64 MB)", 64 * 1024 * 1024],
];
for (let [name, size] of sizes) {
group(name, () => {
var buf = new Uint8Array(size);
for (let algorithm of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) {
bench(algorithm, async () => {
await crypto.subtle.digest(algorithm, buf);
});
}
});
}
await run();

Binary file not shown.

View File

@@ -1,7 +1,7 @@
{
"name": "bench",
"dependencies": {
"better-sqlite3": "^8.0.1"
"better-sqlite3": "8.5.0"
},
"scripts": {
"build": "exit 0",

View File

@@ -2,7 +2,7 @@
This benchmarks a websocket server intended as a simple but very active chat room.
First, start the server. By default, it will wait for 16 clients which the client script will handle.
First, start the server. By default, it will wait for 32 clients which the client script will handle.
Run in Bun (`Bun.serve`):
@@ -19,10 +19,10 @@ node ./chat-server.node.mjs
Run in Deno (`Deno.serve`):
```bash
deno run -A --unstable ./chat-server.deno.mjs
deno run -A ./chat-server.deno.mjs
```
Then, run the client script. By default, it will connect 16 clients. This client script can run in Bun, Node, or Deno
Then, run the client script. By default, it will connect 32 clients. This client script can run in Bun, Node, or Deno
```bash
node ./chat-client.mjs
@@ -34,6 +34,4 @@ For example, when the client sends `"foo"`, the server sends back `"John: foo"`
The client script waits until it receives all the messages for each client before sending the next batch of messages.
TODO: once Deno lands their performance improvements, increase the client count (it was originally going to be 32 or 64, but that would've exluded Deno from the benchmark)
This project was created using `bun init` in bun v0.2.1. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

Binary file not shown.

View File

@@ -3,7 +3,7 @@ const env = "process" in globalThis ? process.env : "Deno" in globalThis ? Deno.
const SERVER = env.SERVER || "ws://0.0.0.0:4001";
const WebSocket = globalThis.WebSocket || (await import("ws")).WebSocket;
const LOG_MESSAGES = env.LOG_MESSAGES === "1";
const CLIENTS_TO_WAIT_FOR = parseInt(env.CLIENTS_COUNT || "", 10) || 16;
const CLIENTS_TO_WAIT_FOR = parseInt(env.CLIENTS_COUNT || "", 10) || 32;
const DELAY = 64;
const MESSAGES_TO_SEND = Array.from({ length: 32 }, () => [
"Hello World!",

View File

@@ -1,5 +1,5 @@
// See ./README.md for instructions on how to run this benchmark.
const CLIENTS_TO_WAIT_FOR = parseInt(process.env.CLIENTS_COUNT || "", 10) || 16;
const CLIENTS_TO_WAIT_FOR = parseInt(process.env.CLIENTS_COUNT || "", 10) || 32;
var remainingClients = CLIENTS_TO_WAIT_FOR;
const COMPRESS = process.env.COMPRESS === "1";
const port = process.PORT || 4001;
@@ -32,6 +32,7 @@ const server = Bun.serve({
},
perMessageDeflate: false,
publishToSelf: true,
},
fetch(req, server) {

View File

@@ -1,6 +1,6 @@
// See ./README.md for instructions on how to run this benchmark.
const port = Deno.env.get("PORT") || 4001;
const CLIENTS_TO_WAIT_FOR = parseInt(Deno.env.get("CLIENTS_COUNT") || "", 10) || 16;
const CLIENTS_TO_WAIT_FOR = parseInt(Deno.env.get("CLIENTS_COUNT") || "", 10) || 32;
var clients = [];
async function reqHandler(req) {
@@ -42,4 +42,4 @@ function sendReadyMessage() {
console.log(`Waiting for ${CLIENTS_TO_WAIT_FOR} clients to connect..`);
Deno.serve(reqHandler, { port });
Deno.serve({ port }, reqHandler);

View File

@@ -1,6 +1,6 @@
// See ./README.md for instructions on how to run this benchmark.
const port = process.env.PORT || 4001;
const CLIENTS_TO_WAIT_FOR = parseInt(process.env.CLIENTS_COUNT || "", 10) || 16;
const CLIENTS_TO_WAIT_FOR = parseInt(process.env.CLIENTS_COUNT || "", 10) || 32;
import { createRequire } from "module";
const require = createRequire(import.meta.url);

View File

@@ -3,8 +3,8 @@
"module": "index.ts",
"type": "module",
"dependencies": {
"bufferutil": "^4.0.7",
"utf-8-validate": "^5.0.10",
"ws": "^8.9.0"
"bufferutil": "4.0.7",
"utf-8-validate": "6.0.3",
"ws": "8.13.0"
}
}

184
build.zig
View File

@@ -1,5 +1,7 @@
const std = @import("std");
const pathRel = std.fs.path.relative;
const Wyhash = @import("./src/wyhash.zig").Wyhash;
var is_debug_build = false;
fn moduleSource(comptime out: []const u8) FileSource {
if (comptime std.fs.path.dirname(@src().file)) |base| {
const outpath = comptime base ++ std.fs.path.sep_str ++ out;
@@ -8,27 +10,6 @@ fn moduleSource(comptime out: []const u8) FileSource {
return FileSource.relative(out);
}
}
pub fn addPicoHTTP(step: *CompileStep, comptime with_obj: bool) void {
step.addIncludePath("src/deps");
if (with_obj) {
step.addObjectFile("src/deps/picohttpparser.o");
}
step.addIncludePath("src/deps");
if (with_obj) {
step.addObjectFile(panicIfNotFound("src/deps/picohttpparser.o"));
step.addObjectFile(panicIfNotFound("src/deps/libssl.a"));
step.addObjectFile(panicIfNotFound("src/deps/libcrypto.a"));
}
// step.add("/Users/jarred/Code/WebKit/WebKitBuild/Release/lib/libWTF.a");
// ./Tools/Scripts/build-jsc --jsc-only --cmakeargs="-DENABLE_STATIC_JSC=ON"
// set -gx ICU_INCLUDE_DIRS "/usr/local/opt/icu4c/include"
// homebrew-provided icu4c
}
const color_map = std.ComptimeStringMap([]const u8, .{
&.{ "black", "30m" },
@@ -53,6 +34,10 @@ fn addInternalPackages(b: *Build, step: *CompileStep, _: std.mem.Allocator, _: [
break :brk b.createModule(.{
.source_file = FileSource.relative("src/io/io_linux.zig"),
});
} else if (target.isWindows()) {
break :brk b.createModule(.{
.source_file = FileSource.relative("src/io/io_windows.zig"),
});
}
break :brk b.createModule(.{
@@ -75,18 +60,31 @@ const BunBuildOptions = struct {
fallback_html_version: u64 = 0,
pub fn updateRuntime(this: *BunBuildOptions) anyerror!void {
var runtime_out_file = try std.fs.cwd().openFile("src/runtime.out.js", .{ .mode = .read_only });
const runtime_hash = std.hash.Wyhash.hash(
0,
try runtime_out_file.readToEndAlloc(std.heap.page_allocator, try runtime_out_file.getEndPos()),
);
this.runtime_js_version = runtime_hash;
var fallback_out_file = try std.fs.cwd().openFile("src/fallback.out.js", .{ .mode = .read_only });
const fallback_hash = std.hash.Wyhash.hash(
0,
try fallback_out_file.readToEndAlloc(std.heap.page_allocator, try fallback_out_file.getEndPos()),
);
this.fallback_html_version = fallback_hash;
if (std.fs.cwd().openFile("src/runtime.out.js", .{ .mode = .read_only })) |file| {
defer file.close();
const runtime_hash = Wyhash.hash(
0,
try file.readToEndAlloc(std.heap.page_allocator, try file.getEndPos()),
);
this.runtime_js_version = runtime_hash;
} else |_| {
if (!is_debug_build) {
@panic("Runtime file was not read successfully. Please run `make setup`");
}
}
if (std.fs.cwd().openFile("src/fallback.out.js", .{ .mode = .read_only })) |file| {
defer file.close();
const fallback_hash = Wyhash.hash(
0,
try file.readToEndAlloc(std.heap.page_allocator, try file.getEndPos()),
);
this.fallback_html_version = fallback_hash;
} else |_| {
if (!is_debug_build) {
@panic("Fallback file was not read successfully. Please run `make setup`");
}
}
}
pub fn step(this: BunBuildOptions, b: anytype) *std.build.OptionsStep {
@@ -103,6 +101,7 @@ const BunBuildOptions = struct {
}
};
// relative to the prefix
var output_dir: []const u8 = "";
fn panicIfNotFound(comptime filepath: []const u8) []const u8 {
var file = std.fs.cwd().openFile(filepath, .{ .optimize = .read_only }) catch |err| {
@@ -137,6 +136,16 @@ const Module = std.build.Module;
const fs = std.fs;
pub fn build(b: *Build) !void {
build_(b) catch |err| {
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
return err;
};
}
pub fn build_(b: *Build) !void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
@@ -179,25 +188,25 @@ pub fn build(b: *Build) !void {
var triplet = triplet_buf[0 .. osname.len + cpuArchName.len + 1];
if (b.option([]const u8, "output-dir", "target to install to") orelse std.os.getenv("OUTPUT_DIR")) |output_dir_| {
output_dir = b.pathFromRoot(output_dir_);
output_dir = try pathRel(b.allocator, b.install_prefix, output_dir_);
} else {
const output_dir_base = try std.fmt.bufPrint(&output_dir_buf, "{s}{s}", .{ bin_label, triplet });
output_dir = b.pathFromRoot(output_dir_base);
output_dir = try pathRel(b.allocator, b.install_prefix, output_dir_base);
}
std.fs.cwd().makePath(output_dir) catch {};
is_debug_build = optimize == OptimizeMode.Debug;
const bun_executable_name = if (optimize == std.builtin.OptimizeMode.Debug) "bun-debug" else "bun";
const root_src = if (target.getOsTag() == std.Target.Os.Tag.freestanding)
"src/main_wasm.zig"
"root_wasm.zig"
else
"root.zig";
const min_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
const min_version: std.SemanticVersion = if (!(target.isWindows() or target.getOsTag() == .freestanding))
target.getOsVersionMin().semver
else
.{ .major = 0, .minor = 0, .patch = 0 };
const max_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
const max_version: std.SemanticVersion = if (!(target.isWindows() or target.getOsTag() == .freestanding))
target.getOsVersionMax().semver
else
.{ .major = 0, .minor = 0, .patch = 0 };
@@ -208,8 +217,11 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative(root_src),
.target = target,
.optimize = optimize,
.main_pkg_path = .{ .cwd_relative = b.pathFromRoot(".") },
});
b.reference_trace = 16;
var default_build_options: BunBuildOptions = brk: {
const is_baseline = arch.isX86() and (target.cpu_model == .baseline or
!std.Target.x86.featureSetHas(target.getCpuFeatures(), .avx2));
@@ -224,7 +236,6 @@ pub fn build(b: *Build) !void {
.argv = &.{
"git",
"rev-parse",
"--short",
"HEAD",
},
.cwd = b.pathFromRoot("."),
@@ -246,9 +257,6 @@ pub fn build(b: *Build) !void {
};
{
addPicoHTTP(obj, false);
obj.setMainPkgPath(b.pathFromRoot("."));
try addInternalPackages(
b,
obj,
@@ -279,9 +287,15 @@ pub fn build(b: *Build) !void {
std.io.getStdErr().writer().print("Output: {s}/{s}\n\n", .{ output_dir, bun_executable_name }) catch unreachable;
defer obj_step.dependOn(&obj.step);
obj.emit_bin = .{
.emit_to = b.fmt("{s}/{s}.o", .{ output_dir, bun_executable_name }),
};
var install = b.addInstallFileWithDir(
obj.getEmittedBin(),
.{ .custom = output_dir },
b.fmt("{s}.o", .{bun_executable_name}),
);
install.step.dependOn(&obj.step);
obj_step.dependOn(&install.step);
var actual_build_options = default_build_options;
if (b.option(bool, "generate-sizes", "Generate sizes of things") orelse false) {
actual_build_options.sizegen = true;
@@ -298,7 +312,8 @@ pub fn build(b: *Build) !void {
if (target.getCpuArch().isX86()) obj.disable_stack_probing = true;
if (b.option(bool, "for-editor", "Do not emit bin, just check for errors") orelse false) {
obj.emit_bin = .no_emit;
// obj.emit_bin = .no_emit;
obj.generated_bin = null;
}
if (target.getOsTag() == .linux) {
@@ -316,9 +331,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("src/bindgen.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
var headers_build_options = default_build_options;
headers_build_options.bindgen = true;
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -326,19 +342,22 @@ pub fn build(b: *Build) !void {
}
{
const wasm = b.step("bun-wasm", "Build WASM");
var wasm_step = b.addStaticLibrary(.{
const wasm_step = b.step("bun-wasm", "Build WASM");
var wasm = b.addStaticLibrary(.{
.name = "bun-wasm",
.root_source_file = FileSource.relative("src/main_wasm.zig"),
.root_source_file = FileSource.relative("root_wasm.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer wasm.dependOn(&wasm_step.step);
wasm_step.strip = false;
defer wasm_step.dependOn(&wasm.step);
wasm.strip = false;
// wasm_step.link_function_sections = true;
// wasm_step.link_emit_relocs = true;
// wasm_step.single_threaded = true;
try configureObjectStep(b, wasm_step, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, wasm, wasm_step, @TypeOf(target), target);
var build_opts = default_build_options;
wasm.addOptions("build_options", build_opts.step(b));
}
{
@@ -348,9 +367,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("misctools/http_bench.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -361,9 +381,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("misctools/machbench.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -374,9 +395,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("misctools/fetch.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -387,9 +409,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("src/bench/string-handling.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -400,9 +423,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("src/sha.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -413,9 +437,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("src/sourcemap/vlq_bench.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -426,9 +451,10 @@ pub fn build(b: *Build) !void {
.root_source_file = FileSource.relative("misctools/tgz.zig"),
.target = target,
.optimize = optimize,
.main_pkg_path = obj.main_pkg_path,
});
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_obj.addOptions("build_options", default_build_options.step(b));
}
@@ -442,16 +468,23 @@ pub fn build(b: *Build) !void {
var headers_obj: *CompileStep = b.addTest(.{
.root_source_file = FileSource.relative(test_file orelse "src/main.zig"),
.target = target,
.main_pkg_path = obj.main_pkg_path,
});
headers_obj.filter = test_filter;
if (test_bin_) |test_bin| {
headers_obj.name = std.fs.path.basename(test_bin);
if (std.fs.path.dirname(test_bin)) |dir| headers_obj.emit_bin = .{
.emit_to = b.fmt("{s}/{s}", .{ dir, headers_obj.name }),
};
if (std.fs.path.dirname(test_bin)) |dir| {
var install = b.addInstallFileWithDir(
headers_obj.getEmittedBin(),
.{ .custom = try std.fs.path.relative(b.allocator, output_dir, dir) },
headers_obj.name,
);
install.step.dependOn(&headers_obj.step);
headers_step.dependOn(&install.step);
}
}
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
try configureObjectStep(b, headers_obj, headers_step, @TypeOf(target), target);
headers_step.dependOn(&headers_obj.step);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -462,23 +495,24 @@ pub fn build(b: *Build) !void {
pub var original_make_fn: ?*const fn (step: *std.build.Step) anyerror!void = null;
pub fn configureObjectStep(b: *std.build.Builder, obj: *CompileStep, comptime Target: type, target: Target, main_pkg_path: []const u8) !void {
obj.setMainPkgPath(main_pkg_path);
pub fn configureObjectStep(b: *std.build.Builder, obj: *CompileStep, obj_step: *std.build.Step, comptime Target: type, target: Target) !void {
// obj.setTarget(target);
try addInternalPackages(b, obj, std.heap.page_allocator, b.zig_exe, target);
if (target.getOsTag() != .freestanding)
addPicoHTTP(obj, false);
obj.strip = false;
// obj.setBuildMode(optimize);
obj.bundle_compiler_rt = false;
if (obj.emit_bin == .default)
obj.emit_bin = .{
.emit_to = b.fmt("{s}/{s}.o", .{ output_dir, obj.name }),
};
if (obj.emit_directory == null) {
var install = b.addInstallFileWithDir(
obj.getEmittedBin(),
.{ .custom = output_dir },
b.fmt("{s}.o", .{obj.name}),
);
install.step.dependOn(&obj.step);
obj_step.dependOn(&install.step);
}
if (target.getOsTag() != .freestanding) obj.linkLibC();
if (target.getOsTag() != .freestanding) obj.bundle_compiler_rt = false;

BIN
bun.lockb

Binary file not shown.

View File

@@ -92,10 +92,10 @@ _bun_completions() {
PACKAGE_OPTIONS[REMOVE_OPTIONS_LONG]="";
PACKAGE_OPTIONS[REMOVE_OPTIONS_SHORT]="";
PACKAGE_OPTIONS[SHARED_OPTIONS_LONG]="--config --yarn --production --no-save --dry-run --lockfile --force --cache-dir --no-cache --silent --verbose --global --cwd --backend --link-native-bins --help";
PACKAGE_OPTIONS[SHARED_OPTIONS_LONG]="--config --yarn --production --frozen-lockfile --no-save --dry-run --lockfile --force --cache-dir --no-cache --silent --verbose --global --cwd --backend --link-native-bins --help";
PACKAGE_OPTIONS[SHARED_OPTIONS_SHORT]="-c -y -p -f -g";
PM_OPTIONS[LONG_OPTIONS]="--config --yarn --production --no-save --dry-run --lockfile --force --cache-dir --no-cache --silent --verbose --no-progress --no-summary --no-verify --ignore-scripts --global --cwd --backend --link-native-bins --help"
PM_OPTIONS[LONG_OPTIONS]="--config --yarn --production --frozen-lockfile --no-save --dry-run --lockfile --force --cache-dir --no-cache --silent --verbose --no-progress --no-summary --no-verify --ignore-scripts --global --cwd --backend --link-native-bins --help"
PM_OPTIONS[SHORT_OPTIONS]="-c -y -p -f -g"
local cur_word="${COMP_WORDS[${COMP_CWORD}]}";

View File

@@ -47,8 +47,9 @@ _bun() {
'-g[Add a package globally]' \
'--global[Add a package globally]' \
'--production[Don'"'"'t install devDependencies]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--optional[Add dependency to optionalDependencies]' \
'--development[Add dependency to devDependencies]' \
'--dev[Add dependency to devDependencies]' \
'-d[Add dependency to devDependencies]' \
'-p[Don'"'"'t install devDependencies]' \
'--no-save[]' \
@@ -88,8 +89,9 @@ _bun() {
'--yarn[Write a yarn.lock file (yarn v1)]' \
'--global[Add a package globally]' \
'--production[Don'"'"'t install devDependencies]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--optional[Add dependency to optionalDependencies]' \
'--development[Add dependency to devDependencies]' \
'--dev[Add dependency to devDependencies]' \
'-d[Add dependency to devDependencies]' \
'-p[Don'"'"'t install devDependencies]' \
'--no-save[]' \
@@ -123,8 +125,9 @@ _bun() {
'--yarn[Write a yarn.lock file (yarn v1)]' \
'--global[Add a package globally]' \
'--production[Don'"'"'t install devDependencies]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--optional[Add dependency to optionalDependencies]' \
'--development[Add dependency to devDependencies]' \
'--dev[Add dependency to devDependencies]' \
'-d[Add dependency to devDependencies]' \
'-p[Don'"'"'t install devDependencies]' \
'--no-save[]' \
@@ -278,6 +281,7 @@ _bun() {
'--yarn[Write a yarn.lock file (yarn v1)]'
'-p[Do not install devDependencies]'
'--production[Do not install devDependencies]'
'--frozen-lockfile[Disallow changes to lockfile]' \
'--no-save[Do not save a lockfile]'
'--dry-run[Do not install anything]'
'--lockfile[Store & load a lockfile at a specific filepath]'
@@ -532,6 +536,7 @@ _bun() {
'--yarn[Write a yarn.lock file (yarn v1)]' \
'--production[Don'"'"'t install devDependencies]' \
'-p[Don'"'"'t install devDependencies]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--no-save[]' \
'--dry-run[Don'"'"'t install anything]' \
'--force[Always request the latest versions from the registry & reinstall all dependenices]' \
@@ -565,6 +570,7 @@ _bun() {
'--yarn[Write a yarn.lock file (yarn v1)]' \
'--production[Don'"'"'t install devDependencies]' \
'-p[Don'"'"'t install devDependencies]' \
'--frozen-lockfile[Disallow changes to lockfile]' \
'--no-save[]' \
'--dry-run[Don'"'"'t install anything]' \
'-g[Remove a package globally]' \

View File

@@ -115,6 +115,7 @@ subcommands:
- yarn -- "Write a yarn.lock file (yarn v1)"
- production -- "Don't install devDependencies"
- p -- "Don't install devDependencies"
- frozen-lockfile -- "Disallow changes to lockfile"
- no-save --
- dry-run -- "Don't install anything"
- force -- "Always request the latest versions from the registry & reinstall all dependenices"
@@ -152,6 +153,7 @@ subcommands:
- development -- "Add dependency to devDependencies"
- d -- "Add dependency to devDependencies"
- p -- "Don't install devDependencies"
- frozen-lockfile -- "Disallow changes to lockfile"
- no-save --
- dry-run -- "Don't install anything"
- force -- "Always request the latest versions from the registry & reinstall all dependenices"
@@ -192,6 +194,7 @@ subcommands:
- yarn -- "Write a yarn.lock file (yarn v1)"
- production -- "Don't install devDependencies"
- p -- "Don't install devDependencies"
- frozen-lockfile -- "Disallow changes to lockfile"
- no-save --
- dry-run -- "Don't install anything"
- force -- "Always request the latest versions from the registry & reinstall all dependenices"

View File

@@ -1,4 +1,5 @@
FROM debian:bullseye-slim AS build
# Not officially supported (yet)
# https://github.com/oven-sh/bun/releases
ARG BUN_VERSION=latest

View File

@@ -74,7 +74,7 @@ dv.getUint8(0); // => 3
// [0x11, 0x0, 0x0, 0x0]
```
Now lets write a `Uint16` at byte offset `1`. This requires two bytes. We're using the value `513`, which is `2 * 256 + 1`; in bytes, that's `00000010 00000001`.
Now let's write a `Uint16` at byte offset `1`. This requires two bytes. We're using the value `513`, which is `2 * 256 + 1`; in bytes, that's `00000010 00000001`.
```ts
dv.setUint16(1, 513);
@@ -90,7 +90,7 @@ console.log(dv.getUint8(1)); // => 2
console.log(dv.getUint8(2)); // => 1
```
Attempting to write a value that requires more space than is available in the underlying `ArrayBuffer` will cuase an error. Below we attempt to write a `Float64` (which requires 8 bytes) at byte offset `0`, but there are only four total bytes in the buffer.
Attempting to write a value that requires more space than is available in the underlying `ArrayBuffer` will cause an error. Below we attempt to write a `Float64` (which requires 8 bytes) at byte offset `0`, but there are only four total bytes in the buffer.
```ts
dv.setFloat64(0, 3.1415);
@@ -927,7 +927,7 @@ Buffer.from(Bun.readableStreamToArrayBuffer(stream));
new Response(stream).text();
// with Bun function
await Bun.readableStreamToString(stream);
await Bun.readableStreamToText(stream);
```
#### To `number[]`

View File

@@ -229,7 +229,11 @@ const lib = linkSymbols({
},
});
const [major, minor, patch] = [lib.symbols.getMajor(), lib.symbols.getMinor(), lib.symbols.getPatch()];
const [major, minor, patch] = [
lib.symbols.getMajor(),
lib.symbols.getMinor(),
lib.symbols.getPatch(),
];
```
## Callbacks
@@ -249,10 +253,13 @@ const {
},
});
const searchIterator = new JSCallback((ptr, length) => /hello/.test(new CString(ptr, length)), {
returns: "bool",
args: ["ptr", "usize"],
});
const searchIterator = new JSCallback(
(ptr, length) => /hello/.test(new CString(ptr, length)),
{
returns: "bool",
args: ["ptr", "usize"],
},
);
const str = Buffer.from("wwutwutwutwutwutwutwutwutwutwutut\0", "utf8");
if (search(ptr(str), searchIterator)) {
@@ -376,10 +383,6 @@ If you want to track when a `TypedArray` is no longer in use from JavaScript, yo
#### From C, Rust, Zig, etc
{% callout %}
**Note** — Available in Bun v0.1.8 and later.
{% /callout %}
If you want to track when a `TypedArray` is no longer in use from C or FFI, you can pass a callback and an optional context pointer to `toArrayBuffer` or `toBuffer`. This function is called at some point later, once the garbage collector frees the underlying `ArrayBuffer` JavaScript object.
The expected signature is the same as in [JavaScriptCore's C API](https://developer.apple.com/documentation/javascriptcore/jstypedarraybytesdeallocator?language=objc):

View File

@@ -1,8 +1,8 @@
{% callout %}
<!-- **Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](/docs/runtime/nodejs-apis#node_fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. -->
<!-- **Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. Existing Node.js projects may use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. -->
**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node_fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module.
{% /callout %}
@@ -195,13 +195,60 @@ const input = Bun.file("input.txt");
await Bun.write(Bun.stdout, input);
```
To write an HTTP response to disk:
To write the body of an HTTP response to disk:
```ts
const response = await fetch("https://bun.sh");
await Bun.write("index.html", response);
```
## Incremental writing with `FileSink`
Bun provides a native incremental file writing API called `FileSink`. To retrieve a `FileSink` instance from a `BunFile`:
```ts
const file = Bun.file("output.txt");
const writer = file.writer();
```
To incrementally write to the file, call `.write()`.
```ts
const file = Bun.file("output.txt");
const writer = file.writer();
writer.write("it was the best of times\n");
writer.write("it was the worst of times\n");
```
These chunks will be buffered internally. To flush the buffer to disk, use `.flush()`. This returns the number of flushed bytes.
```ts
writer.flush(); // write buffer to disk
```
The buffer will also auto-flush when the `FileSink`'s _high water mark_ is reached; that is, when its internal buffer is full. This value can be configured.
```ts
const file = Bun.file("output.txt");
const writer = file.writer({ highWaterMark: 1024 * 1024 }); // 1MB
```
To flush the buffer and close the file:
```ts
writer.end();
```
Note that, by default, the `bun` process will stay alive until this `FileSink` is explicitly closed with `.end()`. To opt out of this behavior, you can "unref" the instance.
```ts
writer.unref();
// to "re-ref" it later
writer.ref();
```
## Benchmarks
The following is a 3-line implementation of the Linux `cat` command.
@@ -238,7 +285,13 @@ interface Bun {
write(
destination: string | number | BunFile | URL,
input: string | Blob | ArrayBuffer | SharedArrayBuffer | TypedArray | Response,
input:
| string
| Blob
| ArrayBuffer
| SharedArrayBuffer
| TypedArray
| Response,
): Promise<number>;
}
@@ -250,5 +303,17 @@ interface BunFile {
stream(): Promise<ReadableStream>;
arrayBuffer(): Promise<ArrayBuffer>;
json(): Promise<any>;
writer(params: { highWaterMark?: number }): FileSink;
}
export interface FileSink {
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
flush(): number | Promise<number>;
end(error?: Error): number | Promise<number>;
start(options?: { highWaterMark?: number }): void;
ref(): void;
unref(): void;
}
```

View File

@@ -34,7 +34,7 @@ Bun implements the following globals.
- [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)
- Node.js
- See [Node.js > `Buffer`](/docs/runtime/nodejs-apis#node_buffer)
- See [Node.js > `Buffer`](/docs/runtime/nodejs-apis#node-buffer)
---
@@ -172,7 +172,7 @@ Bun implements the following globals.
- [`global`](https://nodejs.org/api/globals.html#global)
- Node.js
- See [Node.js > `global`](/docs/runtime/nodejs-apis#node_global).
- See [Node.js > `global`](/docs/runtime/nodejs-apis#global).
---
@@ -220,7 +220,7 @@ Bun implements the following globals.
- [`process`](https://nodejs.org/api/process.html)
- Node.js
- See [Node.js > `process`](/docs/runtime/nodejs-apis#node_process)
- See [Node.js > `process`](/docs/runtime/nodejs-apis#node-process)
---

View File

@@ -4,6 +4,67 @@ Bun implements the `createHash` and `createHmac` functions from [`node:crypto`](
{% /callout %}
## `Bun.password`
`Bun.password` is a collection of utility functions for hashing and verifying passwords with various cryptographically secure algorithms.
```ts
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/SqYCNu6gVdRRNs$GzJ8PuBi+K+BVojzPfS5mjnC8OpLGtv8KJqF99eP6a4
const isMatch = await Bun.password.verify(password, hash);
// => true
```
The second argument to `Bun.password.hash` accepts a params object that lets you pick and configure the hashing algorithm.
```ts
const password = "super-secure-pa$$word";
// use argon2 (default)
const argonHash = await Bun.password.hash(password, {
algorithm: "argon2id", // "argon2id" | "argon2i" | "argon2d"
memoryCost: 4, // memory usage in kibibytes
timeCost: 3, // the number of iterations
});
// use bcrypt
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 4, // number between 4-31
});
```
The algorithm used to create the hash is stored in the hash itself. When using `bcrypt`, the returned hash is encoded in [Modular Crypt Format](https://passlib.readthedocs.io/en/stable/modular_crypt_format.html) for compatibility with most existing `bcrypt` implementations; with `argon2` the result is encoded in the newer [PHC format](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md).
The `verify` function automatically detects the algorithm based on the input hash and use the correct verification method. It can correctly infer the algorithm from both PHC- or MCF-encoded hashes.
```ts
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password, {
/* config */
});
const isMatch = await Bun.password.verify(password, hash);
// => true
```
Synchronous versions of all functions are also available. Keep in mind that these functions are computationally expensive, so using a blocking API may degrade application performance.
```ts
const password = "super-secure-pa$$word";
const hash = Bun.password.hashSync(password, {
/* config */
});
const isMatch = Bun.password.verifySync(password, hash);
// => true
```
## `Bun.hash`
`Bun.hash` is a collection of utilities for _non-cryptographic_ hashing. Non-cryptographic hashing algorithms are optimized for speed of computation over collision-resistance or security.
@@ -12,7 +73,7 @@ The standard `Bun.hash` functions uses [Wyhash](https://github.com/wangyi-fudan/
```ts
Bun.hash("some data here");
// 976213160445840
// 11562320457524636935n
```
The input can be a string, `TypedArray`, `DataView`, `ArrayBuffer`, or `SharedArrayBuffer`.
@@ -26,14 +87,14 @@ Bun.hash(arr.buffer);
Bun.hash(new DataView(arr.buffer));
```
Optionally, an integer seed can be specified as the second parameter.
Optionally, an integer seed can be specified as the second parameter. For 64-bit hashes seeds above `Number.MAX_SAFE_INTEGER` should be given as BigInt to avoid loss of precision.
```ts
Bun.hash("some data here", 1234);
// 1173484059023252
// 15724820720172937558n
```
Additional hashing algorithms are available as properties on `Bun.hash`. The API is the same for each.
Additional hashing algorithms are available as properties on `Bun.hash`. The API is the same for each, only changing the return type from number for 32-bit hashes to bigint for 64-bit hashes.
```ts
Bun.hash.wyhash("data", 1234); // equivalent to Bun.hash()
@@ -42,6 +103,7 @@ Bun.hash.adler32("data", 1234);
Bun.hash.cityHash32("data", 1234);
Bun.hash.cityHash64("data", 1234);
Bun.hash.murmur32v3("data", 1234);
Bun.hash.murmur32v2("data", 1234);
Bun.hash.murmur64v2("data", 1234);
```
@@ -70,7 +132,7 @@ hasher.digest();
Once initialized, data can be incrementally fed to to the hasher using `.update()`. This method accepts `string`, `TypedArray`, and `ArrayBuffer`.
```ts
const hasher = new Bun.CryptoHasher();
const hasher = new Bun.CryptoHasher("sha256");
hasher.update("hello world");
hasher.update(new Uint8Array([1, 2, 3]));
@@ -108,7 +170,7 @@ hasher.update("hello world", "latin1");
After the data has been feed into the hasher, a final hash can be computed using `.digest()`. By default, this method returns a `Uint8Array` containing the hash.
```ts
const hasher = new Bun.CryptoHasher();
const hasher = new Bun.CryptoHasher("sha256");
hasher.update("hello world");
hasher.digest();

View File

@@ -13,7 +13,7 @@ Start an HTTP server in Bun with `Bun.serve`.
```ts
Bun.serve({
fetch(req) {
return new Response(`Bun!`);
return new Response("Bun!");
},
});
```
@@ -24,9 +24,9 @@ The `fetch` handler handles incoming requests. It receives a [`Request`](https:/
Bun.serve({
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") return new Response(`Home page!`);
if (url.pathname === "/") return new Response("Home page!");
if (url.pathname === "/blog") return new Response("Blog!");
return new Response(`404!`);
return new Response("404!");
},
});
```
@@ -35,8 +35,19 @@ To configure which port and hostname the server will listen on:
```ts
Bun.serve({
port: 8080, // defaults to $PORT, then 3000
port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
hostname: "mydomain.com", // defaults to "0.0.0.0"
fetch(req) {
return new Response("404!");
},
});
```
To listen on a [unix domain socket](https://en.wikipedia.org/wiki/Unix_domain_socket):
```ts
Bun.serve({
unix: "/tmp/my-socket.sock", // path to socket
fetch(req) {
return new Response(`404!`);
},
@@ -67,7 +78,7 @@ Bun.serve({
fetch(req) {
throw new Error("woops!");
},
error(error: Error) {
error(error) {
return new Response(`<pre>${error}\n${error.stack}</pre>`, {
headers: {
"Content-Type": "text/html",
@@ -78,7 +89,7 @@ Bun.serve({
```
{% callout %}
**Note** — Full debugger support is planned.
[Learn more about debugging in Bun](https://bun.sh/docs/runtime/debugger)
{% /callout %}
The call to `Bun.serve` returns a `Server` object. To stop the server, call the `.stop()` method.
@@ -95,58 +106,69 @@ server.stop();
## TLS
Bun supports TLS out of the box, powered by [OpenSSL](https://www.openssl.org/). Enable TLS by passing in a value for `key` and `cert`; both are required to enable TLS. If needed, supply a `passphrase` to decrypt the `keyFile`.
Bun supports TLS out of the box, powered by [BoringSSL](https://boringssl.googlesource.com/boringssl). Enable TLS by passing in a value for `key` and `cert`; both are required to enable TLS.
```ts
Bun.serve({
fetch(req) {
return new Response("Hello!!!");
},
```ts-diff
Bun.serve({
fetch(req) {
return new Response("Hello!!!");
},
// can be string, BunFile, TypedArray, Buffer, or array thereof
key: Bun.file("./key.pem"),
cert: Bun.file("./cert.pem"),
// passphrase, only required if key is encrypted
passphrase: "super-secret",
});
+ tls: {
+ key: Bun.file("./key.pem"),
+ cert: Bun.file("./cert.pem"),
+ }
});
```
The `key` and `cert` fields expect the _contents_ of your TLS key and certificate. This can be a string, `BunFile`, `TypedArray`, or `Buffer`.
The `key` and `cert` fields expect the _contents_ of your TLS key and certificate, _not a path to it_. This can be a string, `BunFile`, `TypedArray`, or `Buffer`.
```ts
Bun.serve({
fetch() {},
// BunFile
key: Bun.file("./key.pem"),
// Buffer
key: fs.readFileSync("./key.pem"),
// string
key: fs.readFileSync("./key.pem", "utf8"),
// array of above
key: [Bun.file('./key1.pem'), Bun.file('./key2.pem']
tls: {
// BunFile
key: Bun.file("./key.pem"),
// Buffer
key: fs.readFileSync("./key.pem"),
// string
key: fs.readFileSync("./key.pem", "utf8"),
// array of above
key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")],
},
});
```
{% callout %}
If your private key is encrypted with a passphrase, provide a value for `passphrase` to decrypt it.
**Note** Earlier versions of Bun supported passing a file path as `keyFile` and `certFile`; this has been deprecated as of `v0.6.3`.
```ts-diff
Bun.serve({
fetch(req) {
return new Response("Hello!!!");
},
{% /callout %}
tls: {
key: Bun.file("./key.pem"),
cert: Bun.file("./cert.pem"),
+ passphrase: "my-secret-passphrase",
}
});
```
Optionally, you can override the trusted CA certificates by passing a value for `ca`. By default, the server will trust the list of well-known CAs curated by Mozilla. When `ca` is specified, the Mozilla list is overwritten.
```ts
Bun.serve({
fetch(req) {
return new Response("Hello!!!");
},
key: Bun.file("./key.pem"), // path to TLS key
cert: Bun.file("./cert.pem"), // path to TLS cert
ca: Bun.file("./ca.pem"), // path to root CA certificate
});
```ts-diff
Bun.serve({
fetch(req) {
return new Response("Hello!!!");
},
tls: {
key: Bun.file("./key.pem"), // path to TLS key
cert: Bun.file("./cert.pem"), // path to TLS cert
+ ca: Bun.file("./ca.pem"), // path to root CA certificate
}
});
```
To override Diffie-Helman parameters:
@@ -154,11 +176,14 @@ To override Diffie-Helman parameters:
```ts
Bun.serve({
// ...
dhParamsFile: "./dhparams.pem", // path to Diffie Helman parameters
tls: {
// other config
dhParamsFile: "/path/to/dhparams.pem", // path to Diffie Helman parameters
},
});
```
## Hot reloading
## Object syntax
Thus far, the examples on this page have used the explicit `Bun.serve` API. Bun also supports an alternate syntax.
@@ -167,20 +192,20 @@ import {type Serve} from "bun";
export default {
fetch(req) {
return new Response(`Bun!`);
return new Response("Bun!");
},
} satisfies Serve;
```
Instead of passing the server options into `Bun.serve`, export it. This file can be executed as-is; when Bun runs a file with a `default` export containing a `fetch` handler, it passes it into `Bun.serve` under the hood.
Instead of passing the server options into `Bun.serve`, `export default` it. This file can be executed as-is; when Bun sees a file with a `default` export containing a `fetch` handler, it passes it into `Bun.serve` under the hood.
This syntax has one major advantage: it is hot-reloadable out of the box. When any source file is changed, Bun will reload the server with the updated code _without restarting the process_. This makes hot reloads nearly instantaneous. Use the `--hot` flag when starting the server to enable hot reloading.
<!-- This syntax has one major advantage: it is hot-reloadable out of the box. When any source file is changed, Bun will reload the server with the updated code _without restarting the process_. This makes hot reloads nearly instantaneous. Use the `--hot` flag when starting the server to enable hot reloading. -->
```bash
<!-- ```bash
$ bun --hot server.ts
```
``` -->
It's possible to configure hot reloading while using the explicit `Bun.serve` API; for details refer to [Runtime > Hot reloading](/docs/runtime/hot).
<!-- It's possible to configure hot reloading while using the explicit `Bun.serve` API; for details refer to [Runtime > Hot reloading](/docs/runtime/hot). -->
## Streaming files
@@ -200,7 +225,7 @@ serve({
⚡️ **Speed** — Bun automatically uses the [`sendfile(2)`](https://man7.org/linux/man-pages/man2/sendfile.2.html) system call when possible, enabling zero-copy file transfers in the kernel—the fastest way to send files.
{% /callout %}
**[v0.3.0+]** You can send part of a file using the [`slice(start, end)`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice) method on the `Bun.file` object. This automatically sets the `Content-Range` and `Content-Length` headers on the `Response` object.
You can send part of a file using the [`slice(start, end)`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice) method on the `Bun.file` object. This automatically sets the `Content-Range` and `Content-Length` headers on the `Response` object.
```ts
Bun.serve({
@@ -229,7 +254,7 @@ Below are Bun and Node.js implementations of a simple HTTP server that responds
```ts#Bun
Bun.serve({
fetch(req: Request) {
return new Response(`Bun!`);
return new Response("Bun!");
},
port: 3000,
});
@@ -275,11 +300,21 @@ interface Bun {
port?: number;
development?: boolean;
error?: (error: Error) => Response | Promise<Response>;
keyFile?: string;
certFile?: string;
caFile?: string;
dhParamsFile?: string;
passphrase?: string;
tls?: {
key?:
| string
| TypedArray
| BunFile
| Array<string | TypedArray | BunFile>;
cert?:
| string
| TypedArray
| BunFile
| Array<string | TypedArray | BunFile>;
ca?: string | TypedArray | BunFile | Array<string | TypedArray | BunFile>;
passphrase?: string;
dhParamsFile?: string;
};
maxRequestBodySize?: number;
lowMemoryMode?: boolean;
}): Server;

View File

@@ -19,17 +19,17 @@ import.meta.resolveSync("zod")
---
- `import.meta.dir`
- Absolute path to the directory containing the current fil, e.g. `/path/to/project`. Equivalent to `__dirname` in Node.js.
- Absolute path to the directory containing the current file, e.g. `/path/to/project`. Equivalent to `__dirname` in CommonJS modules (and Node.js)
---
- `import.meta.file`
- The name of the current file, e.g. `index.tsx`. Equivalent to `__filename` in Node.js.
- The name of the current file, e.g. `index.tsx`
---
- `import.meta.path`
- Absolute path to the current file, e.g. `/path/to/project/index.tx`.
- Absolute path to the current file, e.g. `/path/to/project/index.tx`. Equivalent to `__filename` in CommonJS modules (and Node.js)
---

View File

@@ -12,7 +12,7 @@ The second argument to `Bun.spawn` is a parameters object that can be used to co
```ts
const proc = Bun.spawn(["echo", "hello"], {
cwd: "./path/to/subdir", // specify a working direcory
cwd: "./path/to/subdir", // specify a working directory
env: { ...process.env, FOO: "bar" }, // specify environment variables
onExit(proc, exitCode, signalCode, error) {
// exit handler
@@ -28,7 +28,9 @@ By default, the input stream of the subprocess is undefined; it can be configure
```ts
const proc = Bun.spawn(["cat"], {
stdin: await fetch("https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js"),
stdin: await fetch(
"https://raw.githubusercontent.com/oven-sh/bun/main/examples/hashing.js",
),
});
const text = await new Response(proc.stdout).text();
@@ -209,7 +211,7 @@ Bun's `spawnSync` spawns processes 60% faster than the Node.js `child_process` m
```bash
$ bun spawn.mjs
cpu: Apple M1 Max
runtime: bun 0.2.0 (arm64-darwin)
runtime: bun 1.x (arm64-darwin)
benchmark time (avg) (min … max) p75 p99 p995
--------------------------------------------------------- -----------------------------
@@ -230,10 +232,15 @@ A simple reference of the Spawn API and types are shown below. The real types ha
```ts
interface Bun {
spawn(command: string[], options?: SpawnOptions.OptionsObject): Subprocess;
spawnSync(command: string[], options?: SpawnOptions.OptionsObject): SyncSubprocess;
spawnSync(
command: string[],
options?: SpawnOptions.OptionsObject,
): SyncSubprocess;
spawn(options: { cmd: string[] } & SpawnOptions.OptionsObject): Subprocess;
spawnSync(options: { cmd: string[] } & SpawnOptions.OptionsObject): SyncSubprocess;
spawnSync(
options: { cmd: string[] } & SpawnOptions.OptionsObject,
): SyncSubprocess;
}
namespace SpawnOptions {
@@ -243,7 +250,12 @@ namespace SpawnOptions {
stdin?: SpawnOptions.Readable;
stdout?: SpawnOptions.Writable;
stderr?: SpawnOptions.Writable;
onExit?: (proc: Subprocess, exitCode: number | null, signalCode: string | null, error: Error | null) => void;
onExit?: (
proc: Subprocess,
exitCode: number | null,
signalCode: string | null,
error: Error | null,
) => void;
}
type Readable =

View File

@@ -75,7 +75,7 @@ Note: `close()` is called automatically when the database is garbage collected.
```ts
const olddb = new Database("mydb.sqlite");
const contents = olddb.serialize(); // => Uint8Array
const newdb = new Database(contents);
const newdb = Database.deserialize(contents);
```
Internally, `.serialize()` calls [`sqlite3_serialize`](https://www.sqlite.org/c3ref/serialize.html).
@@ -250,7 +250,7 @@ Transactions are a mechanism for executing multiple queries in an _atomic_ way;
```ts
const insertCat = db.prepare("INSERT INTO cats (name) VALUES ($name)");
const insertCats = db.transaction((cats) => {
const insertCats = db.transaction(cats => {
for (const cat of cats) insertCat.run(cat);
});
```
@@ -261,7 +261,7 @@ To execute the transaction, call this function. All arguments will be passed thr
```ts
const insert = db.prepare("INSERT INTO cats (name) VALUES ($name)");
const insertCats = db.transaction((cats) => {
const insertCats = db.transaction(cats => {
for (const cat of cats) insert.run(cat);
return cats.length;
});
@@ -296,11 +296,11 @@ const insertExpense = db.prepare(
"INSERT INTO expenses (note, dollars) VALUES (?, ?)",
);
const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)");
const insertCats = db.transaction((cats) => {
const insertCats = db.transaction(cats => {
for (const cat of cats) insert.run(cat);
});
const adopt = db.transaction((cats) => {
const adopt = db.transaction(cats => {
insertExpense.run("adoption fees", 20);
insertCats(cats); // nested transaction
});

View File

@@ -1,6 +1,6 @@
Streams are an important abstraction for working with binary data without loading it all into memory at once. They are commonly used for reading and writing files, sending and receiving network requests, and processing large amounts of data.
Bun implements the Web APIs [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).
Bun implements the Web APIs [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).
{% callout %}
Bun also implements the `node:stream` module, including [`Readable`](https://nodejs.org/api/stream.html#stream_readable_streams), [`Writable`](https://nodejs.org/api/stream.html#stream_writable_streams), and [`Duplex`](https://nodejs.org/api/stream.html#stream_duplex_and_transform_streams). For complete documentation, refer to the [Node.js docs](https://nodejs.org/api/stream.html).
@@ -28,8 +28,6 @@ for await (const chunk of stream) {
}
```
For a more complete discusson of streams in Bun, see [API > Streams](/docs/api/streams).
## Direct `ReadableStream`
Bun implements an optimized version of `ReadableStream` that avoid unnecessary data copying & queue management logic. With a traditional `ReadableStream`, chunks of data are _enqueued_. Each chunk is copied into a queue, where it sits until the stream is ready to send more data.
@@ -154,7 +152,9 @@ export class ArrayBufferSink {
stream?: boolean;
}): void;
write(chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer): number;
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
/**
* Flush the internal buffer
*

View File

@@ -76,12 +76,6 @@ Bun.listen({
});
```
{% callout %}
**Note** Earlier versions of Bun supported passing a file path as `keyFile` and `certFile`; this has been deprecated as of `v0.6.3`.
{% /callout %}
The `key` and `cert` fields expect the _contents_ of your TLS key and certificate. This can be a string, `BunFile`, `TypedArray`, or `Buffer`.
```ts
@@ -95,7 +89,7 @@ Bun.listen({
// string
key: fs.readFileSync("./key.pem", "utf8"),
// array of above
key: [Bun.file('./key1.pem'), Bun.file('./key2.pem']
key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")],
},
});
```

View File

@@ -160,7 +160,6 @@ export const name = "hello";
`;
const result = transpiler.scanImports(code);
`);
```
```json#Results

View File

@@ -43,7 +43,7 @@ This is analogous to the [`require.main = module` trick](https://stackoverflow.c
## `Bun.sleep()`
`Bun.sleep(ms: number)` (added in Bun v0.5.6)
`Bun.sleep(ms: number)`
Returns a `Promise` that resolves after the given number of milliseconds.
@@ -65,7 +65,7 @@ console.log("hello one second later!");
## `Bun.sleepSync()`
`Bun.sleepSync(ms: number)` (added in Bun v0.5.6)
`Bun.sleepSync(ms: number)`
A blocking synchronous version of `Bun.sleep`.
@@ -75,16 +75,6 @@ Bun.sleepSync(1000); // blocks thread for one second
console.log("hello one second later!");
```
Alternatively, pass a `Date` object to receive a `Promise` that resolves at that point in time.
```ts
const oneSecondInFuture = new Date(Date.now() + 1000);
console.log("hello");
await Bun.sleep(oneSecondInFuture);
console.log("hello one second later!");
```
## `Bun.which()`
`Bun.which(bin: string)`
@@ -118,7 +108,7 @@ console.log(ls); // null
## `Bun.peek()`
`Bun.peek(prom: Promise)` (added in Bun v0.2.2)
`Bun.peek(prom: Promise)`
Reads a promise's result without `await` or `.then`, but only if the promise has already fulfilled or rejected.
@@ -159,7 +149,9 @@ test("peek", () => {
// If we peek a rejected promise, it:
// - returns the error
// - does not mark the promise as handled
const rejected = Promise.reject(new Error("Successfully tested promise rejection"));
const rejected = Promise.reject(
new Error("Successfully tested promise rejection"),
);
expect(peek(rejected).message).toBe("Successfully tested promise rejection");
});
```
@@ -255,7 +247,7 @@ Bun.deepEquals(new Foo(), { a: 1 }, true); // false
## `Bun.escapeHTML()`
`Bun.escapeHTML(value: string | object | number | boolean): boolean`
`Bun.escapeHTML(value: string | object | number | boolean): string`
Escapes the following characters from an input string:
@@ -293,7 +285,7 @@ console.log(url); // "file:///foo/bar.txt"
## `Bun.gzipSync()`
Compresses a `Uint8Array` using zlib's DEFLATE algorithm.
Compresses a `Uint8Array` using zlib's GZIP algorithm.
```ts
const buf = Buffer.from("hello".repeat(100)); // Buffer extends Uint8Array
@@ -382,7 +374,7 @@ export type ZlibCompressionOptions = {
## `Bun.gunzipSync()`
Uncompresses a `Uint8Array` using zlib's INFLATE algorithm.
Decompresses a `Uint8Array` using zlib's GUNZIP algorithm.
```ts
const buf = Buffer.from("hello".repeat(100)); // Buffer extends Uint8Array
@@ -410,15 +402,15 @@ The second argument supports the same set of configuration options as [`Bun.gzip
## `Bun.inflateSync()`
Uncompresses a `Uint8Array` using zlib's INFLATE algorithm.
Decompresses a `Uint8Array` using zlib's INFLATE algorithm.
```ts
const buf = Buffer.from("hello".repeat(100));
const compressed = Bun.deflateSync(buf);
const dec = new TextDecoder();
const uncompressed = Bun.inflateSync(compressed);
dec.decode(uncompressed);
const decompressed = Bun.inflateSync(compressed);
dec.decode(decompressed);
// => "hellohellohello..."
```
@@ -436,6 +428,21 @@ const str = Bun.inspect(arr);
// => "Uint8Array(3) [ 1, 2, 3 ]"
```
## `Bun.inspect.custom`
This is the symbol that Bun uses to implement `Bun.inspect`. You can override this to customize how your objects are printed. It is identical to `util.inspect.custom` in Node.js.
```ts
class Foo {
[Bun.inspect.custom]() {
return "foo";
}
}
const foo = new Foo();
console.log(foo); // => "foo"
```
## `Bun.nanoseconds()`
Returns the number of nanoseconds since the current `bun` process started, as a `number`. Useful for high-precision timing and benchmarking.
@@ -468,6 +475,12 @@ await Bun.readableStreamToText(stream);
// returns all chunks as an array
await Bun.readableStreamToArray(stream);
// => unknown[]
// returns all chunks as a FormData object (encoded as x-www-form-urlencoded)
await Bun.readableStreamToFormData(stream);
// returns all chunks as a FormData object (encoded as multipart/form-data)
await Bun.readableStreamToFormData(stream, multipartFormBoundary);
```
## `Bun.resolveSync()`
@@ -494,3 +507,17 @@ To resolve relative to the directory containing the current file, pass `import.m
```ts
Bun.resolveSync("./foo.ts", import.meta.dir);
```
## `serialize` & `deserialize` in `bun:jsc`
To save a JavaScript value into an ArrayBuffer & back, use `serialize` and `deserialize` from the `"bun:jsc"` module.
```js
import { serialize, deserialize } from "bun:jsc";
const buf = serialize({ foo: "bar" });
const obj = deserialize(buf);
console.log(obj); // => { foo: "bar" }
```
Internally, [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) and [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) serialize and deserialize the same way. This exposes the underlying [HTML Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) to JavaScript as an ArrayBuffer.

View File

@@ -12,41 +12,7 @@
Internally Bun's WebSocket implementation is built on [uWebSockets](https://github.com/uNetworking/uWebSockets).
{% /callout %}
## Connect to a WebSocket server
To connect to an external socket server, create an instance of `WebSocket` with the constructor.
```ts
const socket = new WebSocket("ws://localhost:3000");
```
Bun supports setting custom headers. This is a Bun-specific extension of the `WebSocket` standard.
```ts
const socket = new WebSocket("ws://localhost:3000", {
headers: {
// custom headers
},
});
```
To add event listeners to the socket:
```ts
// message is received
socket.addEventListener("message", event => {});
// socket opened
socket.addEventListener("open", event => {});
// socket closed
socket.addEventListener("close", event => {});
// error handler
socket.addEventListener("error", event => {});
```
## Create a WebSocket server
## Start a WebSocket server
Below is a simple WebSocket server built with `Bun.serve`, in which all incoming requests are [upgraded](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) to WebSocket connections in the `fetch` handler. The socket handlers are declared in the `websocket` parameter.
@@ -109,7 +75,7 @@ Bun.serve({
});
```
## Sending messages
### Sending messages
Each `ServerWebSocket` instance has a `.send()` method for sending messages to the client. It supports a range of input types.
@@ -119,7 +85,7 @@ ws.send(response.arrayBuffer()); // ArrayBuffer
ws.send(new Uint8Array([1, 2, 3])); // TypedArray | DataView
```
## Headers
### Headers
Once the upgrade succeeds, Bun will send a `101 Switching Protocols` response per the [spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism). Additional `headers` can be attched to this `Response` in the call to `server.upgrade()`.
@@ -137,7 +103,7 @@ Bun.serve({
});
```
## Contextual data
### Contextual data
Contextual `data` can be attached to a new WebSocket in the `.upgrade()` call. This data is made available on the `ws.data` property inside the WebSocket handlers.
@@ -145,16 +111,20 @@ Contextual `data` can be attached to a new WebSocket in the `.upgrade()` call. T
type WebSocketData = {
createdAt: number;
channelId: string;
authToken: string;
};
// TypeScript: specify the type of `data`
Bun.serve<WebSocketData>({
fetch(req, server) {
// use a library to parse cookies
const cookies = parseCookies(req.headers.get("Cookie"));
server.upgrade(req, {
// TS: this object must conform to WebSocketData
// this object must conform to WebSocketData
data: {
createdAt: Date.now(),
channelId: new URL(req.url).searchParams.get("channelId"),
authToken: cookies["X-Token"],
},
});
@@ -163,53 +133,76 @@ Bun.serve<WebSocketData>({
websocket: {
// handler called when a message is received
async message(ws, message) {
ws.data; // WebSocketData
const user = getUserFromToken(ws.data.authToken);
await saveMessageToDatabase({
channel: ws.data.channelId,
message: String(message),
userId: user.id,
});
},
},
});
```
## Pub/Sub
To connect to this server from the browser, create a new `WebSocket`.
```ts#browser.js
const socket = new WebSocket("ws://localhost:3000/chat");
socket.addEventListener("message", event => {
console.log(event.data);
})
```
{% callout %}
**Identifying users** — The cookies that are currently set on the page will be sent with the WebSocket upgrade request and available on `req.headers` in the `fetch` handler. Parse these cookies to determine the identity of the connecting user and set the value of `data` accordingly.
{% /callout %}
### Pub/Sub
Bun's `ServerWebSocket` implementation implements a native publish-subscribe API for topic-based broadcasting. Individual sockets can `.subscribe()` to a topic (specified with a string identifier) and `.publish()` messages to all other subscribers to that topic. This topic-based broadcast API is similar to [MQTT](https://en.wikipedia.org/wiki/MQTT) and [Redis Pub/Sub](https://redis.io/topics/pubsub).
```ts
const pubsubserver = Bun.serve<{username: string}>({
const server = Bun.serve<{ username: string }>({
fetch(req, server) {
if (req.url === '/chat') {
const cookies = getCookieFromRequest(req);
const success = server.upgrade(req, {
data: {username: cookies.username},
});
const url = new URL(req.url);
if (url.pathname === "/chat") {
console.log(`upgrade!`);
const username = getUsernameFromReq(req);
const success = server.upgrade(req, { data: { username } });
return success
? undefined
: new Response('WebSocket upgrade error', {status: 400});
: new Response("WebSocket upgrade error", { status: 400 });
}
return new Response('Hello world');
return new Response("Hello world");
},
websocket: {
open(ws) {
ws.subscribe('the-group-chat');
ws.publish('the-group-chat', `${ws.data.username} has entered the chat`);
const msg = `${ws.data.username} has entered the chat`;
ws.subscribe("the-group-chat");
ws.publish("the-group-chat", msg);
},
message(ws, message) {
// this is a group chat
// so the server re-broadcasts incoming message to everyone
ws.publish('the-group-chat', `${ws.data.username}: ${message}`);
ws.publish("the-group-chat", `${ws.data.username}: ${message}`);
},
close(ws) {
ws.unsubscribe('the-group-chat');
ws.publish('the-group-chat', `${ws.data.username} has left the chat`);
const msg = `${ws.data.username} has left the chat`;
ws.unsubscribe("the-group-chat");
ws.publish("the-group-chat", msg);
},
},
});
console.log(`Listening on ${server.hostname}:${server.port}`);
```
## Compression
Calling `.publish(data)` will send the message to all subscribers of a topic _except_ the socket that called `.publish()`.
### Compression
Per-message [compression](https://websockets.readthedocs.io/en/stable/topics/compression.html) can be enabled with the `perMessageDeflate` parameter.
@@ -231,7 +224,7 @@ ws.send("Hello world", true);
For fine-grained control over compression characteristics, refer to the [Reference](#reference).
## Backpressure
### Backpressure
The `.send(message)` method of `ServerWebSocket` returns a `number` indicating the result of the operation.
@@ -241,6 +234,46 @@ The `.send(message)` method of `ServerWebSocket` returns a `number` indicating t
This gives you better control over backpressure in your server.
## Connect to a `Websocket` server
{% callout %}
**🚧** — The `WebSocket` client still does not pass the full [Autobahn test suite](https://github.com/crossbario/autobahn-testsuite) and should not be considered ready for production.
{% /callout %}
Bun implements the `WebSocket` class. To create a WebSocket client that connects to a `ws://` or `wss://` server, create an instance of `WebSocket`, as you would in the browser.
```ts
const socket = new WebSocket("ws://localhost:3000");
```
In browsers, the cookies that are currently set on the page will be sent with the WebSocket upgrade request. This is a standard feature of the `WebSocket` API.
For convenience, Bun lets you setting custom headers directly in the constructor. This is a Bun-specific extension of the `WebSocket` standard. _This will not work in browsers._
```ts
const socket = new WebSocket("ws://localhost:3000", {
headers: {
// custom headers
},
});
```
To add event listeners to the socket:
```ts
// message is received
socket.addEventListener("message", event => {});
// socket opened
socket.addEventListener("open", event => {});
// socket closed
socket.addEventListener("close", event => {});
// error handler
socket.addEventListener("error", event => {});
```
## Reference
```ts
@@ -248,7 +281,10 @@ namespace Bun {
export function serve(params: {
fetch: (req: Request, server: Server) => Response | Promise<Response>;
websocket?: {
message: (ws: ServerWebSocket, message: string | ArrayBuffer | Uint8Array) => void;
message: (
ws: ServerWebSocket,
message: string | ArrayBuffer | Uint8Array,
) => void;
open?: (ws: ServerWebSocket) => void;
close?: (ws: ServerWebSocket) => void;
error?: (ws: ServerWebSocket, error: Error) => void;
@@ -278,7 +314,11 @@ type Compressor =
interface Server {
pendingWebsockets: number;
publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;
publish(
topic: string,
data: string | ArrayBufferView | ArrayBuffer,
compress?: boolean,
): number;
upgrade(
req: Request,
options?: {

168
docs/api/workers.md Normal file
View File

@@ -0,0 +1,168 @@
{% callout %}
**🚧** — The `Worker` API is still experimental and should not be considered ready for production.
{% /callout %}
[`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) lets you start and communicate with a new JavaScript instance running on a separate thread while sharing I/O resources with the main thread.
Bun implements a minimal version of the [Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) with extensions that make it work better for server-side use cases. Like the rest of Bun, `Worker` in Bun support CommonJS, ES Modules, TypeScript, JSX, TSX and more out of the box. No extra build steps are necessary.
## Creating a `Worker`
Like in browsers, [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) is a global. Use it to create a new worker thread.
From the main thread:
```js#Main_thread
const workerURL = new URL("worker.ts", import.meta.url).href;
const worker = new Worker(workerURL);
worker.postMessage("hello");
worker.onmessage = event => {
console.log(event.data);
};
```
Worker thread:
```ts#worker.ts_(Worker_thread)
self.onmessage = (event: MessageEvent) => {
console.log(event.data);
postMessage("world");
};
```
You can use `import`/`export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
To simplify error handling, the initial script to load is resolved at the time `new Worker(url)` is called.
```js
const worker = new Worker("/not-found.js");
// throws an error immediately
```
The specifier passed to `Worker` is resolved relative to the project root (like typing `bun ./path/to/file.js`).
### `"open"`
The `"open"` event is emitted when a worker is created and ready to receive messages. This can be used to send an initial message to a worker once it's ready. (This event does not exist in browsers.)
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.addEventListener("open", () => {
console.log("worker is ready");
});
```
Messages are automatically enqueued until the worker is ready, so there is no need to wait for the `"open"` event to send messages.
## Messages with `postMessage`
To send messages, use [`worker.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) and [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). This leverages the [HTML Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
```js
// On the worker thread, `postMessage` is automatically "routed" to the parent thread.
postMessage({ hello: "world" });
// On the main thread
worker.postMessage({ hello: "world" });
```
To receive messages, use the [`message` event handler](https://developer.mozilla.org/en-US/docs/Web/API/Worker/message_event) on the worker and main thread.
```js
// Worker thread:
self.addEventListener("message", event => {
console.log(event.data);
});
// or use the setter:
// self.onmessage = fn
// if on the main thread
worker.addEventListener("message", event => {
console.log(event.data);
});
// or use the setter:
// worker.onmessage = fn
```
## Terminating a worker
A `Worker` instance terminates automatically once it's event loop has no work left to do. Attaching a `"message"` listener on the global or any `MessagePort`s will keep the event loop alive. To forcefully terminate a `Worker`, call `worker.terminate()`.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
// ...some time later
worker.terminate();
```
This will cause the worker's to exit as soon as possible.
### `process.exit()`
A worker can terminate itself with `process.exit()`. This does not terminate the main process. Like in Node.js, `process.on('beforeExit', callback)` and `process.on('exit', callback)` are emitted on the worker thread (and not on the main thread), and the exit code is passed to the `"close"` event.
### `"close"`
The `"close"` event is emitted when a worker has been terminated. It can take some time for the worker to actually terminate, so this event is emitted when the worker has been marked as terminated. The `CloseEvent` will contain the exit code passed to `process.exit()`, or 0 if closed for other reasons.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.addEventListener("close", event => {
console.log("worker is being closed");
});
```
This event does not exist in browsers.
## Managing lifetime
By default, an active `Worker` will keep the main (spawning) process alive, so async tasks like `setTimeout` and promises will keep the process alive. Attaching `message` listeners will also keep the `Worker` alive.
### `worker.unref()`
To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivlent to what Node.js' `worker_threads` does.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.unref();
```
Note: `worker.unref()` is not available in browers.
### `worker.ref()`
To keep the process alive until the `Worker` terminates, call `worker.ref()`. A ref'd worker is the default behavior, and still needs something going on in the event loop (such as a `"message"` listener) for the worker to continue running.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.unref();
// later...
worker.ref();
```
Alternatively, you can also pass an `options` object to `Worker`:
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href, {
ref: false,
});
```
Note: `worker.ref()` is not available in browers.
## Memory usage with `smol`
JavaScript instances can use a lot of memory. Bun's `Worker` supports a `smol` mode that reduces memory usage, at a cost of performance. To enable `smol` mode, pass `smol: true` to the `options` object in the `Worker` constructor.
```js
const worker = new Worker("./i-am-smol.ts", {
smol: true,
});
```
{% details summary="What does `smol` mode actually do?" %}
Setting `smol: true` sets `JSC::HeapSize` to be `Small` instead of the default `Large`.
{% /details %}

View File

@@ -52,7 +52,6 @@ Run this with `bun cat.js /path/to/big/file`.
## Reading from standard input
```ts
// As of Bun v0.3.0, console is an AsyncIterable
for await (const line of console) {
// line of text from stdin
console.log(line);

View File

@@ -28,6 +28,33 @@ All imported files and packages are bundled into the executable, along with a co
- `--outdir` — use `outfile` instead.
- `--external`
- `--splitting`
- `--publicPath`
- `--public-path`
{% /callout %}
## Embedding files
Standalone executables support embedding files.
To embed files into an executable with `bun build --compile`, import the file in your code
```js
// this becomes an internal file path
import icon from "./icon.png";
import { file } from "bun";
export default {
fetch(req) {
return new Response(file(icon));
},
};
```
You may need to specify a `--loader` for it to be treated as a `"file"` loader (so you get back a file path).
Embedded files can be read using `Bun.file`'s functions or the Node.js `fs.readFile` function (in `"node:fs"`).
## Minification
To trim down the size of the executable a little, pass `--minify` to `bun build --compile`. This uses Bun's minifier to reduce the code size. Overall though, Bun's binary is still way too big and we need to make it smaller.

View File

@@ -307,7 +307,7 @@ Depending on the target, Bun will apply different module resolution rules and op
---
- `browser`
- _Default._ For generating bundles that are intended for execution by a browser. Prioritizes the `"browser"` export condition when resolving imports. An error will be thrown if any Node.js or Bun built-ins are imported or used, e.g. `node:fs` or `Bun.serve`.
- _Default._ For generating bundles that are intended for execution by a browser. Prioritizes the `"browser"` export condition when resolving imports. Importing any built-in modules, like `node:events` or `node:path` will work, but calling some functions, like `fs.readFile` will not work.
---
@@ -482,7 +482,7 @@ n/a
{% /codetabs %}
Bun implements a univeral plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](/docs/bundler/plugins) for complete documentation.
Bun implements a universal plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](/docs/bundler/plugins) for complete documentation.
<!-- ### `manifest`
@@ -960,7 +960,7 @@ By specifying `.` as `root`, the generated file structure will look like this:
A prefix to be appended to any import paths in bundled code.
<!-- $ bun build ./index.tsx --outdir ./out --publicPath https://cdn.example.com -->
<!-- $ bun build ./index.tsx --outdir ./out --public-path https://cdn.example.com -->
In many cases, generated bundles will contain no `import` statements. After all, the goal of bundling is to combine all of the code into a single file. However there are a number of cases with the generated bundles will contain `import` statements.
@@ -1272,7 +1272,17 @@ interface BuildArtifact extends Blob {
sourcemap?: BuildArtifact;
}
type Loader = "js" | "jsx" | "ts" | "tsx" | "json" | "toml" | "file" | "napi" | "wasm" | "text";
type Loader =
| "js"
| "jsx"
| "ts"
| "tsx"
| "json"
| "toml"
| "file"
| "napi"
| "wasm"
| "text";
interface BuildOutput {
outputs: BuildArtifact[];

View File

@@ -10,7 +10,7 @@ Bun uses the file extension to determine which built-in _loader_ should be used
**JavaScript**. Default for `.cjs` and `.mjs`.
Parses the code and applies a set if default transforms, like dead-code elimination, tree shaking, and environment variable inlining. Note that Bun does not attempt to down-convert syntax at the moment.
Parses the code and applies a set of default transforms, like dead-code elimination, tree shaking, and environment variable inlining. Note that Bun does not attempt to down-convert syntax at the moment.
### `jsx`

View File

@@ -33,7 +33,7 @@ As you can see, the source code of the `random` function occurs nowhere in the b
## When to use macros
If you have several build scripts for small things where you would otherwise have a one-off build script, bundle-time code execution can be easier to maintain. It lives with the rest of your code, it runs with the rest of the build, it is automatically paralellized, and if it fails, the build fails too.
If you have several build scripts for small things where you would otherwise have a one-off build script, bundle-time code execution can be easier to maintain. It lives with the rest of your code, it runs with the rest of the build, it is automatically parallelized, and if it fails, the build fails too.
If you find yourself running a lot of code at bundle-time though, consider running a server instead.

View File

@@ -1,20 +1,18 @@
{% callout %}
**Note** — Introduced in Bun v0.1.11.
{% /callout %}
Bun provides a universal plugin API that can be used to extend both the _runtime_ and _bundler_.
Plugins intercept imports and perform custom loading logic: reading files, transpiling code, etc. They can be used to add support for additional file types, like `.scss` or `.yaml`. In the context of Bun's bundler, plugins can be used to implement framework-level features like CSS extraction, macros, and client-server code co-location.
For more complete documentation of the Plugin API, see [Runtime > Plugins](/docs/runtime/plugins).
## Usage
A plugin is defined as simple JavaScript object containing a `name` property and a `setup` function. Register a plugin with Bun using the `plugin` function.
```tsx#yamlPlugin.ts
```tsx#myPlugin.ts
import type { BunPlugin } from "bun";
const myPlugin: BunPlugin = {
name: "YAML loader",
name: "Custom loader",
setup(build) {
// implementation
},
@@ -30,304 +28,3 @@ Bun.build({
plugins: [myPlugin],
});
```
<!-- It can also be "registered" with the Bun runtime using the `Bun.plugin()` function. Once registered, the currently executing `bun` process will incorporate the plugin into its module resolution algorithm.
```ts
import {plugin} from "bun";
plugin(myPlugin);
``` -->
## `--preload`
To consume this plugin, add this file to the `preload` option in your [`bunfig.toml`](/docs/runtime/configuration). Bun automatically loads the files/modules specified in `preload` before running a file.
```toml
preload = ["./yamlPlugin.ts"]
```
To preload files during `bun test`:
```toml
[test]
preload = ["./loader.ts"]
```
{% details summary="Usage without preload" %}
Alternatively, you can import this file manually at the top of your project's entrypoint, before any application code is imported.
```ts#app.ts
import "./yamlPlugin.ts";
import { config } from "./config.yml";
console.log(config);
```
{% /details %}
## Third-party plugins
By convention, third-party plugins intended for consumption should export a factory function that accepts some configuration and returns a plugin object.
```ts
import { plugin } from "bun";
import fooPlugin from "bun-plugin-foo";
plugin(
fooPlugin({
// configuration
}),
);
// application code
```
Bun's plugin API is based on [esbuild](https://esbuild.github.io/plugins). Only [a subset](/docs/bundler/vs-esbuild#plugin-api) of the esbuild API is implemented, but some esbuild plugins "just work" in Bun, like the official [MDX loader](https://mdxjs.com/packages/esbuild/):
```jsx
import { plugin } from "bun";
import mdx from "@mdx-js/esbuild";
plugin(mdx());
import { renderToStaticMarkup } from "react-dom/server";
import Foo from "./bar.mdx";
console.log(renderToStaticMarkup(<Foo />));
```
## Loaders
<!-- The plugin logic is implemented in the `setup` function using the builder provided as the first argument (`build` in the example above). The `build` variable provides two methods: `onResolve` and `onLoad`. -->
<!-- ## `onResolve` -->
<!-- The `onResolve` method lets you intercept imports that match a particular regex and modify the resolution behavior, such as re-mapping the import to another file. In the simplest case, you can simply remap the matched import to a new path.
```ts
import { plugin } from "bun";
plugin({
name: "YAML loader",
setup(build) {
build.onResolve();
// implementation
},
});
``` -->
<!--
Internally, Bun's transpiler automatically turns `plugin()` calls into separate files (at most 1 per file). This lets loaders activate before the rest of your application runs with zero configuration. -->
Plugins are primarily used to extend Bun with loaders for additional file types. Let's look at a simple plugin that implements a loader for `.yaml` files.
```ts#yamlPlugin.ts
import { plugin } from "bun";
plugin({
name: "YAML",
async setup(build) {
const { load } = await import("js-yaml");
const { readFileSync } = await import("fs");
// when a .yaml file is imported...
build.onLoad({ filter: /\.(yaml|yml)$/ }, (args) => {
// read and parse the file
const text = readFileSync(args.path, "utf8");
const exports = load(text) as Record<string, any>;
// and returns it as a module
return {
exports,
loader: "object", // special loader for JS objects
};
});
},
});
```
With this plugin, data can be directly imported from `.yaml` files.
{% codetabs %}
```ts#index.ts
import "./yamlPlugin.ts"
import {name, releaseYear} from "./data.yml"
console.log(name, releaseYear);
```
```yaml#data.yml
name: Fast X
releaseYear: 2023
```
{% /codetabs %}
Note that the returned object has a `loader` property. This tells Bun which of its internal loaders should be used to handle the result. Even though we're implementing a loader for `.yaml`, the result must still be understandable by one of Bun's built-in loaders. It's loaders all the way down.
In this case we're using `"object"`—a built-in loader (intended for use by plugins) that converts a plain JavaScript object to an equivalent ES module. Any of Bun's built-in loaders are supported; these same loaders are used by Bun internally for handling files of various kinds. The table below is a quick reference; refer to [Bundler > Loaders](/docs/bundler/loaders) for complete documentation.
{% table %}
- Loader
- Extensions
- Output
---
- `js`
- `.mjs` `.cjs`
- Transpile to JavaScript files
---
- `jsx`
- `.js` `.jsx`
- Transform JSX then transpile
---
- `ts`
- `.ts` `.mts` `cts`
- Transform TypeScript then transpile
---
- `tsx`
- `.tsx`
- Transform TypeScript, JSX, then transpile
---
- `toml`
- `.toml`
- Parse using Bun's built-in TOML parser
---
- `json`
- `.json`
- Parse using Bun's built-in JSON parser
---
- `napi`
- `.node`
- Import a native Node.js addon
---
- `wasm`
- `.wasm`
- Import a native Node.js addon
---
- `object`
- _none_
- A special loader intended for plugins that converts a plain JavaScript object to an equivalent ES module. Each key in the object corresponds to a named export.
{% /callout %}
Loading a YAML file is useful, but plugins support more than just data loading. Let's look at a plugin that lets Bun import `*.svelte` files.
```ts#sveltePlugin.ts
import { plugin } from "bun";
await plugin({
name: "svelte loader",
async setup(build) {
const { compile } = await import("svelte/compiler");
const { readFileSync } = await import("fs");
// when a .svelte file is imported...
build.onLoad({ filter: /\.svelte$/ }, ({ path }) => {
// read and compile it with the Svelte compiler
const file = readFileSync(path, "utf8");
const contents = compile(file, {
filename: path,
generate: "ssr",
}).js.code;
// and return the compiled source code as "js"
return {
contents,
loader: "js",
};
});
},
});
```
> Note: in a production implementation, you'd want to cache the compiled output and include additional error handling.
The object returned from `build.onLoad` contains the compiled source code in `contents` and specifies `"js"` as its loader. That tells Bun to consider the returned `contents` to be a JavaScript module and transpile it using Bun's built-in `js` loader.
With this plugin, Svelte components can now be directly imported and consumed.
```js
import "./sveltePlugin.ts";
import MySvelteComponent from "./component.svelte";
console.log(mySvelteComponent.render());
```
## Reading `Bun.build`'s config
Plugins can read and write to the [build config](/docs/bundler#api) with `build.config`.
```ts
Bun.build({
entrypoints: ["./app.ts"],
outdir: "./dist",
sourcemap: "external",
plugins: [
{
name: "demo",
setup(build) {
console.log(build.config.sourcemap); // "external"
build.config.minify = true; // enable minification
// `plugins` is readonly
console.log(`Number of plugins: ${build.config.plugins.length}`);
},
},
],
});
```
## Reference
```ts
namespace Bun {
function plugin(plugin: { name: string; setup: (build: PluginBuilder) => void }): void;
}
type PluginBuilder = {
onResolve: (
args: { filter: RegExp; namespace?: string },
callback: (args: { path: string; importer: string }) => {
path: string;
namespace?: string;
} | void,
) => void;
onLoad: (
args: { filter: RegExp; namespace?: string },
callback: (args: { path: string }) => {
loader?: Loader;
contents?: string;
exports?: Record<string, any>;
},
) => void;
config: BuildConfig;
};
type Loader = "js" | "jsx" | "ts" | "tsx" | "json" | "toml" | "object";
```
The `onLoad` method optionally accepts a `namespace` in addition to the `filter` regex. This namespace will be be used to prefix the import in transpiled code; for instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` will transform an import from `./myfile.yaml` into `yaml:./myfile.yaml`.

View File

@@ -1,7 +1,3 @@
{% callout %}
**Note** — Available in Bun v0.6.0 and later.
{% /callout %}
Bun's bundler API is inspired heavily by [esbuild](https://esbuild.github.io/). Migrating to Bun's bundler from esbuild should be relatively painless. This guide will briefly explain why you might consider migrating to Bun's bundler and provide a side-by-side API comparison reference for those who are already familiar with esbuild's API.
There are a few behavioral differences to note.
@@ -897,7 +893,7 @@ const myPlugin: BunPlugin = {
};
```
The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](/docs/bundler/plugins#reading-bunbuilds-config) (same thing but with Bun's `BuildConfig` format) instead.
The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](/docs/bundler/plugins) (same thing but with Bun's `BuildConfig` format) instead.
```ts
import type { BunPlugin } from "bun";

View File

@@ -13,8 +13,6 @@ If you pass `-y` or `--yes`, it will assume you want to continue without asking
At the end, it runs `bun install` to install `bun-types`.
Added in Bun v0.1.7.
#### How is `bun init` different than `bun create`?
`bun init` is for blank projects. `bun create` applies templates.

View File

@@ -47,6 +47,9 @@ registry = "https://registry.yarnpkg.com/"
# Install for production? This is the equivalent to the "--production" CLI argument
production = false
# Disallow changes to lockfile? This is the equivalent to the "--fozen-lockfile" CLI argument
frozenLockfile = false
# Don't actually install
dryRun = true
@@ -108,6 +111,7 @@ export interface Install {
scopes: Scopes;
registry: Registry;
production: boolean;
frozenLockfile: boolean;
dryRun: boolean;
optional: boolean;
dev: boolean;

View File

@@ -50,7 +50,7 @@ Running `bun create` performs the following steps:
- Initialize a fresh Git repo. Opt out with the `--no-git` flag.
- Run the template's configured `start` script, if defined.
## Official templates
<!-- ## Official templates
The following official templates are available.
@@ -73,7 +73,7 @@ Welcome to bun! Create a new project by pasting any of the following:
{% callout %}
⚡️ **Speed** — At the time of writing, `bun create react app` runs ~11x faster on a M1 Macbook Pro than `yarn create react-app app`.
{% /callout %}
{% /callout %} -->
## GitHub repos

View File

@@ -40,7 +40,7 @@ On Linux, `bun install` tends to install packages 20-100x faster than `npm insta
Running `bun install` will:
- **Install** all `dependencies`, `devDependencies`, and `optionalDependencies`. Bun does not install `peerDependencies` by default.
- **Run** your project's `{pre|post}install` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies.
- **Run** your project's `{pre|post}install` and `{pre|post}prepare` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies.
- **Write** a `bun.lockb` lockfile to the project root.
To install in production mode (i.e. without `devDependencies`):
@@ -49,6 +49,12 @@ To install in production mode (i.e. without `devDependencies`):
$ bun install --production
```
To install with reproducible dependencies, use `--frozen-lockfile`. If your `package.json` disagrees with `bun.lockb`, Bun will exit with an error. This is useful for production builds and CI environments.
```bash
$ bun install --frozen-lockfile
```
To perform a dry run (i.e. don't actually install anything):
```bash
@@ -80,6 +86,9 @@ peer = false
# equivalent to `--production` flag
production = false
# equivalent to `--frozen-lockfile` flag
frozenLockfile = false
# equivalent to `--dry-run` flag
dryRun = false
```
@@ -105,7 +114,7 @@ $ bun add zod@latest
To add a package as a dev dependency (`"devDependencies"`):
```bash
$ bun add --development @types/react
$ bun add --dev @types/react
$ bun add -d @types/react
```
@@ -115,6 +124,26 @@ To add a package as an optional dependency (`"optionalDependencies"`):
$ bun add --optional lodash
```
To add a package and pin to the resolved version, use `--exact`. This will resolve the version of the package and add it to your `package.json` with an exact version number instead of a version range.
```bash
$ bun add react --exact
```
This will add the following to your `package.json`:
```jsonc
{
"dependencies": {
// without --exact
"react": "^18.2.0", // this matches >= 18.2.0 < 19.0.0
// with --exact
"react": "18.2.0" // this matches only 18.2.0 exactly
}
}
```
To install a package globally:
```bash
@@ -168,7 +197,7 @@ $ cat package.json
"version": "1.0.0"
}
$ bun link
bun link v0.5.7 (7416672e)
bun link v1.x (7416672e)
Success! Registered "cool-pkg"
To use cool-pkg in a project, run:
@@ -185,7 +214,7 @@ $ cd /path/to/my-app
$ bun link cool-pkg
```
This will add `cool-pkg` to the `dependencies` field of your app's package.json with a special version specifier that tells Bun to load from the registered local directory instead of installing from `npm`.
In addition, the `--save` flag can be used to add `cool-pkg` to the `dependencies` field of your app's package.json with a special version specifier that tells Bun to load from the registered local directory instead of installing from `npm`:
```json-diff
{
@@ -197,6 +226,46 @@ This will add `cool-pkg` to the `dependencies` field of your app's package.json
}
```
## Trusted dependencies
Unlike other npm clients, Bun does not execute arbitrary lifecycle scripts for installed dependencies, such as `postinstall`. These scripts represent a potential security risk, as they can execute arbitrary code on your machine.
<!-- Bun maintains an allow-list of popular packages containing `postinstall` scripts that are known to be safe. To run lifecycle scripts for packages that aren't on this list, add the package to `trustedDependencies` in your package.json. -->
To tell Bun to allow lifecycle scripts for a particular package, add the package to `trustedDependencies` in your package.json.
<!-- ```json-diff
{
"name": "my-app",
"version": "1.0.0",
+ "trustedDependencies": {
+ "my-trusted-package": "*"
+ }
}
``` -->
```json-diff
{
"name": "my-app",
"version": "1.0.0",
+ "trustedDependencies": ["my-trusted-package"]
}
```
Bun reads this field and will run lifecycle scripts for `my-trusted-package`.
<!-- If you specify a version range, Bun will only execute lifecycle scripts if the resolved package version matches the range. -->
<!--
```json
{
"name": "my-app",
"version": "1.0.0",
"trustedDependencies": {
"my-trusted-package": "^1.0.0"
}
}
``` -->
## Git dependencies
To add a dependency from a git repository:

View File

@@ -32,6 +32,22 @@ The "naked" `bun` command is equivalent to `bun run`.
$ bun index.tsx
```
### `--watch`
To run a file in watch mode, use the `--watch` flag.
```bash
$ bun --watch run index.tsx
```
### `--smol`
In memory-constrained environments, use the `--smol` flag to reduce memory usage at a cost to performance.
```bash
$ bun --smol run index.tsx
```
## Run a `package.json` script
{% note %}
@@ -102,8 +118,8 @@ To debug environment variables, run `bun run env` to view a list of resolved env
Bun is designed to start fast and run fast.
Under the hood Bun uses the [JavaScriptCore engine](https://developer.apple.com/documentation/javascriptcore), which is developed by Apple for Safari. In most cases, the startup and running performance is faster than V8, the engine used by Node.js and Chromium-based browsers. It's transpiler and runtime are written in Zig, a modern, high-performance language. On Linux, this translates into startup times [4x faster](https://twitter.com/jarredsumner/status/1499225725492076544) than Node.js.
Under the hood Bun uses the [JavaScriptCore engine](https://developer.apple.com/documentation/javascriptcore), which is developed by Apple for Safari. In most cases, the startup and running performance is faster than V8, the engine used by Node.js and Chromium-based browsers. Its transpiler and runtime are written in Zig, a modern, high-performance language. On Linux, this translates into startup times [4x faster](https://twitter.com/jarredsumner/status/1499225725492076544) than Node.js.
{% image src="/images/bun-run-speed.jpeg" caption="Bun vs Node.js vs Deno running Hello World" /%}
<!-- If no `node_modules` directory is found in the working directory or above, Bun will abandon Node.js-style module resolution in favor of the `Bun module resolution algorithm`. Under Bun-style module resolution, all packages are _auto-installed_ on the fly into a [global module cache](/docs/cli/install#global-cache). For full details on this algorithm, refer to [Runtime > Modules](/docs/runtime/modules). -->
<!-- If no `node_modules` directory is found in the working directory or above, Bun will abandon Node.js-style module resolution in favor of the `Bun module resolution algorithm`. Under Bun-style module resolution, all packages are _auto-installed_ on the fly into a [global module cache](/docs/install/cache). For full details on this algorithm, refer to [Runtime > Modules](/docs/runtime/modules). -->

View File

@@ -30,14 +30,50 @@ The runner recursively searches the working directory for files that match the f
- `*.spec.{js|jsx|ts|tsx}`
- `*_spec.{js|jsx|ts|tsx}`
You can filter the set of tests to run by passing additional positional arguments to `bun test`. Any file in the directory with an _absolute path_ that contains one of the filters will run. Commonly, these filters will be file or directory names; glob patterns are not yet supported.
You can filter the set of _test files_ to run by passing additional positional arguments to `bun test`. Any test file with a path that matches one of the filters will run. Commonly, these filters will be file or directory names; glob patterns are not yet supported.
```bash
$ bun test <filter> <filter> ...
```
To filter by _test name_, use the `-t`/`--test-name-pattern` flag.
```sh
# run all tests or test suites with "addition" in the name
$ bun test --test-name-pattern addition
```
The test runner runs all tests in a single process. It loads all `--preload` scripts (see [Lifecycle](/docs/test/lifecycle) for details), then runs all tests. If a test fails, the test runner will exit with a non-zero exit code.
## Timeouts
Use the `--timeout` flag to specify a _per-test_ timeout in milliseconds. If a test times out, it will be marked as failed. The default value is `5000`.
```bash
# default value is 5000
$ bun test --timeout 20
```
## Rerun tests
Use the `--rerun-each` flag to run each test multiple times. This is useful for detecting flaky or non-deterministic test failures.
```sh
$ bun test --rerun-each 100
```
## Bail out with `--bail`
Use the `--bail` flag to abort the test run early after a pre-determined number of test failures. By default Bun will run all tests and report all failures, but sometimes in CI environments it's preferable to terminate earlier to reduce CPU usage.
```sh
# bail after 1 failure
$ bun test --bail
# bail after 10 failure
$ bun test --bail 10
```
## Watch mode
Similar to `bun run`, you can pass the `--watch` flag to `bun test` to watch for changes and re-run tests.
@@ -65,6 +101,24 @@ $ bun test --preload ./setup.ts
See [Test > Lifecycle](/docs/test/lifecycle) for complete documentation.
## Mocks
Create mocks with the `mock` function. Mocks are automatically reset between tests.
```ts
import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());
test("random", async () => {
const val = random();
expect(val).toBeGreaterThan(0);
expect(random).toHaveBeenCalled();
expect(random).toHaveBeenCalledTimes(1);
});
```
See [Test > Mocks](/docs/test/mocks) for complete documentation.
## Snapshot testing
Snapshots are supported by `bun test`. See [Test > Snapshots](/docs/test/snapshots) for complete documentation.
@@ -77,6 +131,8 @@ Bun is compatible with popular UI testing libraries:
- [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro/)
- [React Testing Library](https://testing-library.com/docs/react-testing-library/intro)
See [Test > DOM Testing](/docs/test/dom) for complete documentation.
## Performance
Bun's test runner is fast.

View File

@@ -1,36 +0,0 @@
[Buchta](https://buchtajs.com) is a fullstack framework designed to take full advantage of Bun's strengths. It currently supports Preact and Svelte.
To get started:
```bash
$ bunx buchta init myapp
Project templates:
- svelte
- default
- preact
Name of template: preact
Do you want TSX? y
Do you want SSR? y
Enable livereload? y
Buchta Preact project was setup successfully!
$ cd myapp
$ bun install
$ bunx buchta serve
```
To implement a simple HTTP server with Buchta:
```ts#server.ts
import { Buchta, type BuchtaRequest, type BuchtaResponse } from "buchta";
const app = new Buchta();
app.get("/api/hello/", (req: BuchtaRequest, res: BuchtaResponse) => {
res.send("Hello, World!");
});
app.run();
```
For more information, refer to Buchta's [documentation](https://buchtajs.com/docs/).

View File

@@ -1,7 +1,7 @@
[Elysia](https://elysiajs.com) is a Bun-first performance focused web framework that takes full advantage of Bun's HTTP, file system, and hot reloading APIs.
Designed with TypeScript in mind, you don't need to understand TypeScript to gain the benefit of TypeScript with Elysia. The library understands what you want and automatically infers the type from your code.
:zap: Elysia is [one of the fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark)
⚡️ Elysia is [one of the fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark)
```ts#server.ts
import { Elysia } from 'elysia'
@@ -9,7 +9,7 @@ import { Elysia } from 'elysia'
const app = new Elysia()
.get('/', () => 'Hello Elysia')
.listen(8080)
console.log(`🦊 Elysia is running at on port ${app.server.port}...`)
```

View File

@@ -22,7 +22,7 @@ app.listen(port, () => {
Bun implements the [`node:http`](https://nodejs.org/api/http.html) and [`node:https`](https://nodejs.org/api/https.html) modules that these libraries rely on. These modules can also be used directly, though [`Bun.serve`](/docs/api/http) is recommended for most use cases.
{% callout %}
**Note** — Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node_http) page for more detailed compatibility information.
**Note** — Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node-http) page for more detailed compatibility information.
{% /callout %}
```ts

View File

@@ -1,15 +1,16 @@
[Hono](https://github.com/honojs/hono) is a lightweight ultrafast web framework designed for the edge.
```ts
import { Hono } from 'hono'
const app = new Hono()
import { Hono } from "hono";
const app = new Hono();
app.get('/', (c) => c.text('Hono!'))
app.get("/", c => c.text("Hono!"));
export default app
export default app;
```
Get started with `bun create` or follow Hono's [Bun quickstart](https://hono.dev/getting-started/bun).
```bash
$ bun create hono ./myapp
$ cd myapp

View File

@@ -1,20 +1,20 @@
[Stric](https://github.com/bunsvr) is a minimalist, fast web framework for Bun.
```ts#index.ts
import { App } from "@stricjs/core";
import { Router } from '@stricjs/router';
// Export the fetch handler and serve with Bun
export default new App()
// Return "Hi!" on every request
.use(() => new Response("Hi!"));
export default new Router()
// Return 'Hi' on every request
.get('/', () => new Response('Hi'));
```
Stric provides support for [ArrowJS](https://www.arrow-js.com), a library for building reactive interfaces in **native** JavaScript.
Stric provides support for [ArrowJS](https://www.arrow-js.com), a library for building reactive interfaces.
{% codetabs %}
```ts#src/App.ts
import { html } from "@stricjs/arrow/utils";
import { html } from '@stricjs/arrow/utils';
// Code inside this function can use web APIs
export function render() {
@@ -23,10 +23,10 @@ export function render() {
};
// Set the path to handle
export const path = "/";
export const path = '/';
```
```ts#index.ts
import { PageRouter } from "@stricjs/arrow";
import { PageRouter } from '@stricjs/arrow';
// Create a page router, build and serve directly
new PageRouter().serve();

Some files were not shown because too many files have changed in this diff Show More