diff --git a/.gitmodules b/.gitmodules
index ad817c2e03..9dd25dae9e 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -11,7 +11,7 @@
ignore = dirty
[submodule "src/deps/mimalloc"]
path = src/deps/mimalloc
- url = https://github.com/microsoft/mimalloc.git
+ url = https://github.com/Jarred-Sumner/mimalloc.git
ignore = dirty
[submodule "src/deps/zlib"]
path = src/deps/zlib
@@ -24,4 +24,8 @@
[submodule "src/deps/boringssl"]
path = src/deps/boringssl
url = https://github.com/google/boringssl.git
- ignore = dirty
\ No newline at end of file
+ ignore = dirty
+[submodule "src/deps/libbacktrace"]
+ path = src/deps/libbacktrace
+ url = https://github.com/ianlancetaylor/libbacktrace
+ ignore = dirty
diff --git a/.scripts/write-versions.sh b/.scripts/write-versions.sh
new file mode 100644
index 0000000000..af020f3f0f
--- /dev/null
+++ b/.scripts/write-versions.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -euxo pipefail
+
+WEBKIT_VERSION=$(git rev-parse HEAD:./src/javascript/jsc/WebKit)
+MIMALLOC_VERSION=$(git rev-parse HEAD:./src/deps/mimalloc)
+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)
+
+rm -rf src/generated_versions_list.zig
+echo "// AUTO-GENERATED FILE. Created via .scripts/write-versions.sh" >src/generated_versions_list.zig
+echo "" >>src/generated_versions_list.zig
+echo "pub const webkit = \"$WEBKIT_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const mimalloc = \"$MIMALLOC_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const libarchive = \"$LIBARCHIVE_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const picohttpparser = \"$PICOHTTPPARSER_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const boringssl = \"$BORINGSSL_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const zlib = \"$ZLIB_VERSION\";" >>src/generated_versions_list.zig
+echo "pub const zig = @import(\"std\").fmt.comptimePrint(\"{}\", .{@import(\"builtin\").zig_version});" >>src/generated_versions_list.zig
+echo "" >>src/generated_versions_list.zig
+
+zig fmt src/generated_versions_list.zig
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 54673976df..48d2a5d348 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -1,7 +1,6 @@
{
"version": "0.2.0",
"configurations": [
-
{
"type": "lldb",
"request": "launch",
@@ -61,8 +60,17 @@
"request": "launch",
"name": "bun create debug",
"program": "bun-debug",
- "args": ["create", "hanford/trends", "foo"],
- "cwd": "/tmp/",
+ "args": ["create", "next", "foo", "--open", "--force"],
+ "cwd": "/tmp",
+ "console": "internalConsole"
+ },
+ {
+ "type": "lldb",
+ "request": "launch",
+ "name": "bun dev debug",
+ "program": "bun-debug",
+ "args": ["dev"],
+ "cwd": "/tmp/foo",
"console": "internalConsole"
},
{
@@ -70,8 +78,9 @@
"request": "launch",
"name": "bun run debug",
"program": "bun-debug",
- "args": ["paoskdpoasdk"],
- "cwd": "/tmp/",
+ "args": ["run", "./integration/bunjs-only-snippets/some-fs.js"],
+ // "args": ["--version"],
+ "cwd": "${workspaceFolder}",
"console": "internalConsole"
},
{
@@ -231,17 +240,49 @@
"request": "launch",
"name": "Dazzle serve",
"program": "bun-debug",
- "args": ["--origin=http://localhost:5001", "--disable-bun.js", "--disable-hmr"],
- "cwd": "/Users/jarred/Build/lattice/apps/dazzle",
+ "args": [
+ "--origin=http://localhost:5001",
+ "--disable-bun.js",
+ "--disable-hmr"
+ ],
+ "cwd": "/Users/jarred/Build/big-app/apps/dazzle",
"console": "internalConsole"
},
{
"type": "lldb",
"request": "launch",
- "name": "bun",
+ "name": "Dazzle bun",
"program": "bun-debug",
"args": ["bun", "--use=next"],
- "cwd": "/Users/jarred/Build/lattice/apps/dazzle",
+ "cwd": "/Users/jarred/Build/big-app/apps/dazzle",
+ "console": "internalConsole",
+ "env": { "GOMAXPROCS": "1" }
+ },
+ {
+ "type": "lldb",
+ "request": "launch",
+ "name": "bun run",
+ "program": "bun-debug",
+ "args": ["cat.js", "./node_modules/@babel/standalone/babel.js"],
+ "cwd": "/Users/jarred/Build/foobar",
+ "console": "internalConsole"
+ },
+ {
+ "type": "lldb",
+ "request": "launch",
+ "name": "bun run callback bench",
+ "program": "bun-debug",
+ "args": ["/Users/jarred/Code/bun/bench/snippets/callbacks-overhead.mjs"],
+ "cwd": "/Users/jarred/Build/foobar",
+ "console": "internalConsole"
+ },
+ {
+ "type": "lldb",
+ "request": "launch",
+ "name": "bun test",
+ "program": "bun-debug",
+ "args": ["wiptest", "import-meta"],
+ "cwd": "${workspaceFolder}",
"console": "internalConsole"
},
{
@@ -367,9 +408,7 @@
"program": "bun-debug",
"args": ["install", "--backend=clonefile", "--force"],
"cwd": "/Users/jarred/Build/octokit-test",
- "env": {
-
- },
+ "env": {},
"console": "internalConsole"
},
{
@@ -379,8 +418,7 @@
"program": "bun-debug",
"args": ["add", "typescript"],
"cwd": "/tmp/wow-such-npm",
- "env": {
- },
+ "env": {},
"console": "internalConsole"
},
{
@@ -390,8 +428,7 @@
"program": "bun-debug",
"args": ["add", "react"],
"cwd": "/tmp/wow-such-npm",
- "env": {
- },
+ "env": {},
"console": "internalConsole"
},
{
@@ -401,8 +438,7 @@
"program": "bun-debug",
"args": ["remove", "foo"],
"cwd": "/Users/jarred/Build/athena.yarn",
- "env": {
- },
+ "env": {},
"console": "internalConsole"
},
{
@@ -414,7 +450,6 @@
"cwd": "/tmp/wow-such-npm",
"env": {
"BUN_CONFIG_SKIP_SAVE_LOCKFILE": "1"
-
},
"console": "internalConsole"
},
@@ -530,7 +565,6 @@
"cwd": "${workspaceFolder}/src/test/fixtures",
"console": "internalConsole"
},
-
// {
// "type": "lldb",
diff --git a/.vscode/settings.json b/.vscode/settings.json
index e7b921d79f..bd7699e024 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -8,7 +8,7 @@
"search.useIgnoreFiles": true,
"zig.buildOnSave": false,
"[zig]": {
- "editor.defaultFormatter": "tiehuis.zig"
+ "editor.defaultFormatter": "AugusteRame.zls-vscode"
},
"[ts]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
diff --git a/Makefile b/Makefile
index 7b18d06530..f95cf17903 100644
--- a/Makefile
+++ b/Makefile
@@ -11,6 +11,7 @@ endif
MIN_MACOS_VERSION = 10.14
+
MARCH_NATIVE =
ARCH_NAME :=
@@ -73,7 +74,7 @@ OPENSSL_LINUX_DIR = $(BUN_DEPS_DIR)/openssl/openssl-OpenSSL_1_1_1l
CMAKE_FLAGS_WITHOUT_RELEASE = -DCMAKE_C_COMPILER=$(CC) -DCMAKE_CXX_COMPILER=$(CXX) -DCMAKE_OSX_DEPLOYMENT_TARGET=$(MIN_MACOS_VERSION)
CMAKE_FLAGS = $(CMAKE_FLAGS_WITHOUT_RELEASE) -DCMAKE_BUILD_TYPE=Release
-CFLAGS = $(MACOS_MIN_FLAG)
+
LIBTOOL=libtoolize
ifeq ($(OS_NAME),darwin)
@@ -84,6 +85,8 @@ ifeq ($(OS_NAME),linux)
LIBICONV_PATH =
endif
+
+CFLAGS = $(MACOS_MIN_FLAG) $(MARCH_NATIVE) -ffunction-sections -fdata-sections -g -O3
BUN_TMP_DIR := /tmp/make-bun
BUN_DEPLOY_DIR = /tmp/bun-v$(PACKAGE_JSON_VERSION)/$(PACKAGE_NAME)
@@ -111,10 +114,12 @@ ZLIB_LIB_DIR ?= $(BUN_DEPS_DIR)/zlib
JSC_FILES := $(JSC_LIB)/libJavaScriptCore.a $(JSC_LIB)/libWTF.a $(JSC_LIB)/libbmalloc.a
+ENABLE_MIMALLOC ?= 1
+
# https://github.com/microsoft/mimalloc/issues/512
# Linking mimalloc via object file on macOS x64 can cause heap corruption
-MIMALLOC_FILE = libmimalloc.o
-MIMALLOC_INPUT_PATH = CMakeFiles/mimalloc-obj.dir/src/static.c.o
+_MIMALLOC_FILE = libmimalloc.o
+_MIMALLOC_INPUT_PATH = CMakeFiles/mimalloc-obj.dir/src/static.c.o
DEFAULT_LINKER_FLAGS =
@@ -125,10 +130,22 @@ DEFAULT_LINKER_FLAGS= -pthread -ldl
endif
ifeq ($(OS_NAME),darwin)
JSC_BUILD_STEPS += jsc-build-mac jsc-copy-headers
- MIMALLOC_FILE = libmimalloc.a
- MIMALLOC_INPUT_PATH = libmimalloc.a
+ _MIMALLOC_FILE = libmimalloc.a
+ _MIMALLOC_INPUT_PATH = libmimalloc.a
endif
+MIMALLOC_FILE=
+MIMALLOC_INPUT_PATH=
+MIMALLOC_FILE_PATH=
+ifeq ($(ENABLE_MIMALLOC), 1)
+MIMALLOC_FILE=$(_MIMALLOC_FILE)
+MIMALLOC_FILE_PATH=$(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE)
+MIMALLOC_INPUT_PATH=$(_MIMALLOC_INPUT_PATH)
+endif
+
+
+
+
MACOSX_DEPLOYMENT_TARGET=$(MIN_MACOS_VERSION)
MACOS_MIN_FLAG=
@@ -207,28 +224,34 @@ CLANG_FLAGS = $(INCLUDE_DIRS) \
-DENABLE_INSPECTOR_ALTERNATE_DISPATCHERS=0 \
-DBUILDING_JSCONLY__ \
-DASSERT_ENABLED=0 \
- -fPIE
+ -fvisibility=hidden \
+ -fvisibility-inlines-hidden \
+ -fno-omit-frame-pointer $(CFLAGS)
# This flag is only added to webkit builds on Apple platforms
# It has something to do with ICU
ifeq ($(OS_NAME), darwin)
CLANG_FLAGS += -DDU_DISABLE_RENAMING=1 \
- $(MACOS_MIN_FLAG) -lstdc++
+ -lstdc++ \
+ -ffunction-sections \
+ -fdata-sections \
+ -Wl,-no_eh_labels \
+ -Wl,-dead_strip \
+ -Wl,-dead_strip_dylibs \
+ -force_flat_namespace
endif
-ARCHIVE_FILES_WITHOUT_LIBCRYPTO = $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE) \
+ARCHIVE_FILES_WITHOUT_LIBCRYPTO = $(MIMALLOC_FILE_PATH) \
$(BUN_DEPS_OUT_DIR)/libz.a \
$(BUN_DEPS_OUT_DIR)/libarchive.a \
$(BUN_DEPS_OUT_DIR)/libssl.a \
$(BUN_DEPS_OUT_DIR)/picohttpparser.o \
+ $(BUN_DEPS_OUT_DIR)/libbacktrace.a
ARCHIVE_FILES = $(ARCHIVE_FILES_WITHOUT_LIBCRYPTO) $(BUN_DEPS_OUT_DIR)/libcrypto.boring.a
-ifeq ($(OS_NAME), darwin)
-ARCHIVE_FILES += $(BUN_DEPS_OUT_DIR)/libCrashReporter.a $(BUN_DEPS_OUT_DIR)/libCrashReporter.bindings.a
-endif
PLATFORM_LINKER_FLAGS =
@@ -238,7 +261,6 @@ ifeq ($(OS_NAME), linux)
PLATFORM_LINKER_FLAGS = \
-fuse-ld=lld \
-lc \
- -fno-omit-frame-pointer \
-Wl,-z,now \
-Wl,--as-needed \
-Wl,--gc-sections \
@@ -250,6 +272,11 @@ PLATFORM_LINKER_FLAGS = \
${STATIC_MUSL_FLAG}
endif
+ifeq ($(OS_NAME), darwin)
+PLATFORM_LINKER_FLAGS = \
+ -Wl,-keep_private_externs
+endif
+
BUN_LLD_FLAGS = $(OBJ_FILES) \
${ICU_FLAGS} \
@@ -264,10 +291,10 @@ BUN_LLD_FLAGS = $(OBJ_FILES) \
bun:
-vendor-without-check: api analytics node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive pl-crash-report
+vendor-without-check: api analytics node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive libbacktrace
boringssl-build:
- cd $(BUN_DEPS_DIR)/boringssl && mkdir -p build && cd build && cmake $(CMAKE_FLAGS) -GNinja .. && ninja
+ cd $(BUN_DEPS_DIR)/boringssl && mkdir -p build && cd build && CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) -GNinja .. && ninja
boringssl-copy:
cp $(BUN_DEPS_DIR)/boringssl/build/ssl/libssl.a $(BUN_DEPS_OUT_DIR)/libssl.a
@@ -275,32 +302,19 @@ boringssl-copy:
boringssl: boringssl-build boringssl-copy
-download-pl-crash-report:
- rm -rf /tmp/PLCrashReporter.zip /tmp/PLCrashReporter
- curl -L https://github.com/microsoft/plcrashreporter/releases/download/1.10.1/PLCrashReporter-Static-1.10.1.zip > /tmp/PLCrashReporter.zip
- unzip /tmp/PLCrashReporter.zip -d /tmp
- cp /tmp/PLCrashReporter/libCrashReporter-MacOSX-Static.a $(BUN_DEPS_OUT_DIR)/libCrashReporter.a
- mkdir -p $(BUN_DEPS_DIR)/PLCrashReporter/include/PLCrashReporter
- cp -r /tmp/PLCrashReporter/include/*.h $(BUN_DEPS_DIR)/PLCrashReporter/include/PLCrashReporter
-
-pl-crash-report:
-
-ifeq ($(OS_NAME), darwin)
-pl-crash-report: pl-crash-report-mac
-endif
-
-pl-crash-report-mac: download-pl-crash-report pl-crash-report-mac-compile
-
-pl-crash-report-mac-compile:
- $(CC) $(MACOS_MIN_FLAG) -O3 -ObjC -I$(BUN_DEPS_DIR)/PLCrashReporter/include -I$(BUN_DEPS_DIR)/PLCrashReporter -c $(BUN_DEPS_DIR)/PLCrashReport.m \
- -g -o $(BUN_DEPS_OUT_DIR)/libCrashReporter.bindings.a
+libbacktrace:
+ cd $(BUN_DEPS_DIR)/libbacktrace && \
+ (make clean || echo "") && \
+ CFLAGS="$(CFLAGS)" CC=$(CC) ./configure --disable-shared --enable-static --with-pic && \
+ make -j$(CPUS) && \
+ cp ./.libs/libbacktrace.a $(BUN_DEPS_OUT_DIR)/libbacktrace.a
libarchive:
cd $(BUN_DEPS_DIR)/libarchive; \
(make clean || echo ""); \
(./build/clean.sh || echo ""); \
./build/autogen.sh; \
- CFLAGS=$(CFLAGS) CC=$(CC) ./configure --disable-shared --enable-static --with-pic --disable-bsdtar --disable-bsdcat --disable-rpath --enable-posix-regex-lib --without-xml2 --without-expat --without-openssl --without-iconv --without-zlib; \
+ CFLAGS="$(CFLAGS)" CC=$(CC) ./configure --disable-shared --enable-static --with-pic --disable-bsdtar --disable-bsdcat --disable-rpath --enable-posix-regex-lib --without-xml2 --without-expat --without-openssl --without-iconv --without-zlib; \
make -j${CPUS}; \
cp ./.libs/libarchive.a $(BUN_DEPS_OUT_DIR)/libarchive.a;
@@ -317,7 +331,7 @@ tgz-debug:
vendor: require init-submodules vendor-without-check
zlib:
- cd $(BUN_DEPS_DIR)/zlib; cmake $(CMAKE_FLAGS) .; make CFLAGS=$(CFLAGS);
+ cd $(BUN_DEPS_DIR)/zlib; CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) .; CFLAGS="$(CFLAGS)" make;
cp $(BUN_DEPS_DIR)/zlib/libz.a $(BUN_DEPS_OUT_DIR)/libz.a
docker-login:
@@ -362,7 +376,7 @@ sign-macos-aarch64:
cls:
@echo "\n\n---\n\n"
-release: all-js jsc-bindings-mac build-obj cls bun-link-lld-release release-bin-entitlements
+release: all-js jsc-bindings-mac build-obj cls bun-link-lld-release bun-link-lld-release-dsym release-bin-entitlements
jsc-check:
@ls $(JSC_BASE_DIR) >/dev/null 2>&1 || (echo "Failed to access WebKit build. Please compile the WebKit submodule using the Dockerfile at $(shell pwd)/src/javascript/WebKit/Dockerfile and then copy from /output in the Docker container to $(JSC_BASE_DIR). You can override the directory via JSC_BASE_DIR. \n\n DOCKER_BUILDKIT=1 docker build -t bun-webkit $(shell pwd)/src/javascript/jsc/WebKit -f $(shell pwd)/src/javascript/jsc/WebKit/Dockerfile --progress=plain\n\n docker container create bun-webkit\n\n # Get the container ID\n docker container ls\n\n docker cp DOCKER_CONTAINER_ID_YOU_JUST_FOUND:/output $(JSC_BASE_DIR)" && exit 1)
@@ -645,9 +659,30 @@ jsc-force-fastjit:
$(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/jit/ExecutableAllocator.h
$(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/assembler/FastJITPermissions.h
$(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/jit/ExecutableAllocator.cpp
+ $(SED) -i "s/GIGACAGE_ENABLED/0/g" $(WEBKIT_DIR)/Source/JavaScriptCore/Gigacage.h
jsc-build-mac-compile:
- cd $(WEBKIT_DIR) && ICU_INCLUDE_DIRS="$(HOMEBREW_PREFIX)opt/icu4c/include" ./Tools/Scripts/build-jsc --jsc-only --cmakeargs="-DENABLE_STATIC_JSC=ON -DCMAKE_BUILD_TYPE=relwithdebinfo -DPTHREAD_JIT_PERMISSIONS_API=1 -DUSE_PTHREAD_JIT_PERMISSIONS_API=ON $(CMAKE_FLAGS_WITHOUT_RELEASE)"
+ mkdir -p $(WEBKIT_RELEASE_DIR) $(WEBKIT_DIR);
+ cd $(WEBKIT_RELEASE_DIR) && \
+ ICU_INCLUDE_DIRS="$(HOMEBREW_PREFIX)opt/icu4c/include" \
+ CMAKE_BUILD_TYPE=Release cmake \
+ -DPORT="JSCOnly" \
+ -DENABLE_STATIC_JSC=ON \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DUSE_THIN_ARCHIVES=OFF \
+ -DENABLE_FTL_JIT=ON \
+ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
+ -G Ninja \
+ -DCMAKE_BUILD_TYPE=Release \
+ $(CMAKE_FLAGS_WITHOUT_RELEASE) \
+ -DPTHREAD_JIT_PERMISSIONS_API=1 \
+ -DUSE_PTHREAD_JIT_PERMISSIONS_API=ON \
+ -DCMAKE_BUILD_TYPE=Release \
+ $(WEBKIT_DIR) \
+ $(WEBKIT_RELEASE_DIR) && \
+ CFLAGS="$CFLAGS -ffat-lto-objects" CXXFLAGS="$CXXFLAGS -ffat-lto-objects" \
+ cmake --build $(WEBKIT_RELEASE_DIR) --config Release --target jsc
+
jsc-build-linux-compile-config:
mkdir -p $(WEBKIT_RELEASE_DIR)
cd $(WEBKIT_RELEASE_DIR) && \
@@ -698,7 +733,7 @@ jsc-bindings-mac: $(OBJ_FILES)
# mimalloc is built as object files so that it can overload the system malloc
mimalloc:
- cd $(BUN_DEPS_DIR)/mimalloc; cmake $(CMAKE_FLAGS) -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; make;
+ cd $(BUN_DEPS_DIR)/mimalloc; CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) -DMI_SKIP_COLLECT_ON_EXIT=ON -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; make;
cp $(BUN_DEPS_DIR)/mimalloc/$(MIMALLOC_INPUT_PATH) $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE)
bun-link-lld-debug:
@@ -712,7 +747,7 @@ bun-link-lld-debug:
bun-relink-copy:
cp /tmp/bun-$(PACKAGE_JSON_VERSION).o $(BUN_RELEASE_BIN).o
-bun-relink: bun-relink-copy bun-link-lld-release
+
bun-link-lld-release:
$(CXX) $(BUN_LLD_FLAGS) \
@@ -724,24 +759,40 @@ bun-link-lld-release:
-O3
rm -rf $(BUN_RELEASE_BIN).dSYM
cp $(BUN_RELEASE_BIN) $(BUN_RELEASE_BIN)-profile
- $(DSYMUTIL) --flat $(BUN_RELEASE_BIN) -o $(BUN_RELEASE_BIN).dSYM
+
+ifeq ($(OS_NAME),darwin)
+bun-link-lld-release-dsym:
+ $(DSYMUTIL) -o $(BUN_RELEASE_BIN).dSYM $(BUN_RELEASE_BIN)
-$(STRIP) $(BUN_RELEASE_BIN)
mv $(BUN_RELEASE_BIN).o /tmp/bun-$(PACKAGE_JSON_VERSION).o
+endif
+
+ifeq ($(OS_NAME),linux)
+bun-link-lld-release-dsym:
+ -$(STRIP) $(BUN_RELEASE_BIN)
+ mv $(BUN_RELEASE_BIN).o /tmp/bun-$(PACKAGE_JSON_VERSION).o
+endif
+
+
+bun-relink: bun-relink-copy bun-link-lld-release bun-link-lld-release-dsym
+
+
# We do this outside of build.zig for performance reasons
# The C compilation stuff with build.zig is really slow and we don't need to run this as often as the rest
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CXX) -c -o $@ $< \
$(CLANG_FLAGS) $(PLATFORM_LINKER_FLAGS) \
- -O3 \
- -w
+ -O1 \
+ -fvectorize \
+ -w -g
sizegen:
$(CXX) src/javascript/jsc/headergen/sizegen.cpp -o $(BUN_TMP_DIR)/sizegen $(CLANG_FLAGS) -O1
$(BUN_TMP_DIR)/sizegen > src/javascript/jsc/bindings/sizes.zig
picohttp:
- $(CC) $(MARCH_NATIVE) $(MACOS_MIN_FLAG) -O3 -g -fPIE -c $(BUN_DEPS_DIR)/picohttpparser/picohttpparser.c -I$(BUN_DEPS_DIR) -o $(BUN_DEPS_OUT_DIR)/picohttpparser.o; cd ../../
+ $(CC) $(CFLAGS) -O3 -g -fPIC -c $(BUN_DEPS_DIR)/picohttpparser/picohttpparser.c -I$(BUN_DEPS_DIR) -o $(BUN_DEPS_OUT_DIR)/picohttpparser.o; cd ../../
analytics:
./node_modules/.bin/peechy --schema src/analytics/schema.peechy --zig src/analytics/analytics_schema.zig
diff --git a/bench/snippets/callbacks-overhead.mjs b/bench/snippets/callbacks-overhead.mjs
new file mode 100644
index 0000000000..65171145c4
--- /dev/null
+++ b/bench/snippets/callbacks-overhead.mjs
@@ -0,0 +1,78 @@
+const iterations = 1_000;
+
+export var report = {
+ async: 0,
+ callback: 0,
+ sync: 0,
+ then: 0,
+};
+
+const tests = {
+ callback(n, cb) {
+ if (n === iterations) return cb();
+ tests.callback(1 + n, () => cb());
+ },
+
+ sync(n) {
+ if (n === iterations) return;
+
+ tests.sync(1 + n);
+ },
+
+ async async(n) {
+ if (n === iterations) return;
+
+ await tests.async(1 + n);
+ },
+
+ then(n) {
+ if (n === iterations) return;
+ return Promise.resolve(1 + n).then(tests.then);
+ },
+};
+
+async function test(log) {
+ {
+ const a = performance.now();
+ await tests.async(0);
+ if (log)
+ console.log(
+ `async/await: ${(report.async = (performance.now() - a).toFixed(4))}ms`
+ );
+ }
+
+ {
+ const a = performance.now();
+ tests.callback(0, function () {
+ if (log)
+ console.log(
+ `callback: ${(report.callback = (performance.now() - a).toFixed(
+ 4
+ ))}ms`
+ );
+ });
+ }
+
+ {
+ const a = performance.now();
+ await tests.then(0);
+ if (log)
+ console.log(
+ `then: ${(report.then = (performance.now() - a).toFixed(4))}ms`
+ );
+ }
+
+ {
+ const a = performance.now();
+ tests.sync(0);
+ if (log)
+ console.log(
+ `sync: ${(report.sync = (performance.now() - a).toFixed(4))}ms`
+ );
+ }
+}
+
+let warmup = 10;
+while (warmup--) await test();
+
+await test(true);
diff --git a/bench/snippets/exists.js b/bench/snippets/exists.js
new file mode 100644
index 0000000000..1d1d6cfe0c
--- /dev/null
+++ b/bench/snippets/exists.js
@@ -0,0 +1,6 @@
+const { existsSync } = require("fs");
+const cwd = process.cwd();
+
+const count = parseInt(process.env.ITERATIONS || "1", 10) || 1;
+
+for (let i = 0; i < count; i++) existsSync(cwd);
diff --git a/build-id b/build-id
index 3fdcd7c44c..38b10c1b2b 100644
--- a/build-id
+++ b/build-id
@@ -1 +1 @@
-67
+68
diff --git a/build.zig b/build.zig
index 7bb6a7b2f3..3aabb02bda 100644
--- a/build.zig
+++ b/build.zig
@@ -51,14 +51,9 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar
.path = pkgPath("src/thread_pool.zig"),
};
- var crash_reporter_mac: std.build.Pkg = .{
+ var crash_reporter: std.build.Pkg = .{
.name = "crash_reporter",
- .path = pkgPath("src/deps/PLCrashReport.zig"),
- };
-
- var crash_reporter_linux: std.build.Pkg = .{
- .name = "crash_reporter",
- .path = pkgPath("src/deps/crash_reporter_linux.zig"),
+ .path = pkgPath("src/deps/backtrace.zig"),
};
var picohttp: std.build.Pkg = .{
@@ -80,11 +75,6 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar
else
io_linux;
- var crash_reporter = if (target.isDarwin())
- crash_reporter_mac
- else
- crash_reporter_linux;
-
var strings: std.build.Pkg = .{
.name = "strings",
.path = pkgPath("src/string_immutable.zig"),
@@ -104,7 +94,7 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar
.name = "javascript_core",
.path = pkgPath("src/jsc.zig"),
};
- javascript_core.dependencies = &.{ http, strings, picohttp };
+ javascript_core.dependencies = &.{ http, strings, picohttp, io };
http.dependencies = &.{
strings,
picohttp,
@@ -283,6 +273,7 @@ pub fn build(b: *std.build.Builder) !void {
obj.strip = false;
obj.bundle_compiler_rt = true;
+ obj.omit_frame_pointer = false;
b.default_step.dependOn(&obj.step);
@@ -292,6 +283,7 @@ pub fn build(b: *std.build.Builder) !void {
obj.link_eh_frame_hdr = true;
obj.link_function_sections = true;
}
+
var log_step = b.addLog("Destination: {s}/{s}\n", .{ output_dir, bun_executable_name });
log_step.step.dependOn(&obj.step);
}
@@ -422,8 +414,7 @@ pub fn linkObjectFiles(b: *std.build.Builder, obj: *std.build.LibExeObjStep, tar
.{ "libJavaScriptCore.a", "libJavaScriptCore.a" },
.{ "libWTF.a", "libWTF.a" },
.{ "libbmalloc.a", "libbmalloc.a" },
- .{ "libCrashReporter.a", "libCrashReporter.a" },
- .{ "libCrashReporter.bindings.a", "libCrashReporter.bindings.a" },
+ .{ "libbacktrace.a", "libbacktrace.a" },
});
for (dirs_to_search.slice()) |deps_path| {
diff --git a/fs-test/writeFileSync.txt b/fs-test/writeFileSync.txt
new file mode 100644
index 0000000000..b1759f75ad
--- /dev/null
+++ b/fs-test/writeFileSync.txt
@@ -0,0 +1 @@
+utf8
\ No newline at end of file
diff --git a/integration/bunjs-only-snippets/console-log.js b/integration/bunjs-only-snippets/console-log.js
new file mode 100644
index 0000000000..e8aa200acb
--- /dev/null
+++ b/integration/bunjs-only-snippets/console-log.js
@@ -0,0 +1,58 @@
+console.log("Hello World!");
+console.log(123);
+console.log(-123);
+console.log(123.567);
+console.log(-123.567);
+console.log(true);
+console.log(false);
+console.log(null);
+console.log(undefined);
+console.log(Symbol("Symbol Description"));
+console.log(new Date(2021, 12, 30, 666, 777, 888, 999));
+console.log([123, 456, 789]);
+console.log({ a: 123, b: 456, c: 789 });
+console.log({
+ a: {
+ b: {
+ c: 123,
+ },
+ bacon: true,
+ },
+});
+
+console.log(new Promise(() => {}));
+
+class Foo {}
+
+console.log(() => {});
+console.log(Foo);
+console.log(new Foo());
+console.log(function foooo() {});
+
+console.log(/FooRegex/);
+
+console.error("uh oh");
+console.time("Check");
+
+console.log(
+ "Is it a bug or a feature that formatting numbers like %d is colored",
+ 123
+);
+console.log(globalThis);
+
+console.log(
+ "String %s should be 2nd word, 456 == %s and percent s %s == %s",
+ "123",
+ "456",
+ "%s",
+ "What",
+ "okay"
+);
+
+const infinteLoop = {
+ foo: {},
+ bar: {},
+};
+
+infinteLoop.bar = infinteLoop;
+console.log(infinteLoop, "am");
diff --git a/integration/bunjs-only-snippets/fetch.js b/integration/bunjs-only-snippets/fetch.js
new file mode 100644
index 0000000000..cc83b5af43
--- /dev/null
+++ b/integration/bunjs-only-snippets/fetch.js
@@ -0,0 +1,14 @@
+import fs from "fs";
+
+const response = await fetch("http://example.com/");
+const text = await response.text();
+
+if (
+ fs.readFileSync(
+ import.meta.path.substring(0, import.meta.path.lastIndexOf("/")) +
+ "/fetch.js.txt",
+ "utf8"
+ ) !== text
+) {
+ throw new Error("Expected fetch.js.txt to match snapshot");
+}
diff --git a/integration/bunjs-only-snippets/fetch.js.txt b/integration/bunjs-only-snippets/fetch.js.txt
new file mode 100644
index 0000000000..5a9b52fcf1
--- /dev/null
+++ b/integration/bunjs-only-snippets/fetch.js.txt
@@ -0,0 +1,46 @@
+
+
+
+ Example Domain
+
+
+
+
+
+
+
+
+
+
Example Domain
+
This domain is for use in illustrative examples in documents. You may use this
+ domain in literature without prior coordination or asking for permission.
+
More information...
+
+
+
diff --git a/integration/bunjs-only-snippets/fs-stream.js b/integration/bunjs-only-snippets/fs-stream.js
new file mode 100644
index 0000000000..4b71c95b77
--- /dev/null
+++ b/integration/bunjs-only-snippets/fs-stream.js
@@ -0,0 +1,23 @@
+import { createReadStream, createWriteStream, readFileSync } from "fs";
+
+await new Promise((resolve, reject) => {
+ createReadStream("fs-stream.js")
+ .pipe(createWriteStream("/tmp/fs-stream.copy.js"))
+ .once("error", (err) => reject(err))
+ .once("finish", () => {
+ try {
+ const copied = readFileSync("/tmp/fs-stream.copy.js", "utf8");
+ const real = readFileSync("/tmp/fs-stream.js", "utf8");
+ if (copied !== real) {
+ reject(
+ new Error("fs-stream.js is not the same as fs-stream.copy.js")
+ );
+ return;
+ }
+
+ resolve(true);
+ } catch (err) {
+ reject(err);
+ }
+ });
+});
diff --git a/integration/bunjs-only-snippets/fs.test.js b/integration/bunjs-only-snippets/fs.test.js
new file mode 100644
index 0000000000..4fc5c9e91e
--- /dev/null
+++ b/integration/bunjs-only-snippets/fs.test.js
@@ -0,0 +1,35 @@
+import { describe, it, expect } from "bun:test";
+import {
+ mkdirSync,
+ existsSync,
+ readFileSync,
+ mkdtempSync,
+ writeFileSync,
+} from "node:fs";
+
+const tmp = mkdtempSync("fs-test");
+
+describe("mkdirSync", () => {
+ it("should create a directory", () => {
+ const tempdir = `${tmp}/1234/hi`;
+ expect(existsSync(tempdir)).toBe(false);
+ expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe(
+ true
+ );
+ expect(existsSync(tempdir)).toBe(true);
+ });
+});
+
+describe("readFileSync", () => {
+ it("works", () => {
+ const text = readFileSync(import.meta.dir + "/readFileSync.txt", "utf8");
+ expect(text).toBe("File read successfully");
+ });
+});
+
+describe("writeFileSync", () => {
+ it("works", () => {
+ const text = writeFileSync(`${tmp}/writeFileSync.txt`, "utf8");
+ expect(text).toBe("File read successfully");
+ });
+});
diff --git a/integration/bunjs-only-snippets/import-meta.test.js b/integration/bunjs-only-snippets/import-meta.test.js
new file mode 100644
index 0000000000..226dd396b4
--- /dev/null
+++ b/integration/bunjs-only-snippets/import-meta.test.js
@@ -0,0 +1,13 @@
+import { it, expect } from "bun:test";
+
+const { path, dir } = import.meta;
+
+it("import.meta.dir", () => {
+ expect(dir.endsWith("/bun/integration/bunjs-only-snippets")).toBe(true);
+});
+
+it("import.meta.path", () => {
+ expect(
+ path.endsWith("/bun/integration/bunjs-only-snippets/import-meta.test.js")
+ ).toBe(true);
+});
diff --git a/integration/bunjs-only-snippets/microtask.js b/integration/bunjs-only-snippets/microtask.js
new file mode 100644
index 0000000000..c5acfd5787
--- /dev/null
+++ b/integration/bunjs-only-snippets/microtask.js
@@ -0,0 +1,76 @@
+// You can verify this test is correct by copy pasting this into a browser's console and checking it doesn't throw an error.
+var run = 0;
+
+await new Promise((resolve, reject) => {
+ queueMicrotask(() => {
+ if (run++ != 0) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 3) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ });
+ });
+ queueMicrotask(() => {
+ if (run++ != 1) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 4) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+
+ queueMicrotask(() => {
+ if (run++ != 6) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ });
+ });
+ });
+ queueMicrotask(() => {
+ if (run++ != 2) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 5) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+
+ queueMicrotask(() => {
+ if (run++ != 7) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ resolve(true);
+ });
+ });
+ });
+});
+
+{
+ var passed = false;
+ try {
+ queueMicrotask(1234);
+ } catch (exception) {
+ passed = exception instanceof TypeError;
+ }
+
+ if (!passed)
+ throw new Error(
+ "queueMicrotask should throw a TypeError if the argument is not a function"
+ );
+}
+
+{
+ var passed = false;
+ try {
+ queueMicrotask();
+ } catch (exception) {
+ passed = exception instanceof TypeError;
+ }
+
+ if (!passed)
+ throw new Error(
+ "queueMicrotask should throw a TypeError if the argument is empty"
+ );
+}
diff --git a/integration/bunjs-only-snippets/process-nexttick.js b/integration/bunjs-only-snippets/process-nexttick.js
new file mode 100644
index 0000000000..337977c0a7
--- /dev/null
+++ b/integration/bunjs-only-snippets/process-nexttick.js
@@ -0,0 +1,91 @@
+// You can verify this test is correct by copy pasting this into a browser's console and checking it doesn't throw an error.
+var run = 0;
+
+var queueMicrotask = process.nextTick;
+
+await new Promise((resolve, reject) => {
+ queueMicrotask(() => {
+ if (run++ != 0) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 3) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ });
+ });
+ queueMicrotask(() => {
+ if (run++ != 1) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 4) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+
+ queueMicrotask(() => {
+ if (run++ != 6) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ });
+ });
+ });
+ queueMicrotask(() => {
+ if (run++ != 2) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ queueMicrotask(() => {
+ if (run++ != 5) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+
+ queueMicrotask(() => {
+ if (run++ != 7) {
+ reject(new Error("Microtask execution order is wrong: " + run));
+ }
+ resolve(true);
+ });
+ });
+ });
+});
+
+{
+ var passed = false;
+ try {
+ queueMicrotask(1234);
+ } catch (exception) {
+ passed = exception instanceof TypeError;
+ }
+
+ if (!passed)
+ throw new Error(
+ "queueMicrotask should throw a TypeError if the argument is not a function"
+ );
+}
+
+{
+ var passed = false;
+ try {
+ queueMicrotask();
+ } catch (exception) {
+ passed = exception instanceof TypeError;
+ }
+
+ if (!passed)
+ throw new Error(
+ "queueMicrotask should throw a TypeError if the argument is empty"
+ );
+}
+
+await new Promise((resolve, reject) => {
+ process.nextTick(
+ (first, second) => {
+ console.log(first, second);
+ if (first !== 12345 || second !== "hello")
+ reject(new Error("process.nextTick called with wrong arguments"));
+ resolve(true);
+ },
+ 12345,
+ "hello"
+ );
+});
diff --git a/integration/bunjs-only-snippets/process.js b/integration/bunjs-only-snippets/process.js
new file mode 100644
index 0000000000..486d20f46b
--- /dev/null
+++ b/integration/bunjs-only-snippets/process.js
@@ -0,0 +1,48 @@
+// this property isn't implemented yet but it should at least return a string
+const isNode = !process.isBun;
+
+if (!isNode && process.title !== "bun")
+ throw new Error("process.title is not 'bun'");
+
+if (typeof process.env.USER !== "string")
+ throw new Error("process.env is not an object");
+
+if (process.env.USER.length === 0)
+ throw new Error("process.env is missing a USER property");
+
+if (process.platform !== "darwin" && process.platform !== "linux")
+ throw new Error("process.platform is invalid");
+
+if (isNode) throw new Error("process.isBun is invalid");
+
+// partially to test it doesn't crash due to various strange types
+process.env.BACON = "yummy";
+if (process.env.BACON !== "yummy") {
+ throw new Error("process.env is not writable");
+}
+
+delete process.env.BACON;
+if (typeof process.env.BACON !== "undefined") {
+ throw new Error("process.env is not deletable");
+}
+
+process.env.BACON = "yummy";
+if (process.env.BACON !== "yummy") {
+ throw new Error("process.env is not re-writable");
+}
+
+if (JSON.parse(JSON.stringify(process.env)).BACON !== "yummy") {
+ throw new Error("process.env is not serializable");
+}
+
+if (typeof JSON.parse(JSON.stringify(process.env)).toJSON !== "undefined") {
+ throw new Error("process.env should call toJSON to hide its internal state");
+}
+
+var { env, ...proces } = process;
+console.log(JSON.stringify(proces, null, 2));
+console.log(proces);
+
+console.log("CWD", process.cwd());
+console.log("SET CWD", process.chdir("../"));
+console.log("CWD", process.cwd());
diff --git a/integration/bunjs-only-snippets/readFileSync.txt b/integration/bunjs-only-snippets/readFileSync.txt
new file mode 100644
index 0000000000..ddc94b988e
--- /dev/null
+++ b/integration/bunjs-only-snippets/readFileSync.txt
@@ -0,0 +1 @@
+File read successfully
\ No newline at end of file
diff --git a/integration/bunjs-only-snippets/readdir.js b/integration/bunjs-only-snippets/readdir.js
new file mode 100644
index 0000000000..18c111d0a0
--- /dev/null
+++ b/integration/bunjs-only-snippets/readdir.js
@@ -0,0 +1,9 @@
+const { readdirSync } = require("fs");
+
+const count = parseInt(process.env.ITERATIONS || "1", 10) || 1;
+
+for (let i = 0; i < count; i++) {
+ readdirSync(".");
+}
+
+console.log(readdirSync("."));
diff --git a/integration/bunjs-only-snippets/sleep.js b/integration/bunjs-only-snippets/sleep.js
index 9a62201c54..080597424c 100644
--- a/integration/bunjs-only-snippets/sleep.js
+++ b/integration/bunjs-only-snippets/sleep.js
@@ -1,7 +1,7 @@
-const interval = 0.5;
+const interval = 0.01;
const now = performance.now();
console.time("Slept");
-Bun.sleep(interval);
+Bun.sleepSync(interval);
const elapsed = performance.now() - now;
if (elapsed < interval) {
throw new Error("Didn't sleep");
diff --git a/integration/bunjs-only-snippets/some-fs.js b/integration/bunjs-only-snippets/some-fs.js
new file mode 100644
index 0000000000..e6b31f1620
--- /dev/null
+++ b/integration/bunjs-only-snippets/some-fs.js
@@ -0,0 +1,51 @@
+const { mkdirSync, existsSync } = require("fs");
+
+var performance = globalThis.performance;
+if (!performance) {
+ try {
+ performance = require("perf_hooks").performance;
+ } catch (e) {}
+}
+
+const count = parseInt(process.env.ITERATIONS || "1", 10) || 1;
+var tempdir = `/tmp/some-fs-test/dir/${Date.now()}/hi`;
+
+for (let i = 0; i < count; i++) {
+ tempdir += `/${i.toString(36)}`;
+}
+
+if (existsSync(tempdir)) {
+ throw new Error(
+ `existsSync reports ${tempdir} exists, but it probably does not`
+ );
+}
+
+var origTempDir = tempdir;
+var iterations = new Array(count * count).fill("");
+var total = 0;
+for (let i = 0; i < count; i++) {
+ for (let j = 0; j < count; j++) {
+ iterations[total++] = `${origTempDir}/${j.toString(36)}-${i.toString(36)}`;
+ }
+}
+tempdir = origTempDir;
+mkdirSync(origTempDir, { recursive: true });
+const recurse = { recursive: false };
+const start = performance.now();
+for (let i = 0; i < total; i++) {
+ mkdirSync(iterations[i], recurse);
+}
+
+console.log("MKDIR " + total + " depth took:", performance.now() - start, "ms");
+
+if (!existsSync(tempdir)) {
+ throw new Error(
+ "Expected directory to exist after mkdirSync, but it doesn't"
+ );
+}
+
+if (mkdirSync(tempdir, { recursive: true })) {
+ throw new Error(
+ "mkdirSync shouldn't return directory name on existing directories"
+ );
+}
diff --git a/integration/scripts/bun.js b/integration/scripts/bun.js
index d227857877..f8e4d2fa02 100644
--- a/integration/scripts/bun.js
+++ b/integration/scripts/bun.js
@@ -1,84 +1,85 @@
-import snippets from "./snippets.json";
+const fail = true;
+// import snippets from "./snippets.json";
-globalThis.console.assert = (condition, ...content) => {
- if (!condition) {
- throw new Error(content.join(" "));
- }
-};
-globalThis.getModuleScriptSrc = async (name) => {
- const response = await fetch(name, {
- cache: "force-cache",
- });
+// globalThis.console.assert = (condition, ...content) => {
+// if (!condition) {
+// throw new Error(content.join(" "));
+// }
+// };
+// globalThis.getModuleScriptSrc = async (name) => {
+// const response = await fetch(name, {
+// cache: "force-cache",
+// });
- if (response.ok) {
- return await response.text();
- } else {
- throw new Error(`Failed to get module script ${name}`);
- }
-};
+// if (response.ok) {
+// return await response.text();
+// } else {
+// throw new Error(`Failed to get module script ${name}`);
+// }
+// };
-globalThis.runTest = async (name) => {
- testSuccess = false;
- var Namespace = await import(name);
- var testFunction = Namespace.test;
+// globalThis.runTest = async (name) => {
+// testSuccess = false;
+// var Namespace = await import(name);
+// var testFunction = Namespace.test;
- if (
- !("test" in Namespace) &&
- "default" in Namespace &&
- typeof Namespace.default === "function"
- ) {
- Namespace = Namespace.default();
- testFunction = Namespace.test;
- }
+// if (
+// !("test" in Namespace) &&
+// "default" in Namespace &&
+// typeof Namespace.default === "function"
+// ) {
+// Namespace = Namespace.default();
+// testFunction = Namespace.test;
+// }
- if (!testFunction) {
- throw new Error("No test function found in " + name);
- }
+// if (!testFunction) {
+// throw new Error("No test function found in " + name);
+// }
- if (typeof testFunction !== "function") {
- throw new Error(
- `Expected (await import(\"${name}\"")) to have a test function.\nReceived: ${Object.keys(
- Namespace
- ).join(", ")} `
- );
- }
+// if (typeof testFunction !== "function") {
+// throw new Error(
+// `Expected (await import(\"${name}\"")) to have a test function.\nReceived: ${Object.keys(
+// Namespace
+// ).join(", ")} `
+// );
+// }
- if (globalThis.BUN_DEBUG_MODE) {
- try {
- await testFunction();
- if (!testSuccess) {
- throw new Error("Test failed");
- }
- } catch (exception) {
- console.error(exception);
- debugger;
- throw exception;
- }
- } else {
- await testFunction();
- if (!testSuccess) {
- throw new Error("Test failed");
- }
- }
-};
+// if (globalThis.BUN_DEBUG_MODE) {
+// try {
+// await testFunction();
+// if (!testSuccess) {
+// throw new Error("Test failed");
+// }
+// } catch (exception) {
+// console.error(exception);
+// debugger;
+// throw exception;
+// }
+// } else {
+// await testFunction();
+// if (!testSuccess) {
+// throw new Error("Test failed");
+// }
+// }
+// };
-var testSuccess = false;
-globalThis.testDone = () => {
- testSuccess = true;
-};
+// var testSuccess = false;
+// globalThis.testDone = () => {
+// testSuccess = true;
+// };
-let fail = 0;
-for (let snippet of snippets) {
- try {
- await runTest("../snippets/" + snippet.substring(1));
- console.log("✅", snippet);
- } catch (exception) {
- console.error(`❌ ${snippet}`);
- console.error(exception);
+// let fail = 0;
+// for (let snippet of snippets) {
+// try {
+// await runTest("../snippets/" + snippet.substring(1));
+// console.log("✅", snippet);
+// } catch (exception) {
+// console.error(`❌ ${snippet}`);
+// console.error(exception);
- fail++;
- }
-}
+// fail++;
+// }
+// }
if (fail) throw new Error(`❌ browser test failed (${fail})`);
diff --git a/integration/scripts/bun.lockb b/integration/scripts/bun.lockb
index 557f98ef6d..1af6fbf693 100755
Binary files a/integration/scripts/bun.lockb and b/integration/scripts/bun.lockb differ
diff --git a/integration/snapshots/array-args-with-default-values.hmr.debug.js b/integration/snapshots/array-args-with-default-values.hmr.debug.js
index 58e8b47bff..f55cb290ef 100644
--- a/integration/snapshots/array-args-with-default-values.hmr.debug.js
+++ b/integration/snapshots/array-args-with-default-values.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(3474597122, "array-args-with-default-values.js"), exports = hmr.exports;
diff --git a/integration/snapshots/array-args-with-default-values.hmr.js b/integration/snapshots/array-args-with-default-values.hmr.js
index aae356eedc..5c67d0c6c6 100644
--- a/integration/snapshots/array-args-with-default-values.hmr.js
+++ b/integration/snapshots/array-args-with-default-values.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(3474597122, "array-args-with-default-values.js"), exports = hmr.exports;
diff --git a/integration/snapshots/bundled-entry-point.debug.js b/integration/snapshots/bundled-entry-point.debug.js
index 04f92d63a5..0ffe267f19 100644
--- a/integration/snapshots/bundled-entry-point.debug.js
+++ b/integration/snapshots/bundled-entry-point.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var hello = null ?? "world";
diff --git a/integration/snapshots/bundled-entry-point.hmr.debug.js b/integration/snapshots/bundled-entry-point.hmr.debug.js
index fd211daa25..4b62d3dbc6 100644
--- a/integration/snapshots/bundled-entry-point.hmr.debug.js
+++ b/integration/snapshots/bundled-entry-point.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
Bun.activate(true);
diff --git a/integration/snapshots/bundled-entry-point.hmr.js b/integration/snapshots/bundled-entry-point.hmr.js
index f3008327aa..b04c384958 100644
--- a/integration/snapshots/bundled-entry-point.hmr.js
+++ b/integration/snapshots/bundled-entry-point.hmr.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
Bun.activate(false);
diff --git a/integration/snapshots/bundled-entry-point.js b/integration/snapshots/bundled-entry-point.js
index 04f92d63a5..0ffe267f19 100644
--- a/integration/snapshots/bundled-entry-point.js
+++ b/integration/snapshots/bundled-entry-point.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var hello = null ?? "world";
diff --git a/integration/snapshots/caught-require.debug.js b/integration/snapshots/caught-require.debug.js
index 690ec4db50..f4f12c29d5 100644
--- a/integration/snapshots/caught-require.debug.js
+++ b/integration/snapshots/caught-require.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
try {
require((() => { throw (new Error(`Cannot require module '"this-package-should-not-exist"'`)); } )());
diff --git a/integration/snapshots/caught-require.hmr.debug.js b/integration/snapshots/caught-require.hmr.debug.js
index 25883fac75..2cd9f386d1 100644
--- a/integration/snapshots/caught-require.hmr.debug.js
+++ b/integration/snapshots/caught-require.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(2398506918, "caught-require.js"), exports = hmr.exports;
diff --git a/integration/snapshots/caught-require.hmr.js b/integration/snapshots/caught-require.hmr.js
index ea7bccc2ca..c57c6f90e9 100644
--- a/integration/snapshots/caught-require.hmr.js
+++ b/integration/snapshots/caught-require.hmr.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(2398506918, "caught-require.js"), exports = hmr.exports;
diff --git a/integration/snapshots/caught-require.js b/integration/snapshots/caught-require.js
index 690ec4db50..f4f12c29d5 100644
--- a/integration/snapshots/caught-require.js
+++ b/integration/snapshots/caught-require.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
try {
require((() => { throw (new Error(`Cannot require module '"this-package-should-not-exist"'`)); } )());
diff --git a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js
index 2ca15542e3..c5aa627299 100644
--- a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js
+++ b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import _login from "http://localhost:8080/_login.js";
import _auth from "http://localhost:8080/_auth.js";
import * as _loginReally from "http://localhost:8080/_login.js";
diff --git a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js
index ef0bd004eb..82d8617f00 100644
--- a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js
+++ b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import _login from "http://localhost:8080/_login.js";
import _auth from "http://localhost:8080/_auth.js";
import * as _loginReally from "http://localhost:8080/_login.js";
diff --git a/integration/snapshots/code-simplification-neql-define.hmr.debug.js b/integration/snapshots/code-simplification-neql-define.hmr.debug.js
index 80aedf8bb1..860c514ba3 100644
--- a/integration/snapshots/code-simplification-neql-define.hmr.debug.js
+++ b/integration/snapshots/code-simplification-neql-define.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(726376257, "code-simplification-neql-define.js"), exports = hmr.exports;
diff --git a/integration/snapshots/code-simplification-neql-define.hmr.js b/integration/snapshots/code-simplification-neql-define.hmr.js
index 1e517c5331..9fdd73d14a 100644
--- a/integration/snapshots/code-simplification-neql-define.hmr.js
+++ b/integration/snapshots/code-simplification-neql-define.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(726376257, "code-simplification-neql-define.js"), exports = hmr.exports;
diff --git a/integration/snapshots/custom-emotion-jsx/file.debug.jsx b/integration/snapshots/custom-emotion-jsx/file.debug.jsx
index b6be3371ff..97987ff3fc 100644
--- a/integration/snapshots/custom-emotion-jsx/file.debug.jsx
+++ b/integration/snapshots/custom-emotion-jsx/file.debug.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx b/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx
index c595a59576..bd299b2a8e 100644
--- a/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx
+++ b/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/custom-emotion-jsx/file.hmr.jsx b/integration/snapshots/custom-emotion-jsx/file.hmr.jsx
index da190ef0dd..ffc4f8c966 100644
--- a/integration/snapshots/custom-emotion-jsx/file.hmr.jsx
+++ b/integration/snapshots/custom-emotion-jsx/file.hmr.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/custom-emotion-jsx/file.jsx b/integration/snapshots/custom-emotion-jsx/file.jsx
index b6be3371ff..97987ff3fc 100644
--- a/integration/snapshots/custom-emotion-jsx/file.jsx
+++ b/integration/snapshots/custom-emotion-jsx/file.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/export.hmr.debug.js b/integration/snapshots/export.hmr.debug.js
index b5d3e0ad15..ed800afa11 100644
--- a/integration/snapshots/export.hmr.debug.js
+++ b/integration/snapshots/export.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import what from "http://localhost:8080/_auth.js";
import * as where from "http://localhost:8080/_auth.js";
Bun.activate(true);
diff --git a/integration/snapshots/export.hmr.js b/integration/snapshots/export.hmr.js
index 6088ffd774..a7d1f9b313 100644
--- a/integration/snapshots/export.hmr.js
+++ b/integration/snapshots/export.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import what from "http://localhost:8080/_auth.js";
import * as where from "http://localhost:8080/_auth.js";
Bun.activate(false);
diff --git a/integration/snapshots/forbid-in-is-correct.hmr.debug.js b/integration/snapshots/forbid-in-is-correct.hmr.debug.js
index 7014ea1e8e..e38cadb7f2 100644
--- a/integration/snapshots/forbid-in-is-correct.hmr.debug.js
+++ b/integration/snapshots/forbid-in-is-correct.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(346837007, "forbid-in-is-correct.js"), exports = hmr.exports;
diff --git a/integration/snapshots/forbid-in-is-correct.hmr.js b/integration/snapshots/forbid-in-is-correct.hmr.js
index bd20b7b424..e442630954 100644
--- a/integration/snapshots/forbid-in-is-correct.hmr.js
+++ b/integration/snapshots/forbid-in-is-correct.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(346837007, "forbid-in-is-correct.js"), exports = hmr.exports;
diff --git a/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js b/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js
index dace8fa7ac..c2a6edc5f7 100644
--- a/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js
+++ b/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(713665787, "global-is-remapped-to-globalThis.js"), exports = hmr.exports;
diff --git a/integration/snapshots/global-is-remapped-to-globalThis.hmr.js b/integration/snapshots/global-is-remapped-to-globalThis.hmr.js
index a5a3723a6c..d1dd77003c 100644
--- a/integration/snapshots/global-is-remapped-to-globalThis.hmr.js
+++ b/integration/snapshots/global-is-remapped-to-globalThis.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(713665787, "global-is-remapped-to-globalThis.js"), exports = hmr.exports;
diff --git a/integration/snapshots/jsx-entities.debug.jsx b/integration/snapshots/jsx-entities.debug.jsx
index cfaf14c106..63128a105c 100644
--- a/integration/snapshots/jsx-entities.debug.jsx
+++ b/integration/snapshots/jsx-entities.debug.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/jsx-entities.hmr.debug.jsx b/integration/snapshots/jsx-entities.hmr.debug.jsx
index 73f00bdef0..5427483d32 100644
--- a/integration/snapshots/jsx-entities.hmr.debug.jsx
+++ b/integration/snapshots/jsx-entities.hmr.debug.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/jsx-entities.hmr.jsx b/integration/snapshots/jsx-entities.hmr.jsx
index 2ec3158d6d..fee5ba0f3a 100644
--- a/integration/snapshots/jsx-entities.hmr.jsx
+++ b/integration/snapshots/jsx-entities.hmr.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/jsx-entities.jsx b/integration/snapshots/jsx-entities.jsx
index cfaf14c106..63128a105c 100644
--- a/integration/snapshots/jsx-entities.jsx
+++ b/integration/snapshots/jsx-entities.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/jsx-spacing.debug.jsx b/integration/snapshots/jsx-spacing.debug.jsx
index 0b19147222..29c8995d32 100644
--- a/integration/snapshots/jsx-spacing.debug.jsx
+++ b/integration/snapshots/jsx-spacing.debug.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/jsx-spacing.hmr.debug.jsx b/integration/snapshots/jsx-spacing.hmr.debug.jsx
index 8d45ec417e..462469ba55 100644
--- a/integration/snapshots/jsx-spacing.hmr.debug.jsx
+++ b/integration/snapshots/jsx-spacing.hmr.debug.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/jsx-spacing.hmr.jsx b/integration/snapshots/jsx-spacing.hmr.jsx
index d41bc53c79..a17970a7df 100644
--- a/integration/snapshots/jsx-spacing.hmr.jsx
+++ b/integration/snapshots/jsx-spacing.hmr.jsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/jsx-spacing.jsx b/integration/snapshots/jsx-spacing.jsx
index 0b19147222..29c8995d32 100644
--- a/integration/snapshots/jsx-spacing.jsx
+++ b/integration/snapshots/jsx-spacing.jsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js b/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js
index f0e79c4882..db7f60ee3e 100644
--- a/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js
+++ b/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(1430071586, "latin1-chars-in-regexp.js"), exports = hmr.exports;
diff --git a/integration/snapshots/latin1-chars-in-regexp.hmr.js b/integration/snapshots/latin1-chars-in-regexp.hmr.js
index 03b9344e43..db6eec375f 100644
--- a/integration/snapshots/latin1-chars-in-regexp.hmr.js
+++ b/integration/snapshots/latin1-chars-in-regexp.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(1430071586, "latin1-chars-in-regexp.js"), exports = hmr.exports;
diff --git a/integration/snapshots/lodash-regexp.debug.js b/integration/snapshots/lodash-regexp.debug.js
index 6e0e6190a7..dd6bca3627 100644
--- a/integration/snapshots/lodash-regexp.debug.js
+++ b/integration/snapshots/lodash-regexp.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js";
var { shuffle} = require($60f52dc2);
export function test() {
diff --git a/integration/snapshots/lodash-regexp.hmr.debug.js b/integration/snapshots/lodash-regexp.hmr.debug.js
index 3030e47c65..a66de30695 100644
--- a/integration/snapshots/lodash-regexp.hmr.debug.js
+++ b/integration/snapshots/lodash-regexp.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js";
var { shuffle} = require($60f52dc2);
Bun.activate(true);
diff --git a/integration/snapshots/lodash-regexp.hmr.js b/integration/snapshots/lodash-regexp.hmr.js
index cd9ca40f72..3575687048 100644
--- a/integration/snapshots/lodash-regexp.hmr.js
+++ b/integration/snapshots/lodash-regexp.hmr.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js";
var { shuffle} = require($60f52dc2);
Bun.activate(false);
diff --git a/integration/snapshots/lodash-regexp.js b/integration/snapshots/lodash-regexp.js
index 6e0e6190a7..dd6bca3627 100644
--- a/integration/snapshots/lodash-regexp.js
+++ b/integration/snapshots/lodash-regexp.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js";
var { shuffle} = require($60f52dc2);
export function test() {
diff --git a/integration/snapshots/multiple-imports.debug.js b/integration/snapshots/multiple-imports.debug.js
index a98366885f..dcf7b62312 100644
--- a/integration/snapshots/multiple-imports.debug.js
+++ b/integration/snapshots/multiple-imports.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/multiple-imports.hmr.debug.js b/integration/snapshots/multiple-imports.hmr.debug.js
index 3c40e88a6e..78cf5bd0e1 100644
--- a/integration/snapshots/multiple-imports.hmr.debug.js
+++ b/integration/snapshots/multiple-imports.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/multiple-imports.hmr.js b/integration/snapshots/multiple-imports.hmr.js
index 03cfe9d1ab..4f57d33b86 100644
--- a/integration/snapshots/multiple-imports.hmr.js
+++ b/integration/snapshots/multiple-imports.hmr.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/multiple-imports.js b/integration/snapshots/multiple-imports.js
index a98366885f..dcf7b62312 100644
--- a/integration/snapshots/multiple-imports.js
+++ b/integration/snapshots/multiple-imports.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/number-literal-bug.hmr.debug.js b/integration/snapshots/number-literal-bug.hmr.debug.js
index e9d9f7b066..96e0dc96cc 100644
--- a/integration/snapshots/number-literal-bug.hmr.debug.js
+++ b/integration/snapshots/number-literal-bug.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(583570002, "number-literal-bug.js"), exports = hmr.exports;
diff --git a/integration/snapshots/number-literal-bug.hmr.js b/integration/snapshots/number-literal-bug.hmr.js
index 87cd08433a..1d128538cc 100644
--- a/integration/snapshots/number-literal-bug.hmr.js
+++ b/integration/snapshots/number-literal-bug.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(583570002, "number-literal-bug.js"), exports = hmr.exports;
diff --git a/integration/snapshots/optional-chain-with-function.hmr.debug.js b/integration/snapshots/optional-chain-with-function.hmr.debug.js
index acd6569012..f4c7a3641c 100644
--- a/integration/snapshots/optional-chain-with-function.hmr.debug.js
+++ b/integration/snapshots/optional-chain-with-function.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(3608848620, "optional-chain-with-function.js"), exports = hmr.exports;
diff --git a/integration/snapshots/optional-chain-with-function.hmr.js b/integration/snapshots/optional-chain-with-function.hmr.js
index 91666bf96f..780c8b425f 100644
--- a/integration/snapshots/optional-chain-with-function.hmr.js
+++ b/integration/snapshots/optional-chain-with-function.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(3608848620, "optional-chain-with-function.js"), exports = hmr.exports;
diff --git a/integration/snapshots/package-json-exports/index.debug.js b/integration/snapshots/package-json-exports/index.debug.js
index 882f9d489e..cfeee9a4a1 100644
--- a/integration/snapshots/package-json-exports/index.debug.js
+++ b/integration/snapshots/package-json-exports/index.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js";
var InexactRoot = require($4068f25b);
import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js";
diff --git a/integration/snapshots/package-json-exports/index.hmr.debug.js b/integration/snapshots/package-json-exports/index.hmr.debug.js
index 26be6ac7b3..8c23e74fc8 100644
--- a/integration/snapshots/package-json-exports/index.hmr.debug.js
+++ b/integration/snapshots/package-json-exports/index.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js";
var InexactRoot = require($4068f25b);
import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js";
diff --git a/integration/snapshots/package-json-exports/index.hmr.js b/integration/snapshots/package-json-exports/index.hmr.js
index d4e1aff18c..eaaad675c5 100644
--- a/integration/snapshots/package-json-exports/index.hmr.js
+++ b/integration/snapshots/package-json-exports/index.hmr.js
@@ -1,12 +1,12 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js";
var InexactRoot = require($4068f25b);
import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js";
diff --git a/integration/snapshots/package-json-exports/index.js b/integration/snapshots/package-json-exports/index.js
index 882f9d489e..cfeee9a4a1 100644
--- a/integration/snapshots/package-json-exports/index.js
+++ b/integration/snapshots/package-json-exports/index.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js";
var InexactRoot = require($4068f25b);
import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js";
diff --git a/integration/snapshots/react-context-value-func.debug.tsx b/integration/snapshots/react-context-value-func.debug.tsx
index 5d151afba6..6ce4b09dbe 100644
--- a/integration/snapshots/react-context-value-func.debug.tsx
+++ b/integration/snapshots/react-context-value-func.debug.tsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/react-context-value-func.hmr.debug.tsx b/integration/snapshots/react-context-value-func.hmr.debug.tsx
index 9280a638df..4632802d41 100644
--- a/integration/snapshots/react-context-value-func.hmr.debug.tsx
+++ b/integration/snapshots/react-context-value-func.hmr.debug.tsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/react-context-value-func.hmr.tsx b/integration/snapshots/react-context-value-func.hmr.tsx
index c6313661e3..5ad188422e 100644
--- a/integration/snapshots/react-context-value-func.hmr.tsx
+++ b/integration/snapshots/react-context-value-func.hmr.tsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/react-context-value-func.tsx b/integration/snapshots/react-context-value-func.tsx
index 5d151afba6..6ce4b09dbe 100644
--- a/integration/snapshots/react-context-value-func.tsx
+++ b/integration/snapshots/react-context-value-func.tsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/spread_with_key.debug.tsx b/integration/snapshots/spread_with_key.debug.tsx
index cb079bb950..25f380a8d4 100644
--- a/integration/snapshots/spread_with_key.debug.tsx
+++ b/integration/snapshots/spread_with_key.debug.tsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/spread_with_key.hmr.debug.tsx b/integration/snapshots/spread_with_key.hmr.debug.tsx
index 7f5076f1ae..78754d7dd2 100644
--- a/integration/snapshots/spread_with_key.hmr.debug.tsx
+++ b/integration/snapshots/spread_with_key.hmr.debug.tsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/spread_with_key.hmr.tsx b/integration/snapshots/spread_with_key.hmr.tsx
index 4b5d9ccf65..9e4da7bf4a 100644
--- a/integration/snapshots/spread_with_key.hmr.tsx
+++ b/integration/snapshots/spread_with_key.hmr.tsx
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/spread_with_key.tsx b/integration/snapshots/spread_with_key.tsx
index cb079bb950..25f380a8d4 100644
--- a/integration/snapshots/spread_with_key.tsx
+++ b/integration/snapshots/spread_with_key.tsx
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/string-escapes.debug.js b/integration/snapshots/string-escapes.debug.js
index af9c53abfc..9feb91e50b 100644
--- a/integration/snapshots/string-escapes.debug.js
+++ b/integration/snapshots/string-escapes.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/string-escapes.hmr.debug.js b/integration/snapshots/string-escapes.hmr.debug.js
index 19045846a2..923c8b8b3a 100644
--- a/integration/snapshots/string-escapes.hmr.debug.js
+++ b/integration/snapshots/string-escapes.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/string-escapes.hmr.js b/integration/snapshots/string-escapes.hmr.js
index e1f38c7afa..2ffed5df45 100644
--- a/integration/snapshots/string-escapes.hmr.js
+++ b/integration/snapshots/string-escapes.hmr.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/string-escapes.js b/integration/snapshots/string-escapes.js
index af9c53abfc..9feb91e50b 100644
--- a/integration/snapshots/string-escapes.js
+++ b/integration/snapshots/string-escapes.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js";
var JSXClassic = require($bbcd215f);
diff --git a/integration/snapshots/styledcomponents-output.debug.js b/integration/snapshots/styledcomponents-output.debug.js
index b99d434da8..7dcaa3d080 100644
--- a/integration/snapshots/styledcomponents-output.debug.js
+++ b/integration/snapshots/styledcomponents-output.debug.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/styledcomponents-output.hmr.debug.js b/integration/snapshots/styledcomponents-output.hmr.debug.js
index dc9e2de7d7..cecb4780ed 100644
--- a/integration/snapshots/styledcomponents-output.hmr.debug.js
+++ b/integration/snapshots/styledcomponents-output.hmr.debug.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/styledcomponents-output.hmr.js b/integration/snapshots/styledcomponents-output.hmr.js
index 5f0d525a47..c9bd340d12 100644
--- a/integration/snapshots/styledcomponents-output.hmr.js
+++ b/integration/snapshots/styledcomponents-output.hmr.js
@@ -1,12 +1,12 @@
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/styledcomponents-output.js b/integration/snapshots/styledcomponents-output.js
index b99d434da8..7dcaa3d080 100644
--- a/integration/snapshots/styledcomponents-output.js
+++ b/integration/snapshots/styledcomponents-output.js
@@ -1,6 +1,6 @@
import {
__require as require
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js";
var jsx = require(JSX).jsxDEV;
diff --git a/integration/snapshots/template-literal.hmr.debug.js b/integration/snapshots/template-literal.hmr.debug.js
index af93a6fa5d..a603ab705b 100644
--- a/integration/snapshots/template-literal.hmr.debug.js
+++ b/integration/snapshots/template-literal.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(2201713056, "template-literal.js"), exports = hmr.exports;
diff --git a/integration/snapshots/template-literal.hmr.js b/integration/snapshots/template-literal.hmr.js
index d27857c779..b237b0ec50 100644
--- a/integration/snapshots/template-literal.hmr.js
+++ b/integration/snapshots/template-literal.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(2201713056, "template-literal.js"), exports = hmr.exports;
diff --git a/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js b/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js
index c90ac6d25b..1b2c6fbf2d 100644
--- a/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js
+++ b/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(421762902, "ts-fallback-rewrite-works.ts"), exports = hmr.exports;
diff --git a/integration/snapshots/ts-fallback-rewrite-works.hmr.js b/integration/snapshots/ts-fallback-rewrite-works.hmr.js
index e728c5f143..577275c99e 100644
--- a/integration/snapshots/ts-fallback-rewrite-works.hmr.js
+++ b/integration/snapshots/ts-fallback-rewrite-works.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(421762902, "ts-fallback-rewrite-works.ts"), exports = hmr.exports;
diff --git a/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js b/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js
index d3aa0919aa..b9155a35fd 100644
--- a/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js
+++ b/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(2117426367, "tsx-fallback-rewrite-works.tsx"), exports = hmr.exports;
diff --git a/integration/snapshots/tsx-fallback-rewrite-works.hmr.js b/integration/snapshots/tsx-fallback-rewrite-works.hmr.js
index 3f2f754e26..98449f3558 100644
--- a/integration/snapshots/tsx-fallback-rewrite-works.hmr.js
+++ b/integration/snapshots/tsx-fallback-rewrite-works.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(2117426367, "tsx-fallback-rewrite-works.tsx"), exports = hmr.exports;
diff --git a/integration/snapshots/type-only-imports.hmr.debug.ts b/integration/snapshots/type-only-imports.hmr.debug.ts
index c647843ea4..c6ddfa45ff 100644
--- a/integration/snapshots/type-only-imports.hmr.debug.ts
+++ b/integration/snapshots/type-only-imports.hmr.debug.ts
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(650094581, "type-only-imports.ts"), exports = hmr.exports;
diff --git a/integration/snapshots/type-only-imports.hmr.ts b/integration/snapshots/type-only-imports.hmr.ts
index 84740d0d9e..4c3d9b9bbe 100644
--- a/integration/snapshots/type-only-imports.hmr.ts
+++ b/integration/snapshots/type-only-imports.hmr.ts
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(650094581, "type-only-imports.ts"), exports = hmr.exports;
diff --git a/integration/snapshots/unicode-identifiers.hmr.debug.js b/integration/snapshots/unicode-identifiers.hmr.debug.js
index 894cd0fe5c..81017ff5c7 100644
--- a/integration/snapshots/unicode-identifiers.hmr.debug.js
+++ b/integration/snapshots/unicode-identifiers.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(1398361736, "unicode-identifiers.js"), exports = hmr.exports;
diff --git a/integration/snapshots/unicode-identifiers.hmr.js b/integration/snapshots/unicode-identifiers.hmr.js
index f43fef51ce..d85c42c725 100644
--- a/integration/snapshots/unicode-identifiers.hmr.js
+++ b/integration/snapshots/unicode-identifiers.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(1398361736, "unicode-identifiers.js"), exports = hmr.exports;
diff --git a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js
index ebc46c9ba6..fa25488ec7 100644
--- a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js
+++ b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(true);
var hmr = new HMR(635901064, "void-shouldnt-delete-call-expressions.js"), exports = hmr.exports;
diff --git a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js
index 239b40fbd7..fb14bc53ac 100644
--- a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js
+++ b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js
@@ -1,9 +1,9 @@
import {
__HMRModule as HMR
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
import {
__HMRClient as Bun
-} from "http://localhost:8080/__runtime.js";
+} from "http://localhost:8080/bun:runtime";
Bun.activate(false);
var hmr = new HMR(635901064, "void-shouldnt-delete-call-expressions.js"), exports = hmr.exports;
diff --git a/misctools/readlink-getfd.zig b/misctools/readlink-getfd.zig
index 3e7cba5b99..f7934f54a8 100644
--- a/misctools/readlink-getfd.zig
+++ b/misctools/readlink-getfd.zig
@@ -22,7 +22,7 @@ pub fn main() anyerror!void {
var args_buffer: [8096 * 2]u8 = undefined;
var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer);
- var allocator = &fixed_buffer.allocator;
+ var allocator = fixed_buffer.allocator();
var args = std.mem.span(try std.process.argsAlloc(allocator));
@@ -32,7 +32,7 @@ pub fn main() anyerror!void {
var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var j: usize = 0;
- while (j < 100000) : (j += 1) {
+ while (j < 1000) : (j += 1) {
var parts = [1][]const u8{std.mem.span(to_resolve)};
var joined_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var joined = path_handler.joinAbsStringBuf(
diff --git a/misctools/readlink-realpath.zig b/misctools/readlink-realpath.zig
index cb7c7de2aa..e88a2e883a 100644
--- a/misctools/readlink-realpath.zig
+++ b/misctools/readlink-realpath.zig
@@ -22,17 +22,16 @@ pub fn main() anyerror!void {
var args_buffer: [8096 * 2]u8 = undefined;
var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer);
- var allocator = &fixed_buffer.allocator;
+ var allocator = fixed_buffer.allocator();
var args = std.mem.span(try std.process.argsAlloc(allocator));
const to_resolve = args[args.len - 1];
- const cwd = try std.process.getCwdAlloc(allocator);
var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var path: []u8 = undefined;
var j: usize = 0;
- while (j < 100000) : (j += 1) {
+ while (j < 1000) : (j += 1) {
path = try std.os.realpathZ(to_resolve, &out_buffer);
}
diff --git a/packages/bun-error/bun.lockb b/packages/bun-error/bun.lockb
index 1e4f1c8011..e61a4dd71f 100755
Binary files a/packages/bun-error/bun.lockb and b/packages/bun-error/bun.lockb differ
diff --git a/packages/bun-error/package-lock.json b/packages/bun-error/package-lock.json
index c33780e18f..29e3c4ab4d 100644
--- a/packages/bun-error/package-lock.json
+++ b/packages/bun-error/package-lock.json
@@ -1,187 +1,141 @@
{
"name": "bun-error",
"version": "1.0.0",
- "lockfileVersion": 2,
+ "lockfileVersion": 1,
"requires": true,
- "packages": {
- "": {
- "name": "bun-error",
- "version": "1.0.0",
- "license": "MIT",
- "dependencies": {
- "esbuild": "^0.12.26",
- "preact": "^10.5.14",
- "preact-compat": "^3.19.0",
- "react": "^17.0.2",
- "react-dom": "^17.0.2"
- }
- },
- "node_modules/esbuild": {
- "version": "0.12.26",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz",
- "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA==",
- "hasInstallScript": true,
- "bin": {
- "esbuild": "bin/esbuild"
- }
- },
- "node_modules/immutability-helper": {
- "version": "2.9.1",
- "resolved": "https://registry.npmjs.org/immutability-helper/-/immutability-helper-2.9.1.tgz",
- "integrity": "sha512-r/RmRG8xO06s/k+PIaif2r5rGc3j4Yhc01jSBfwPCXDLYZwp/yxralI37Df1mwmuzcCsen/E/ITKcTEvc1PQmQ==",
- "dependencies": {
- "invariant": "^2.2.0"
- }
- },
- "node_modules/invariant": {
- "version": "2.2.4",
- "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
- "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==",
- "dependencies": {
- "loose-envify": "^1.0.0"
- }
- },
- "node_modules/js-tokens": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
- },
- "node_modules/loose-envify": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
- "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
- "dependencies": {
- "js-tokens": "^3.0.0 || ^4.0.0"
- },
- "bin": {
- "loose-envify": "cli.js"
- }
- },
- "node_modules/object-assign": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
- "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/preact": {
- "version": "10.5.14",
- "resolved": "https://registry.npmjs.org/preact/-/preact-10.5.14.tgz",
- "integrity": "sha512-KojoltCrshZ099ksUZ2OQKfbH66uquFoxHSbnwKbTJHeQNvx42EmC7wQVWNuDt6vC5s3nudRHFtKbpY4ijKlaQ==",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/preact"
- }
- },
- "node_modules/preact-compat": {
- "version": "3.19.0",
- "resolved": "https://registry.npmjs.org/preact-compat/-/preact-compat-3.19.0.tgz",
- "integrity": "sha512-f83A4hIhH8Uzhb9GbIcGk8SM19ffWlwP9mDaYwQdRnMdekZwcCA7eIAbeV4EMQaV9C0Yuy8iKgBAtyTKPZQt/Q==",
- "dependencies": {
- "immutability-helper": "^2.7.1",
- "preact-context": "^1.1.3",
- "preact-render-to-string": "^3.8.2",
- "preact-transition-group": "^1.1.1",
- "prop-types": "^15.6.2",
- "standalone-react-addons-pure-render-mixin": "^0.1.1"
- },
- "peerDependencies": {
- "preact": "<10"
- }
- },
- "node_modules/preact-context": {
- "version": "1.1.4",
- "resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz",
- "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==",
- "peerDependencies": {
- "preact": "^8.2.7"
- }
- },
- "node_modules/preact-render-to-string": {
- "version": "3.8.2",
- "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-3.8.2.tgz",
- "integrity": "sha512-przuZPajiurStGgxMoJP0EJeC4xj5CgHv+M7GfF3YxAdhGgEWAkhOSE0xympAFN20uMayntBZpttIZqqLl77fw==",
- "dependencies": {
- "pretty-format": "^3.5.1"
- },
- "peerDependencies": {
- "preact": "*"
- }
- },
- "node_modules/preact-transition-group": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz",
- "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=",
- "peerDependencies": {
- "preact": "*"
- }
- },
- "node_modules/pretty-format": {
- "version": "3.8.0",
- "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz",
- "integrity": "sha1-v77VbV6ad2ZF9LH/eqGjrE+jw4U="
- },
- "node_modules/prop-types": {
- "version": "15.7.2",
- "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",
- "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",
- "dependencies": {
- "loose-envify": "^1.4.0",
- "object-assign": "^4.1.1",
- "react-is": "^16.8.1"
- }
- },
- "node_modules/react": {
- "version": "17.0.2",
- "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz",
- "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/react-dom": {
- "version": "17.0.2",
- "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz",
- "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1",
- "scheduler": "^0.20.2"
- },
- "peerDependencies": {
- "react": "17.0.2"
- }
- },
- "node_modules/react-is": {
- "version": "16.13.1",
- "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
- "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
- },
- "node_modules/scheduler": {
- "version": "0.20.2",
- "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz",
- "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==",
- "dependencies": {
- "loose-envify": "^1.1.0",
- "object-assign": "^4.1.1"
- }
- },
- "node_modules/standalone-react-addons-pure-render-mixin": {
- "version": "0.1.1",
- "resolved": "https://registry.npmjs.org/standalone-react-addons-pure-render-mixin/-/standalone-react-addons-pure-render-mixin-0.1.1.tgz",
- "integrity": "sha1-PHQJ9MecQN6axyxhbPZ5qZTzdVE="
- }
- },
"dependencies": {
"esbuild": {
- "version": "0.12.26",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz",
- "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA=="
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.11.tgz",
+ "integrity": "sha512-xZvPtVj6yecnDeFb3KjjCM6i7B5TCAQZT77kkW/CpXTMnd6VLnRPKrUB1XHI1pSq6a4Zcy3BGueQ8VljqjDGCg==",
+ "requires": {
+ "esbuild-android-arm64": "0.14.11",
+ "esbuild-darwin-64": "0.14.11",
+ "esbuild-darwin-arm64": "0.14.11",
+ "esbuild-freebsd-64": "0.14.11",
+ "esbuild-freebsd-arm64": "0.14.11",
+ "esbuild-linux-32": "0.14.11",
+ "esbuild-linux-64": "0.14.11",
+ "esbuild-linux-arm": "0.14.11",
+ "esbuild-linux-arm64": "0.14.11",
+ "esbuild-linux-mips64le": "0.14.11",
+ "esbuild-linux-ppc64le": "0.14.11",
+ "esbuild-linux-s390x": "0.14.11",
+ "esbuild-netbsd-64": "0.14.11",
+ "esbuild-openbsd-64": "0.14.11",
+ "esbuild-sunos-64": "0.14.11",
+ "esbuild-windows-32": "0.14.11",
+ "esbuild-windows-64": "0.14.11",
+ "esbuild-windows-arm64": "0.14.11"
+ }
+ },
+ "esbuild-android-arm64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.11.tgz",
+ "integrity": "sha512-6iHjgvMnC/SzDH8TefL+/3lgCjYWwAd1LixYfmz/TBPbDQlxcuSkX0yiQgcJB9k+ibZ54yjVXziIwGdlc+6WNw==",
+ "optional": true
+ },
+ "esbuild-darwin-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.11.tgz",
+ "integrity": "sha512-olq84ikh6TiBcrs3FnM4eR5VPPlcJcdW8BnUz/lNoEWYifYQ+Po5DuYV1oz1CTFMw4k6bQIZl8T3yxL+ZT2uvQ==",
+ "optional": true
+ },
+ "esbuild-darwin-arm64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.11.tgz",
+ "integrity": "sha512-Jj0ieWLREPBYr/TZJrb2GFH8PVzDqiQWavo1pOFFShrcmHWDBDrlDxPzEZ67NF/Un3t6sNNmeI1TUS/fe1xARg==",
+ "optional": true
+ },
+ "esbuild-freebsd-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.11.tgz",
+ "integrity": "sha512-C5sT3/XIztxxz/zwDjPRHyzj/NJFOnakAanXuyfLDwhwupKPd76/PPHHyJx6Po6NI6PomgVp/zi6GRB8PfrOTA==",
+ "optional": true
+ },
+ "esbuild-freebsd-arm64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.11.tgz",
+ "integrity": "sha512-y3Llu4wbs0bk4cwjsdAtVOesXb6JkdfZDLKMt+v1U3tOEPBdSu6w8796VTksJgPfqvpX22JmPLClls0h5p+L9w==",
+ "optional": true
+ },
+ "esbuild-linux-32": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.11.tgz",
+ "integrity": "sha512-Cg3nVsxArjyLke9EuwictFF3Sva+UlDTwHIuIyx8qpxRYAOUTmxr2LzYrhHyTcGOleLGXUXYsnUVwKqnKAgkcg==",
+ "optional": true
+ },
+ "esbuild-linux-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.11.tgz",
+ "integrity": "sha512-oeR6dIrrojr8DKVrxtH3xl4eencmjsgI6kPkDCRIIFwv4p+K7ySviM85K66BN01oLjzthpUMvBVfWSJkBLeRbg==",
+ "optional": true
+ },
+ "esbuild-linux-arm": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.11.tgz",
+ "integrity": "sha512-vcwskfD9g0tojux/ZaTJptJQU3a7YgTYsptK1y6LQ/rJmw7U5QJvboNawqM98Ca3ToYEucfCRGbl66OTNtp6KQ==",
+ "optional": true
+ },
+ "esbuild-linux-arm64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.11.tgz",
+ "integrity": "sha512-+e6ZCgTFQYZlmg2OqLkg1jHLYtkNDksxWDBWNtI4XG4WxuOCUErLqfEt9qWjvzK3XBcCzHImrajkUjO+rRkbMg==",
+ "optional": true
+ },
+ "esbuild-linux-mips64le": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.11.tgz",
+ "integrity": "sha512-Rrs99L+p54vepmXIb87xTG6ukrQv+CzrM8eoeR+r/OFL2Rg8RlyEtCeshXJ2+Q66MXZOgPJaokXJZb9snq28bw==",
+ "optional": true
+ },
+ "esbuild-linux-ppc64le": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.11.tgz",
+ "integrity": "sha512-JyzziGAI0D30Vyzt0HDihp4s1IUtJ3ssV2zx9O/c+U/dhUHVP2TmlYjzCfCr2Q6mwXTeloDcLS4qkyvJtYptdQ==",
+ "optional": true
+ },
+ "esbuild-linux-s390x": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.11.tgz",
+ "integrity": "sha512-DoThrkzunZ1nfRGoDN6REwmo8ZZWHd2ztniPVIR5RMw/Il9wiWEYBahb8jnMzQaSOxBsGp0PbyJeVLTUatnlcw==",
+ "optional": true
+ },
+ "esbuild-netbsd-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.11.tgz",
+ "integrity": "sha512-12luoRQz+6eihKYh1zjrw0CBa2aw3twIiHV/FAfjh2NEBDgJQOY4WCEUEN+Rgon7xmLh4XUxCQjnwrvf8zhACw==",
+ "optional": true
+ },
+ "esbuild-openbsd-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.11.tgz",
+ "integrity": "sha512-l18TZDjmvwW6cDeR4fmizNoxndyDHamGOOAenwI4SOJbzlJmwfr0jUgjbaXCUuYVOA964siw+Ix+A+bhALWg8Q==",
+ "optional": true
+ },
+ "esbuild-sunos-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.11.tgz",
+ "integrity": "sha512-bmYzDtwASBB8c+0/HVOAiE9diR7+8zLm/i3kEojUH2z0aIs6x/S4KiTuT5/0VKJ4zk69kXel1cNWlHBMkmavQg==",
+ "optional": true
+ },
+ "esbuild-windows-32": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.11.tgz",
+ "integrity": "sha512-J1Ys5hMid8QgdY00OBvIolXgCQn1ARhYtxPnG6ESWNTty3ashtc4+As5nTrsErnv8ZGUcWZe4WzTP/DmEVX1UQ==",
+ "optional": true
+ },
+ "esbuild-windows-64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.11.tgz",
+ "integrity": "sha512-h9FmMskMuGeN/9G9+LlHPAoiQk9jlKDUn9yA0MpiGzwLa82E7r1b1u+h2a+InprbSnSLxDq/7p5YGtYVO85Mlg==",
+ "optional": true
+ },
+ "esbuild-windows-arm64": {
+ "version": "0.14.11",
+ "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.11.tgz",
+ "integrity": "sha512-dZp7Krv13KpwKklt9/1vBFBMqxEQIO6ri7Azf8C+ob4zOegpJmha2XY9VVWP/OyQ0OWk6cEeIzMJwInRZrzBUQ==",
+ "optional": true
},
"immutability-helper": {
"version": "2.9.1",
@@ -238,8 +192,7 @@
"preact-context": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz",
- "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==",
- "requires": {}
+ "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ=="
},
"preact-render-to-string": {
"version": "3.8.2",
@@ -252,8 +205,7 @@
"preact-transition-group": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz",
- "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=",
- "requires": {}
+ "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA="
},
"pretty-format": {
"version": "3.8.0",
diff --git a/realpath.js b/realpath.js
new file mode 100644
index 0000000000..eabc112f3b
--- /dev/null
+++ b/realpath.js
@@ -0,0 +1,2 @@
+for (let i = 0; i < 9999; i++)
+ require("fs").realpathSync("./node_modules/.bin/prettier");
diff --git a/src/allocators.zig b/src/allocators.zig
index 16fe5deecb..f956de4d0f 100644
--- a/src/allocators.zig
+++ b/src/allocators.zig
@@ -68,11 +68,45 @@ pub const ItemStatus = enum(u3) {
not_found,
};
+fn OverflowGroup(comptime Block: type) type {
+ return struct {
+ const Overflow = @This();
+ // 16 million files should be good enough for anyone
+ // ...right?
+ const max = 4095;
+ const UsedSize = std.math.IntFittingRange(0, max + 1);
+ const default_allocator = @import("./global.zig").default_allocator;
+ used: UsedSize = 0,
+ allocated: UsedSize = 0,
+ ptrs: [max]*Block = undefined,
+
+ pub fn tail(this: *Overflow) *Block {
+ if (this.allocated > 0 and this.ptrs[this.used].isFull()) {
+ this.used +%= 1;
+ if (this.allocated > this.used) {
+ this.ptrs[this.used].used = 0;
+ }
+ }
+
+ if (this.allocated <= this.used) {
+ this.ptrs[this.allocated] = default_allocator.create(Block) catch unreachable;
+ this.ptrs[this.allocated].* = Block{};
+ this.allocated +%= 1;
+ }
+
+ return this.ptrs[this.used];
+ }
+
+ pub inline fn slice(this: *Overflow) []*Block {
+ return this.ptrs[0..this.used];
+ }
+ };
+}
+
pub fn OverflowList(comptime ValueType: type, comptime count: comptime_int) type {
return struct {
const This = @This();
const SizeType = std.math.IntFittingRange(0, count);
- const default_allocator = @import("./global.zig").default_allocator;
const Block = struct {
used: SizeType = 0,
@@ -90,37 +124,7 @@ pub fn OverflowList(comptime ValueType: type, comptime count: comptime_int) type
return &block.items[index];
}
};
-
- const Overflow = struct {
- // 16 million files should be good enough for anyone
- // ...right?
- const max = 4095;
- const UsedSize = std.math.IntFittingRange(0, max + 1);
- used: UsedSize = 0,
- allocated: UsedSize = 0,
- ptrs: [max]*Block = undefined,
-
- pub fn tail(this: *Overflow) *Block {
- if (this.allocated > 0 and this.ptrs[this.used].isFull()) {
- this.used +%= 1;
- if (this.allocated > this.used) {
- this.ptrs[this.used].used = 0;
- }
- }
-
- if (this.allocated <= this.used) {
- this.ptrs[this.allocated] = default_allocator.create(Block) catch unreachable;
- this.ptrs[this.allocated].* = Block{};
- this.allocated +%= 1;
- }
-
- return this.ptrs[this.used];
- }
-
- pub inline fn slice(this: *Overflow) []*Block {
- return this.ptrs[0..this.used];
- }
- };
+ const Overflow = OverflowGroup(Block);
list: Overflow = Overflow{},
count: u31 = 0,
diff --git a/src/ast/base.zig b/src/ast/base.zig
index f2312677f2..91e0bcafc7 100644
--- a/src/ast/base.zig
+++ b/src/ast/base.zig
@@ -25,50 +25,54 @@ pub const NodeIndexNone = 4294967293;
pub const RefHashCtx = struct {
pub fn hash(_: @This(), key: Ref) u32 {
- return @truncate(u32, std.hash.Wyhash.hash(0, std.mem.asBytes(&key)));
+ return key.hash();
}
pub fn eql(_: @This(), ref: Ref, b: Ref) bool {
- return std.mem.readIntNative(u64, std.mem.asBytes(&ref)) == std.mem.readIntNative(u64, std.mem.asBytes(&b));
+ return ref.asBitInt() == b.asBitInt();
}
};
pub const Ref = packed struct {
- source_index: Int = std.math.maxInt(Ref.Int),
+ const max_ref_int = std.math.maxInt(Ref.Int);
+ pub const BitInt = std.meta.Int(.unsigned, @bitSizeOf(Ref));
+
+ source_index: Int = max_ref_int,
inner_index: Int = 0,
is_source_contents_slice: bool = false,
+ pub inline fn asBitInt(this: Ref) BitInt {
+ return @bitCast(BitInt, this);
+ }
+
// 2 bits of padding for whatever is the parent
pub const Int = u30;
pub const None = Ref{
- .inner_index = std.math.maxInt(Ref.Int),
- .source_index = std.math.maxInt(Ref.Int),
+ .inner_index = max_ref_int,
+ .source_index = max_ref_int,
};
pub const RuntimeRef = Ref{
- .inner_index = std.math.maxInt(Ref.Int),
- .source_index = std.math.maxInt(Ref.Int) - 1,
+ .inner_index = max_ref_int,
+ .source_index = max_ref_int - 1,
};
+
pub fn toInt(int: anytype) Int {
return @intCast(Int, int);
}
pub fn hash(key: Ref) u32 {
- return @truncate(u32, std.hash.Wyhash.hash(0, std.mem.asBytes(&key)));
+ return @truncate(u32, std.hash.Wyhash.hash(0, &@bitCast([8]u8, @as(u64, key.asBitInt()))));
}
pub fn eql(ref: Ref, b: Ref) bool {
- return std.mem.readIntNative(u64, std.mem.asBytes(&ref)) == std.mem.readIntNative(u64, std.mem.asBytes(&b));
+ return asBitInt(ref) == b.asBitInt();
}
pub fn isNull(self: *const Ref) bool {
- return self.source_index == std.math.maxInt(Ref.Int) and self.inner_index == std.math.maxInt(Ref.Int);
- }
-
- pub fn isSourceNull(self: *const Ref) bool {
- return self.source_index == std.math.maxInt(Ref.Int);
+ return self.source_index == max_ref_int and self.inner_index == max_ref_int;
}
pub fn isSourceIndexNull(int: anytype) bool {
- return int == std.math.maxInt(Ref.Int);
+ return int == max_ref_int;
}
pub fn jsonStringify(self: *const Ref, options: anytype, writer: anytype) !void {
diff --git a/src/bindgen.zig b/src/bindgen.zig
index e76a1ce6da..adca783319 100644
--- a/src/bindgen.zig
+++ b/src/bindgen.zig
@@ -1,3 +1,5 @@
pub const bindgen = true;
pub const main = @import("./javascript/jsc/bindings/bindings-generator.zig").main;
+pub export fn PLCrashReportHandler(_: ?*anyopaque) void {}
+pub export fn mkdirp(_: ?*anyopaque) void {}
diff --git a/src/bun_js.zig b/src/bun_js.zig
index 5bfd27110d..0915cc55c5 100644
--- a/src/bun_js.zig
+++ b/src/bun_js.zig
@@ -29,6 +29,9 @@ const NodeModuleBundle = @import("node_module_bundle.zig").NodeModuleBundle;
const DotEnv = @import("env_loader.zig");
const which = @import("which.zig").which;
const VirtualMachine = @import("./javascript/jsc/javascript.zig").VirtualMachine;
+const JSC = @import("javascript_core");
+
+const OpaqueWrap = JSC.OpaqueWrap;
pub const Run = struct {
file: std.fs.File,
@@ -48,8 +51,10 @@ pub const Run = struct {
.entry_path = entry_path,
};
+ run.vm.argv = ctx.positionals;
+
run.vm.bundler.configureRouter(false) catch {
- if (Output.enable_ansi_colors) {
+ if (Output.enable_ansi_colors_stderr) {
run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
@@ -59,7 +64,7 @@ pub const Run = struct {
std.os.exit(1);
};
run.vm.bundler.configureDefines() catch {
- if (Output.enable_ansi_colors) {
+ if (Output.enable_ansi_colors_stderr) {
run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
@@ -69,11 +74,12 @@ pub const Run = struct {
std.os.exit(1);
};
- try run.start();
+ var callback = OpaqueWrap(Run, Run.start);
+ run.vm.global.vm().holdAPILock(&run, callback);
}
- pub fn start(this: *Run) !void {
- var promise = try this.vm.loadEntryPoint(this.entry_path);
+ pub fn start(this: *Run) void {
+ var promise = this.vm.loadEntryPoint(this.entry_path) catch return;
this.vm.tick();
while (promise.status(this.vm.global.vm()) == .Pending) {
diff --git a/src/bundler.zig b/src/bundler.zig
index 00a37a5553..8127a4dc59 100644
--- a/src/bundler.zig
+++ b/src/bundler.zig
@@ -1376,6 +1376,29 @@ pub const Bundler = struct {
.module_id = package_json.hashModule(package_path),
};
}
+
+ // This is our last resort.
+ // The package is supposed to be bundled
+ // package.json says its' in packages/@foo/bar/index.js
+ // The file really is in packages/bar/index.js
+ // But we need the import path to contain the package path for bundling to work
+ // so we fake it
+ // we say ""
+ if (package_json.name[0] == '@') {
+ if (std.mem.indexOfScalar(u8, package_json.name, '/')) |at| {
+ const package_subpath = package_json.name[at + 1 ..];
+ if (std.mem.lastIndexOf(u8, file_path, package_subpath)) |i| {
+ package_path = this.bundler.fs.dirname_store.print("{s}/{s}", .{ package_json.name, file_path[i + package_subpath.len ..] }) catch unreachable;
+ import_path = package_path[package_json.name.len + 1 ..];
+ return BundledModuleData{
+ .import_path = import_path,
+ .package_path = package_path,
+ .package = package_json,
+ .module_id = package_json.hashModule(package_path),
+ };
+ }
+ }
+ }
}
unreachable;
}
@@ -1487,7 +1510,8 @@ pub const Bundler = struct {
};
var file_path = (resolve.pathConst() orelse unreachable).*;
const source_dir = file_path.sourceDir();
- const loader = this.bundler.options.loader(file_path.name.ext);
+ const loader = bundler.options.loader(file_path.name.ext);
+ const platform = bundler.options.platform;
defer scan_pass_result.reset();
defer shared_buffer.reset();
@@ -1656,7 +1680,7 @@ pub const Bundler = struct {
} else |err| {
if (comptime Environment.isDebug) {
if (!import_record.handles_import_errors) {
- Output.prettyErrorln("\n{s} on resolving \"{s}\" from \"{s}\"", .{
+ Output.prettyErrorln("\n{s} resolving \"{s}\" from \"{s}\"", .{
@errorName(err),
import_record.path.text,
file_path.text,
@@ -1672,29 +1696,36 @@ pub const Bundler = struct {
switch (err) {
error.ModuleNotFound => {
+ const addError = logger.Log.addResolveErrorWithTextDupeMaybeWarn;
+
if (!import_record.handles_import_errors) {
if (isPackagePath(import_record.path.text)) {
- if (this.bundler.options.platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) {
- try log.addResolveErrorWithTextDupe(
+ if (platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) {
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
"Could not resolve Node.js builtin: \"{s}\".",
.{import_record.path.text},
import_record.kind,
+ platform.isBun(),
);
} else {
- try log.addResolveErrorWithTextDupe(
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
"Could not resolve: \"{s}\". Maybe you need to \"bun install\"?",
.{import_record.path.text},
import_record.kind,
+ platform.isBun(),
);
}
} else {
- try log.addResolveErrorWithTextDupe(
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
@@ -1703,6 +1734,7 @@ pub const Bundler = struct {
import_record.path.text,
},
import_record.kind,
+ platform.isBun(),
);
}
}
@@ -2098,28 +2130,34 @@ pub const Bundler = struct {
switch (err) {
error.ModuleNotFound => {
if (!import_record.handles_import_errors) {
+ const addError = logger.Log.addResolveErrorWithTextDupeMaybeWarn;
if (isPackagePath(import_record.path.text)) {
- if (this.bundler.options.platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) {
- try log.addResolveErrorWithTextDupe(
+ if (platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) {
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
"Could not resolve Node.js builtin: \"{s}\".",
.{import_record.path.text},
import_record.kind,
+ platform.isBun(),
);
} else {
- try log.addResolveErrorWithTextDupe(
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
"Could not resolve: \"{s}\". Maybe you need to \"bun install\"?",
.{import_record.path.text},
import_record.kind,
+ platform.isBun(),
);
}
} else {
- try log.addResolveErrorWithTextDupe(
+ try addError(
+ log,
&source,
import_record.range,
this.allocator,
@@ -2128,6 +2166,7 @@ pub const Bundler = struct {
import_record.path.text,
},
import_record.kind,
+ platform.isBun(),
);
}
}
@@ -2740,13 +2779,6 @@ pub const Bundler = struct {
var path_to_use = path_to_use_;
- if (strings.eqlComptime(path_to_use, "__runtime.js")) {
- return ServeResult{
- .file = options.OutputFile.initBuf(runtime.Runtime.sourceContent(), "__runtime.js", .js),
- .mime_type = MimeType.javascript,
- };
- }
-
defer {
js_ast.Expr.Data.Store.reset();
js_ast.Stmt.Data.Store.reset();
@@ -2915,8 +2947,6 @@ pub const Bundler = struct {
}
}
- if (bundler.options.write and bundler.options.output_dir.len > 0) {}
-
// 100.00 µs std.fifo.LinearFifo(resolver.Result,std.fifo.LinearFifoBufferType { .Dynamic = {}}).writeItemAssumeCapacity
if (bundler.options.resolve_mode != .lazy) {
try bundler.resolve_queue.ensureUnusedCapacity(3);
@@ -3003,7 +3033,7 @@ pub const Bundler = struct {
if (bundler.linker.any_needs_runtime) {
try bundler.output_files.append(
- options.OutputFile.initBuf(runtime.Runtime.sourceContent(), bundler.linker.runtime_source_path, .js),
+ options.OutputFile.initBuf(runtime.Runtime.sourceContent(), Linker.runtime_source_path, .js),
);
}
diff --git a/src/c.zig b/src/c.zig
index 6529a234da..f26f838880 100644
--- a/src/c.zig
+++ b/src/c.zig
@@ -3,6 +3,7 @@ const Enviroment = @import("./env.zig");
const PlatformSpecific = switch (@import("builtin").target.os.tag) {
.macos => @import("./darwin_c.zig"),
+ .linux => @import("./linux_c.zig"),
else => struct {},
};
pub usingnamespace PlatformSpecific;
@@ -18,16 +19,23 @@ const errno = os.errno;
const mode_t = C.mode_t;
const libc_stat = C.Stat;
const zeroes = mem.zeroes;
-
+pub const darwin = @import("./darwin_c.zig");
+pub const linux = @import("./linux_c.zig");
pub extern "c" fn chmod([*c]const u8, mode_t) c_int;
pub extern "c" fn fchmod(std.c.fd_t, mode_t) c_int;
pub extern "c" fn umask(mode_t) mode_t;
pub extern "c" fn fchmodat(c_int, [*c]const u8, mode_t, c_int) c_int;
pub extern "c" fn fchown(std.c.fd_t, std.c.uid_t, std.c.gid_t) c_int;
+pub extern "c" fn lchown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int;
+pub extern "c" fn chown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int;
pub extern "c" fn lstat([*c]const u8, [*c]libc_stat) c_int;
pub extern "c" fn lstat64([*c]const u8, [*c]libc_stat) c_int;
+pub extern "c" fn lchmod(path: [*:0]const u8, mode: mode_t) c_int;
+pub extern "c" fn truncate(path: [*:0]const u8, len: os.off_t) c_int;
+pub extern "c" fn lutimes(path: [*:0]const u8, times: *const [2]std.os.timeval) c_int;
+pub extern "c" fn mkdtemp(template: [*c]u8) ?[*:0]u8;
-pub fn lstat_absolute(path: [:0]const u8) StatError!Stat {
+pub fn lstat_absolute(path: [:0]const u8) !Stat {
if (builtin.os.tag == .windows) {
@compileError("Not implemented yet");
}
@@ -35,6 +43,7 @@ pub fn lstat_absolute(path: [:0]const u8) StatError!Stat {
var st = zeroes(libc_stat);
switch (errno(lstat64(path.ptr, &st))) {
.SUCCESS => {},
+ .NOENT => return error.FileNotFound,
// .EINVAL => unreachable,
.BADF => unreachable, // Always a race condition.
.NOMEM => return error.SystemResources,
diff --git a/src/cli.zig b/src/cli.zig
index b17dc83967..40b59b9284 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -36,30 +36,35 @@ const Router = @import("./router.zig");
const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle;
-const BunCommand = @import("./cli/bun_command.zig").BunCommand;
-const DevCommand = @import("./cli/dev_command.zig").DevCommand;
-const DiscordCommand = @import("./cli/discord_command.zig").DiscordCommand;
+const AddCommand = @import("./cli/add_command.zig").AddCommand;
const BuildCommand = @import("./cli/build_command.zig").BuildCommand;
+const BunCommand = @import("./cli/bun_command.zig").BunCommand;
const CreateCommand = @import("./cli/create_command.zig").CreateCommand;
const CreateListExamplesCommand = @import("./cli/create_command.zig").CreateListExamplesCommand;
-const RunCommand = @import("./cli/run_command.zig").RunCommand;
-const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand;
+const DevCommand = @import("./cli/dev_command.zig").DevCommand;
+const DiscordCommand = @import("./cli/discord_command.zig").DiscordCommand;
const InstallCommand = @import("./cli/install_command.zig").InstallCommand;
-const AddCommand = @import("./cli/add_command.zig").AddCommand;
-const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand;
-const PackageManagerCommand = @import("./cli/package_manager_command.zig").PackageManagerCommand;
const InstallCompletionsCommand = @import("./cli/install_completions_command.zig").InstallCompletionsCommand;
+const PackageManagerCommand = @import("./cli/package_manager_command.zig").PackageManagerCommand;
+const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand;
+const RunCommand = @import("./cli/run_command.zig").RunCommand;
const ShellCompletions = @import("./cli/shell_completions.zig");
+const TestCommand = @import("./cli/test_command.zig").TestCommand;
+const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand;
+const Reporter = @import("./report.zig");
var start_time: i128 = undefined;
pub const Cli = struct {
var wait_group: sync.WaitGroup = undefined;
+ var log_: logger.Log = undefined;
pub fn startTransform(_: std.mem.Allocator, _: Api.TransformOptions, _: *logger.Log) anyerror!void {}
- pub fn start(allocator: std.mem.Allocator, _: anytype, _: anytype, comptime MainPanicHandler: type) anyerror!void {
+ pub fn start(allocator: std.mem.Allocator, _: anytype, _: anytype, comptime MainPanicHandler: type) void {
start_time = std.time.nanoTimestamp();
- var log = try allocator.create(logger.Log);
- log.* = logger.Log.init(allocator);
+ log_ = logger.Log.init(allocator);
+
+ var log = &log_;
+
var panicker = MainPanicHandler.init(log);
MainPanicHandler.Singleton = &panicker;
@@ -71,7 +76,14 @@ pub const Cli = struct {
std.os.exit(1);
},
else => {
- return err;
+ // Always dump the logs
+ if (Output.enable_ansi_colors_stderr) {
+ log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
+ } else {
+ log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
+ }
+
+ Reporter.globalError(err);
},
}
};
@@ -84,7 +96,13 @@ const LoaderMatcher = strings.ExactSizeMatcher(4);
const ColonListType = @import("./cli/colon_list_type.zig").ColonListType;
pub const LoaderColonList = ColonListType(Api.Loader, Arguments.loader_resolver);
pub const DefineColonList = ColonListType(string, Arguments.noop_resolver);
-
+fn invalidPlatform(diag: *clap.Diagnostic, _platform: []const u8) noreturn {
+ @setCold(true);
+ diag.name.long = "--platform";
+ diag.arg = _platform;
+ diag.report(Output.errorWriter(), error.InvalidPlatform) catch {};
+ std.process.exit(1);
+}
pub const Arguments = struct {
pub fn loader_resolver(in: string) !Api.Loader {
const Matcher = strings.ExactSizeMatcher(4);
@@ -199,11 +217,16 @@ pub const Arguments = struct {
printVersionAndExit();
}
- var cwd_paths = [_]string{args.option("--cwd") orelse try std.process.getCwdAlloc(allocator)};
- var cwd = try std.fs.path.resolve(allocator, &cwd_paths);
+ var cwd: []u8 = undefined;
+ if (args.option("--cwd")) |cwd_| {
+ var cwd_paths = [_]string{cwd_};
+ cwd = try std.fs.path.resolve(allocator, &cwd_paths);
+ } else {
+ cwd = try std.process.getCwdAlloc(allocator);
+ }
var defines_tuple = try DefineColonList.resolve(allocator, args.options("--define"));
- var loader_tuple = try LoaderColonList.resolve(allocator, args.options("--define"));
+ var loader_tuple = try LoaderColonList.resolve(allocator, args.options("--loader"));
var externals = std.mem.zeroes([][]u8);
if (args.options("--external").len > 0) {
externals = try allocator.alloc([]u8, args.options("--external").len);
@@ -329,17 +352,19 @@ pub const Arguments = struct {
else => true,
};
- opts.node_modules_bundle_path = args.option("--bunfile") orelse brk: {
- const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.bun");
+ if (comptime Command.Tag.cares_about_bun_file.get(cmd)) {
+ opts.node_modules_bundle_path = args.option("--bunfile") orelse brk: {
+ const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.bun");
- break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null;
- };
+ break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null;
+ };
- opts.node_modules_bundle_path_server = args.option("--server-bunfile") orelse brk: {
- const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.server.bun");
+ opts.node_modules_bundle_path_server = args.option("--server-bunfile") orelse brk: {
+ const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.server.bun");
- break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null;
- };
+ break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null;
+ };
+ }
switch (comptime cmd) {
.AutoCommand, .DevCommand, .BuildCommand, .BunCommand => {
@@ -387,23 +412,12 @@ pub const Arguments = struct {
const PlatformMatcher = strings.ExactSizeMatcher(8);
if (args.option("--platform")) |_platform| {
- switch (PlatformMatcher.match(_platform)) {
- PlatformMatcher.case("browser") => {
- opts.platform = Api.Platform.browser;
- },
- PlatformMatcher.case("node") => {
- opts.platform = Api.Platform.node;
- },
- PlatformMatcher.case("macro"), PlatformMatcher.case("bun") => {
- opts.platform = Api.Platform.bun;
- },
- else => {
- diag.name.long = "--platform";
- diag.arg = _platform;
- try diag.report(Output.errorWriter(), error.InvalidPlatform);
- std.process.exit(1);
- },
- }
+ opts.platform = switch (PlatformMatcher.match(_platform)) {
+ PlatformMatcher.case("browser") => Api.Platform.browser,
+ PlatformMatcher.case("node") => Api.Platform.node,
+ PlatformMatcher.case("macro"), PlatformMatcher.case("bun") => Api.Platform.bun,
+ else => invalidPlatform(&diag, _platform),
+ };
}
if (jsx_factory != null or
@@ -577,22 +591,26 @@ pub const Command = struct {
pub const Context = struct {
start_time: i128,
- args: Api.TransformOptions = std.mem.zeroes(Api.TransformOptions),
+ args: Api.TransformOptions,
log: *logger.Log,
allocator: std.mem.Allocator,
positionals: []const string = &[_]string{},
debug: DebugOptions = DebugOptions{},
+ const _ctx = Command.Context{
+ .args = std.mem.zeroes(Api.TransformOptions),
+ .log = undefined,
+ .start_time = 0,
+ .allocator = undefined,
+ };
+
pub fn create(allocator: std.mem.Allocator, log: *logger.Log, comptime command: Command.Tag) anyerror!Context {
Cli.cmd = command;
-
- var ctx = Command.Context{
- .args = std.mem.zeroes(Api.TransformOptions),
- .log = log,
- .start_time = start_time,
- .allocator = allocator,
- };
+ var ctx = _ctx;
+ ctx.log = log;
+ ctx.start_time = start_time;
+ ctx.allocator = allocator;
if (comptime Command.Tag.uses_global_options.get(command)) {
ctx.args = try Arguments.parse(allocator, &ctx, command);
@@ -602,8 +620,27 @@ pub const Command = struct {
}
};
- pub fn which(allocator: std.mem.Allocator) Tag {
- var args_iter = std.process.args();
+ // std.process.args allocates!
+ const ArgsIterator = struct {
+ buf: [][*:0]u8 = undefined,
+ i: u32 = 0,
+
+ pub fn next(this: *ArgsIterator) ?[]const u8 {
+ if (this.buf.len <= this.i) {
+ return null;
+ }
+ const i = this.i;
+ this.i += 1;
+ return std.mem.span(this.buf[i]);
+ }
+
+ pub fn skip(this: *ArgsIterator) bool {
+ return this.next() != null;
+ }
+ };
+
+ pub fn which() Tag {
+ var args_iter = ArgsIterator{ .buf = std.os.argv };
// first one is the executable name
const skipped = args_iter.skip();
@@ -611,9 +648,9 @@ pub const Command = struct {
return .AutoCommand;
}
- var next_arg = ((args_iter.next(allocator) catch null) orelse return .AutoCommand);
+ var next_arg = ((args_iter.next()) orelse return .AutoCommand);
while (next_arg[0] == '-') {
- next_arg = ((args_iter.next(allocator) catch null) orelse return .AutoCommand);
+ next_arg = ((args_iter.next()) orelse return .AutoCommand);
}
const first_arg_name = std.mem.span(next_arg);
@@ -630,6 +667,8 @@ pub const Command = struct {
RootCommandMatcher.case("i"), RootCommandMatcher.case("install") => .InstallCommand,
RootCommandMatcher.case("c"), RootCommandMatcher.case("create") => .CreateCommand,
+ RootCommandMatcher.case(TestCommand.name) => .TestCommand,
+
RootCommandMatcher.case("pm") => .PackageManagerCommand,
RootCommandMatcher.case("add"), RootCommandMatcher.case("update"), RootCommandMatcher.case("a") => .AddCommand,
@@ -665,7 +704,7 @@ pub const Command = struct {
};
pub fn start(allocator: std.mem.Allocator, log: *logger.Log) !void {
- const tag = which(allocator);
+ const tag = which();
switch (tag) {
.DiscordCommand => return try DiscordCommand.exec(allocator),
.HelpCommand => return try HelpCommand.exec(allocator),
@@ -717,6 +756,12 @@ pub const Command = struct {
try PackageManagerCommand.exec(ctx);
return;
},
+ .TestCommand => {
+ const ctx = try Command.Context.create(allocator, log, .TestCommand);
+
+ try TestCommand.exec(ctx);
+ return;
+ },
.GetCompletionsCommand => {
const ctx = try Command.Context.create(allocator, log, .GetCompletionsCommand);
var filter = ctx.positionals;
@@ -881,6 +926,21 @@ pub const Command = struct {
const file_: std.fs.File.OpenError!std.fs.File = brk: {
if (script_name_to_search[0] == std.fs.path.sep) {
break :brk std.fs.openFileAbsolute(script_name_to_search, .{ .read = true });
+ } else if (!strings.hasPrefix(script_name_to_search, "..") and script_name_to_search[0] != '~') {
+ const file_pathZ = brk2: {
+ if (!strings.hasPrefix(file_path, "./")) {
+ script_name_buf[0..2].* = "./".*;
+ @memcpy(script_name_buf[2..], file_path.ptr, file_path.len);
+ script_name_buf[file_path.len + 2] = 0;
+ break :brk2 script_name_buf[0 .. file_path.len + 2 :0];
+ } else {
+ @memcpy(&script_name_buf, file_path.ptr, file_path.len);
+ script_name_buf[file_path.len] = 0;
+ break :brk2 script_name_buf[0..file_path.len :0];
+ }
+ };
+
+ break :brk std.fs.cwd().openFileZ(file_pathZ, .{ .read = true });
} else {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const cwd = std.os.getcwd(&path_buf) catch break :possibly_open_with_bun_js;
@@ -954,6 +1014,16 @@ pub const Command = struct {
RunCommand,
UpgradeCommand,
PackageManagerCommand,
+ TestCommand,
+
+ pub const cares_about_bun_file: std.EnumArray(Tag, bool) = std.EnumArray(Tag, bool).initDefault(false, .{
+ .AutoCommand = true,
+ .BuildCommand = true,
+ .BunCommand = true,
+ .DevCommand = true,
+ .RunCommand = true,
+ .TestCommand = true,
+ });
pub const uses_global_options: std.EnumArray(Tag, bool) = std.EnumArray(Tag, bool).initDefault(true, .{
.CreateCommand = false,
diff --git a/src/cli/colon_list_type.zig b/src/cli/colon_list_type.zig
index 2dd5e25227..73a3f12993 100644
--- a/src/cli/colon_list_type.zig
+++ b/src/cli/colon_list_type.zig
@@ -26,7 +26,7 @@ pub fn ColonListType(comptime t: type, value_resolver: anytype) type {
// Support either ":" or "=" as the separator, preferring whichever is first.
// ":" is less confusing IMO because that syntax is used with flags
// but "=" is what esbuild uses and I want this to be somewhat familiar for people using esbuild
- const midpoint = std.math.min(strings.indexOfChar(str, ':') orelse std.math.maxInt(usize), strings.indexOfChar(str, '=') orelse std.math.maxInt(usize));
+ const midpoint = @minimum(strings.indexOfChar(str, ':') orelse std.math.maxInt(usize), strings.indexOfChar(str, '=') orelse std.math.maxInt(usize));
if (midpoint == std.math.maxInt(usize)) {
return error.InvalidSeparator;
}
diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig
new file mode 100644
index 0000000000..60d03392ab
--- /dev/null
+++ b/src/cli/test_command.zig
@@ -0,0 +1,397 @@
+const _global = @import("../global.zig");
+const string = _global.string;
+const Output = _global.Output;
+const Global = _global.Global;
+const Environment = _global.Environment;
+const strings = _global.strings;
+const MutableString = _global.MutableString;
+const stringZ = _global.stringZ;
+const default_allocator = _global.default_allocator;
+const C = _global.C;
+const std = @import("std");
+
+const lex = @import("../js_lexer.zig");
+const logger = @import("../logger.zig");
+
+const FileSystem = @import("../fs.zig").FileSystem;
+const options = @import("../options.zig");
+const js_parser = @import("../js_parser.zig");
+const json_parser = @import("../json_parser.zig");
+const js_printer = @import("../js_printer.zig");
+const js_ast = @import("../js_ast.zig");
+const linker = @import("../linker.zig");
+const panicky = @import("../panic_handler.zig");
+const sync = @import("../sync.zig");
+const Api = @import("../api/schema.zig").Api;
+const resolve_path = @import("../resolver/resolve_path.zig");
+const configureTransformOptionsForBun = @import("../javascript/jsc/config.zig").configureTransformOptionsForBun;
+const Command = @import("../cli.zig").Command;
+const bundler = @import("../bundler.zig");
+const NodeModuleBundle = @import("../node_module_bundle.zig").NodeModuleBundle;
+const DotEnv = @import("../env_loader.zig");
+const which = @import("../which.zig").which;
+const Run = @import("../bun_js.zig").Run;
+var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
+var path_buf2: [std.fs.MAX_PATH_BYTES]u8 = undefined;
+const PathString = _global.PathString;
+
+const JSC = @import("javascript_core");
+const Jest = JSC.Jest;
+const TestRunner = JSC.Jest.TestRunner;
+const Test = TestRunner.Test;
+pub const CommandLineReporter = struct {
+ jest: TestRunner,
+ callback: TestRunner.Callback,
+ last_dot: u32 = 0,
+ summary: Summary = Summary{},
+
+ pub const Summary = struct {
+ pass: u32 = 0,
+ expectations: u32 = 0,
+ fail: u32 = 0,
+ };
+
+ const DotColorMap = std.EnumMap(TestRunner.Test.Status, string);
+ const dots: DotColorMap = brk: {
+ var map: DotColorMap = DotColorMap.init(.{});
+ map.put(TestRunner.Test.Status.pending, Output.RESET ++ Output.ED ++ Output.color_map.get("yellow").? ++ "." ++ Output.RESET);
+ map.put(TestRunner.Test.Status.pass, Output.RESET ++ Output.ED ++ Output.color_map.get("green").? ++ "." ++ Output.RESET);
+ map.put(TestRunner.Test.Status.fail, Output.RESET ++ Output.ED ++ Output.color_map.get("red").? ++ "." ++ Output.RESET);
+ break :brk map;
+ };
+
+ fn updateDots(this: *CommandLineReporter) void {
+ const statuses = this.jest.tests.items(.status);
+ var writer = Output.errorWriter();
+ writer.writeAll("\r") catch unreachable;
+ if (Output.enable_ansi_colors_stderr) {
+ for (statuses) |status| {
+ writer.writeAll(dots.get(status).?) catch unreachable;
+ }
+ } else {
+ for (statuses) |_| {
+ writer.writeAll(".") catch unreachable;
+ }
+ }
+ }
+
+ pub fn handleUpdateCount(cb: *TestRunner.Callback, _: u32, _: u32) void {
+ _ = cb;
+ }
+
+ pub fn handleTestStart(_: *TestRunner.Callback, _: Test.ID) void {
+ // var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb);
+ }
+ pub fn handleTestPass(cb: *TestRunner.Callback, _: Test.ID, expectations: u32) void {
+ var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb);
+ // this.updateDots();
+ this.summary.pass += 1;
+ this.summary.expectations += expectations;
+ }
+ pub fn handleTestFail(cb: *TestRunner.Callback, test_id: Test.ID, _: string, _: string, _: u32) void {
+ // var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb);
+ var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb);
+ // this.updateDots();
+ this.summary.fail += 1;
+ _ = test_id;
+ }
+};
+
+const Scanner = struct {
+ const Fifo = std.fifo.LinearFifo(ScanEntry, .Dynamic);
+ exclusion_names: []const []const u8 = &.{},
+ filter_names: []const []const u8 = &.{},
+ dirs_to_scan: Fifo,
+ results: std.ArrayList(_global.PathString),
+ fs: *FileSystem,
+ open_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined,
+ scan_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined,
+ options: *options.BundleOptions,
+ has_iterated: bool = false,
+
+ const ScanEntry = struct {
+ relative_dir: _global.StoredFileDescriptorType,
+ dir_path: string,
+ name: strings.StringOrTinyString,
+ };
+
+ fn readDirWithName(this: *Scanner, name: string, handle: ?std.fs.Dir) !*FileSystem.RealFS.EntriesOption {
+ return try this.fs.fs.readDirectoryWithIterator(name, handle, *Scanner, this);
+ }
+
+ pub fn scan(this: *Scanner, path_literal: string) void {
+ var parts = &[_]string{ this.fs.top_level_dir, path_literal };
+ const path = this.fs.absBuf(parts, &this.scan_dir_buf);
+ var root = this.readDirWithName(path, null) catch |err| {
+ if (err == error.NotDir) {
+ if (this.isTestFile(path)) {
+ this.results.append(_global.PathString.init(this.fs.filename_store.append(@TypeOf(path), path) catch unreachable)) catch unreachable;
+ }
+ }
+
+ return;
+ };
+
+ // you typed "." and we already scanned it
+ if (!this.has_iterated) {
+ if (@as(FileSystem.RealFS.EntriesOption.Tag, root.*) == .entries) {
+ var iter = root.entries.data.iterator();
+ const fd = root.entries.fd;
+ while (iter.next()) |entry| {
+ this.next(entry.value, fd);
+ }
+ }
+ }
+
+ while (this.dirs_to_scan.readItem()) |entry| {
+ var dir = std.fs.Dir{ .fd = entry.relative_dir };
+ var parts2 = &[_]string{ entry.dir_path, entry.name.slice() };
+ var path2 = this.fs.absBuf(parts2, &this.open_dir_buf);
+ this.open_dir_buf[path2.len] = 0;
+ var pathZ = this.open_dir_buf[path2.len - entry.name.slice().len .. path2.len :0];
+ var child_dir = dir.openDirZ(pathZ, .{ .iterate = true }) catch continue;
+ path2 = this.fs.dirname_store.append(string, path2) catch unreachable;
+ FileSystem.setMaxFd(child_dir.fd);
+ _ = this.readDirWithName(path2, child_dir) catch continue;
+ }
+ }
+
+ const test_name_suffixes = [_]string{
+ ".test",
+ "_test",
+ ".spec",
+ "_spec",
+ };
+
+ pub fn couldBeTestFile(this: *Scanner, name: string) bool {
+ const extname = std.fs.path.extension(name);
+ if (!this.options.loader(extname).isJavaScriptLike()) return false;
+ const name_without_extension = name[0 .. name.len - extname.len];
+ inline for (test_name_suffixes) |suffix| {
+ if (strings.endsWithComptime(name_without_extension, suffix)) return true;
+ }
+
+ return false;
+ }
+
+ pub fn doesAbsolutePathMatchFilter(this: *Scanner, name: string) bool {
+ if (this.filter_names.len == 0) return true;
+
+ for (this.filter_names) |filter_name| {
+ if (strings.contains(name, filter_name)) return true;
+ }
+
+ return false;
+ }
+
+ pub fn isTestFile(this: *Scanner, name: string) bool {
+ return this.couldBeTestFile(name) and this.doesAbsolutePathMatchFilter(name);
+ }
+
+ pub fn next(this: *Scanner, entry: *FileSystem.Entry, fd: _global.StoredFileDescriptorType) void {
+ const name = entry.base_lowercase();
+ this.has_iterated = true;
+ switch (entry.kind(&this.fs.fs)) {
+ .dir => {
+ if (strings.eqlComptime(name, "node_modules") or strings.eqlComptime(name, ".git")) {
+ return;
+ }
+
+ for (this.exclusion_names) |exclude_name| {
+ if (strings.eql(exclude_name, name)) return;
+ }
+
+ this.dirs_to_scan.writeItem(.{
+ .relative_dir = fd,
+ .name = entry.base_,
+ .dir_path = entry.dir,
+ }) catch unreachable;
+ },
+ .file => {
+ // already seen it!
+ if (!entry.abs_path.isEmpty()) return;
+
+ if (!this.couldBeTestFile(name)) return;
+
+ var parts = &[_]string{ entry.dir, entry.base() };
+ const path = this.fs.absBuf(parts, &this.open_dir_buf);
+
+ if (!this.doesAbsolutePathMatchFilter(path)) return;
+
+ entry.abs_path = _global.PathString.init(this.fs.filename_store.append(@TypeOf(path), path) catch unreachable);
+ this.results.append(entry.abs_path) catch unreachable;
+ },
+ }
+ }
+};
+
+pub const TestCommand = struct {
+ pub const name = "wiptest";
+ pub fn exec(ctx: Command.Context) !void {
+ var env_loader = brk: {
+ var map = try ctx.allocator.create(DotEnv.Map);
+ map.* = DotEnv.Map.init(ctx.allocator);
+
+ var loader = try ctx.allocator.create(DotEnv.Loader);
+ loader.* = DotEnv.Loader.init(map, ctx.allocator);
+ break :brk loader;
+ };
+ JSC.C.JSCInitialize();
+ var reporter = try ctx.allocator.create(CommandLineReporter);
+ reporter.* = CommandLineReporter{
+ .jest = TestRunner{
+ .allocator = ctx.allocator,
+ .log = ctx.log,
+ .callback = undefined,
+ },
+ .callback = undefined,
+ };
+ reporter.callback = TestRunner.Callback{
+ .onUpdateCount = CommandLineReporter.handleUpdateCount,
+ .onTestStart = CommandLineReporter.handleTestStart,
+ .onTestPass = CommandLineReporter.handleTestPass,
+ .onTestFail = CommandLineReporter.handleTestFail,
+ };
+ reporter.jest.callback = &reporter.callback;
+ Jest.Jest.runner = &reporter.jest;
+
+ js_ast.Expr.Data.Store.create(default_allocator);
+ js_ast.Stmt.Data.Store.create(default_allocator);
+ var vm = try JSC.VirtualMachine.init(ctx.allocator, ctx.args, null, ctx.log, env_loader);
+ vm.argv = ctx.positionals;
+
+ try vm.bundler.configureDefines();
+
+ var scanner = Scanner{
+ .dirs_to_scan = Scanner.Fifo.init(ctx.allocator),
+ .options = &vm.bundler.options,
+ .fs = vm.bundler.fs,
+ .filter_names = ctx.positionals[1..],
+ .results = std.ArrayList(PathString).init(ctx.allocator),
+ };
+
+ scanner.scan(scanner.fs.top_level_dir);
+ scanner.dirs_to_scan.deinit();
+
+ const test_files = scanner.results.toOwnedSlice();
+
+ // vm.bundler.fs.fs.readDirectory(_dir: string, _handle: ?std.fs.Dir)
+ runAllTests(reporter, vm, test_files, ctx.allocator);
+
+ Output.pretty("\n", .{});
+ Output.flush();
+
+ Output.prettyError("\n", .{});
+
+ if (reporter.summary.pass > 0) {
+ Output.prettyError("", .{});
+ }
+
+ Output.prettyError(" {d:5>} pass\n", .{reporter.summary.pass});
+
+ if (reporter.summary.fail > 0) {
+ Output.prettyError("", .{});
+ } else {
+ Output.prettyError("", .{});
+ }
+
+ Output.prettyError(" {d:5>} fail\n", .{reporter.summary.fail});
+
+ if (reporter.summary.fail == 0 and reporter.summary.expectations > 0) {
+ Output.prettyError("", .{});
+ } else {
+ Output.prettyError("", .{});
+ }
+ Output.prettyError(" {d:5>} expectations\n", .{reporter.summary.expectations});
+
+ Output.prettyError(
+ \\ Ran {d} tests across {d} files
+ , .{
+ reporter.summary.fail + reporter.summary.pass,
+ test_files.len,
+ });
+ Output.printStartEnd(ctx.start_time, std.time.nanoTimestamp());
+ Output.prettyError("\n", .{});
+
+ Output.flush();
+
+ if (reporter.summary.fail > 0) {
+ std.os.exit(1);
+ }
+ }
+
+ pub fn runAllTests(
+ reporter_: *CommandLineReporter,
+ vm_: *JSC.VirtualMachine,
+ files_: []const PathString,
+ allocator_: std.mem.Allocator,
+ ) void {
+ const Context = struct {
+ reporter: *CommandLineReporter,
+ vm: *JSC.VirtualMachine,
+ files: []const PathString,
+ allocator: std.mem.Allocator,
+ pub fn begin(this: *@This()) void {
+ var reporter = this.reporter;
+ var vm = this.vm;
+ var files = this.files;
+ var allocator = this.allocator;
+ for (files) |file_name| {
+ TestCommand.run(reporter, vm, file_name.slice(), allocator) catch {};
+ }
+ }
+ };
+ var ctx = Context{ .reporter = reporter_, .vm = vm_, .files = files_, .allocator = allocator_ };
+ vm_.runWithAPILock(Context, &ctx, Context.begin);
+ }
+
+ pub fn run(
+ reporter: *CommandLineReporter,
+ vm: *JSC.VirtualMachine,
+ file_name: string,
+ _: std.mem.Allocator,
+ ) !void {
+ defer {
+ js_ast.Expr.Data.Store.reset();
+ js_ast.Stmt.Data.Store.reset();
+
+ if (vm.log.errors > 0) {
+ if (Output.enable_ansi_colors) {
+ vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
+ } else {
+ vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
+ }
+ vm.log.msgs.clearRetainingCapacity();
+ vm.log.errors = 0;
+ }
+
+ Output.flush();
+ }
+
+ var file_start = reporter.jest.files.len;
+ var resolution = try vm.bundler.resolveEntryPoint(file_name);
+
+ var promise = try vm.loadEntryPoint(resolution.path_pair.primary.text);
+
+ while (promise.status(vm.global.vm()) == .Pending) {
+ vm.tick();
+ }
+
+ var result = promise.result(vm.global.vm());
+ if (result.isError() or
+ result.isAggregateError(vm.global) or
+ result.isException(vm.global.vm()))
+ {
+ vm.defaultErrorHandler(result, null);
+ }
+
+ reporter.updateDots();
+
+ var modules: []*Jest.DescribeScope = reporter.jest.files.items(.module_scope)[file_start..];
+ for (modules) |module| {
+ module.runTests(vm.global.ref());
+ }
+
+ reporter.updateDots();
+ }
+};
diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig
index 3f6a4840d2..672afb8c48 100644
--- a/src/cli/upgrade_command.zig
+++ b/src/cli/upgrade_command.zig
@@ -91,13 +91,12 @@ pub const UpgradeCheckerThread = struct {
Output.Source.configureThread();
NetworkThread.init() catch unreachable;
+
defer {
js_ast.Expr.Data.Store.deinit();
js_ast.Stmt.Data.Store.deinit();
}
- var arena = std.heap.ArenaAllocator.init(default_allocator);
- defer arena.deinit();
- const version = (try UpgradeCommand.getLatestVersion(arena.allocator(), env_loader, undefined, undefined, true)) orelse return;
+ var version = (try UpgradeCommand.getLatestVersion(default_allocator, env_loader, undefined, undefined, true)) orelse return;
if (!version.isCurrent()) {
if (version.name()) |name| {
@@ -105,6 +104,8 @@ pub const UpgradeCheckerThread = struct {
Output.flush();
}
}
+
+ version.buf.deinit();
}
fn run(env_loader: *DotEnv.Loader) void {
@@ -118,7 +119,7 @@ pub const UpgradeCheckerThread = struct {
pub const UpgradeCommand = struct {
pub const timeout: u32 = 30000;
- const default_github_headers = "Acceptapplication/vnd.github.v3+json";
+ const default_github_headers: string = "Acceptapplication/vnd.github.v3+json";
var github_repository_url_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var current_executable_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var unzip_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
@@ -132,6 +133,12 @@ pub const UpgradeCommand = struct {
comptime silent: bool,
) !?Version {
var headers_buf: string = default_github_headers;
+ // gonna have to free memory myself like a goddamn caveman due to a thread safety issue with ArenaAllocator
+ defer {
+ if (comptime silent) {
+ if (headers_buf.ptr != default_github_headers.ptr) allocator.free(headers_buf);
+ }
+ }
var header_entries: Headers.Entries = .{};
const accept = Headers.Kv{
@@ -139,6 +146,7 @@ pub const UpgradeCommand = struct {
.value = Api.StringPointer{ .offset = @intCast(u32, "Accept".len), .length = @intCast(u32, "application/vnd.github.v3+json".len) },
};
try header_entries.append(allocator, accept);
+ defer if (comptime silent) header_entries.deinit(allocator);
// Incase they're using a GitHub proxy in e.g. China
var github_api_domain: string = "api.github.com";
@@ -196,6 +204,7 @@ pub const UpgradeCommand = struct {
}
var log = logger.Log.init(allocator);
+ defer if (comptime silent) log.deinit();
var source = logger.Source.initPathString("releases.json", metadata_body.list.items);
initializeStore();
var expr = ParseJSON(&source, &log, allocator) catch |err| {
@@ -326,8 +335,6 @@ pub const UpgradeCommand = struct {
std.os.exit(0);
}
- version.buf.deinit();
-
return null;
}
const exe_subpath = Version.folder_name ++ std.fs.path.sep_str ++ "bun";
diff --git a/src/darwin_c.zig b/src/darwin_c.zig
index e227ee8bfd..e92312d74c 100644
--- a/src/darwin_c.zig
+++ b/src/darwin_c.zig
@@ -9,6 +9,62 @@ const off_t = std.c.off_t;
const errno = os.errno;
const zeroes = mem.zeroes;
+pub extern "c" fn copyfile(from: [*:0]const u8, to: [*:0]const u8, state: ?std.c.copyfile_state_t, flags: u32) c_int;
+pub const COPYFILE_STATE_SRC_FD = @as(c_int, 1);
+pub const COPYFILE_STATE_SRC_FILENAME = @as(c_int, 2);
+pub const COPYFILE_STATE_DST_FD = @as(c_int, 3);
+pub const COPYFILE_STATE_DST_FILENAME = @as(c_int, 4);
+pub const COPYFILE_STATE_QUARANTINE = @as(c_int, 5);
+pub const COPYFILE_STATE_STATUS_CB = @as(c_int, 6);
+pub const COPYFILE_STATE_STATUS_CTX = @as(c_int, 7);
+pub const COPYFILE_STATE_COPIED = @as(c_int, 8);
+pub const COPYFILE_STATE_XATTRNAME = @as(c_int, 9);
+pub const COPYFILE_STATE_WAS_CLONED = @as(c_int, 10);
+pub const COPYFILE_DISABLE_VAR = "COPYFILE_DISABLE";
+pub const COPYFILE_ACL = @as(c_int, 1) << @as(c_int, 0);
+pub const COPYFILE_STAT = @as(c_int, 1) << @as(c_int, 1);
+pub const COPYFILE_XATTR = @as(c_int, 1) << @as(c_int, 2);
+pub const COPYFILE_DATA = @as(c_int, 1) << @as(c_int, 3);
+pub const COPYFILE_SECURITY = COPYFILE_STAT | COPYFILE_ACL;
+pub const COPYFILE_METADATA = COPYFILE_SECURITY | COPYFILE_XATTR;
+pub const COPYFILE_ALL = COPYFILE_METADATA | COPYFILE_DATA;
+/// Descend into hierarchies
+pub const COPYFILE_RECURSIVE = @as(c_int, 1) << @as(c_int, 15);
+/// return flags for xattr or acls if set
+pub const COPYFILE_CHECK = @as(c_int, 1) << @as(c_int, 16);
+/// fail if destination exists
+pub const COPYFILE_EXCL = @as(c_int, 1) << @as(c_int, 17);
+/// don't follow if source is a symlink
+pub const COPYFILE_NOFOLLOW_SRC = @as(c_int, 1) << @as(c_int, 18);
+/// don't follow if dst is a symlink
+pub const COPYFILE_NOFOLLOW_DST = @as(c_int, 1) << @as(c_int, 19);
+/// unlink src after copy
+pub const COPYFILE_MOVE = @as(c_int, 1) << @as(c_int, 20);
+/// unlink dst before copy
+pub const COPYFILE_UNLINK = @as(c_int, 1) << @as(c_int, 21);
+pub const COPYFILE_NOFOLLOW = COPYFILE_NOFOLLOW_SRC | COPYFILE_NOFOLLOW_DST;
+pub const COPYFILE_PACK = @as(c_int, 1) << @as(c_int, 22);
+pub const COPYFILE_UNPACK = @as(c_int, 1) << @as(c_int, 23);
+pub const COPYFILE_CLONE = @as(c_int, 1) << @as(c_int, 24);
+pub const COPYFILE_CLONE_FORCE = @as(c_int, 1) << @as(c_int, 25);
+pub const COPYFILE_RUN_IN_PLACE = @as(c_int, 1) << @as(c_int, 26);
+pub const COPYFILE_DATA_SPARSE = @as(c_int, 1) << @as(c_int, 27);
+pub const COPYFILE_PRESERVE_DST_TRACKED = @as(c_int, 1) << @as(c_int, 28);
+pub const COPYFILE_VERBOSE = @as(c_int, 1) << @as(c_int, 30);
+pub const COPYFILE_RECURSE_ERROR = @as(c_int, 0);
+pub const COPYFILE_RECURSE_FILE = @as(c_int, 1);
+pub const COPYFILE_RECURSE_DIR = @as(c_int, 2);
+pub const COPYFILE_RECURSE_DIR_CLEANUP = @as(c_int, 3);
+pub const COPYFILE_COPY_DATA = @as(c_int, 4);
+pub const COPYFILE_COPY_XATTR = @as(c_int, 5);
+pub const COPYFILE_START = @as(c_int, 1);
+pub const COPYFILE_FINISH = @as(c_int, 2);
+pub const COPYFILE_ERR = @as(c_int, 3);
+pub const COPYFILE_PROGRESS = @as(c_int, 4);
+pub const COPYFILE_CONTINUE = @as(c_int, 0);
+pub const COPYFILE_SKIP = @as(c_int, 1);
+pub const COPYFILE_QUIT = @as(c_int, 2);
+
// int clonefileat(int src_dirfd, const char * src, int dst_dirfd, const char * dst, int flags);
pub extern "c" fn clonefileat(c_int, [*c]const u8, c_int, [*c]const u8, uint32_t: c_int) c_int;
// int fclonefileat(int srcfd, int dst_dirfd, const char * dst, int flags);
@@ -117,3 +173,295 @@ pub fn preallocate_file(fd: os.fd_t, offset: off_t, len: off_t) !void {
std.mem.doNotOptimizeAway(&fstore);
}
+
+pub const SystemErrno = enum(u8) {
+ SUCCESS = 0,
+ EPERM = 1,
+ ENOENT = 2,
+ ESRCH = 3,
+ EINTR = 4,
+ EIO = 5,
+ ENXIO = 6,
+ E2BIG = 7,
+ ENOEXEC = 8,
+ EBADF = 9,
+ ECHILD = 10,
+ EDEADLK = 11,
+ ENOMEM = 12,
+ EACCES = 13,
+ EFAULT = 14,
+ ENOTBLK = 15,
+ EBUSY = 16,
+ EEXIST = 17,
+ EXDEV = 18,
+ ENODEV = 19,
+ ENOTDIR = 20,
+ EISDIR = 21,
+ EINVAL = 22,
+ ENFILE = 23,
+ EMFILE = 24,
+ ENOTTY = 25,
+ ETXTBSY = 26,
+ EFBIG = 27,
+ ENOSPC = 28,
+ ESPIPE = 29,
+ EROFS = 30,
+ EMLINK = 31,
+ EPIPE = 32,
+ EDOM = 33,
+ ERANGE = 34,
+ EAGAIN = 35,
+ EINPROGRESS = 36,
+ EALREADY = 37,
+ ENOTSOCK = 38,
+ EDESTADDRREQ = 39,
+ EMSGSIZE = 40,
+ EPROTOTYPE = 41,
+ ENOPROTOOPT = 42,
+ EPROTONOSUPPORT = 43,
+ ESOCKTNOSUPPORT = 44,
+ ENOTSUP = 45,
+ EPFNOSUPPORT = 46,
+ EAFNOSUPPORT = 47,
+ EADDRINUSE = 48,
+ EADDRNOTAVAIL = 49,
+ ENETDOWN = 50,
+ ENETUNREACH = 51,
+ ENETRESET = 52,
+ ECONNABORTED = 53,
+ ECONNRESET = 54,
+ ENOBUFS = 55,
+ EISCONN = 56,
+ ENOTCONN = 57,
+ ESHUTDOWN = 58,
+ ETOOMANYREFS = 59,
+ ETIMEDOUT = 60,
+ ECONNREFUSED = 61,
+ ELOOP = 62,
+ ENAMETOOLONG = 63,
+ EHOSTDOWN = 64,
+ EHOSTUNREACH = 65,
+ ENOTEMPTY = 66,
+ EPROCLIM = 67,
+ EUSERS = 68,
+ EDQUOT = 69,
+ ESTALE = 70,
+ EREMOTE = 71,
+ EBADRPC = 72,
+ ERPCMISMATCH = 73,
+ EPROGUNAVAIL = 74,
+ EPROGMISMATCH = 75,
+ EPROCUNAVAIL = 76,
+ ENOLCK = 77,
+ ENOSYS = 78,
+ EFTYPE = 79,
+ EAUTH = 80,
+ ENEEDAUTH = 81,
+ EPWROFF = 82,
+ EDEVERR = 83,
+ EOVERFLOW = 84,
+ EBADEXEC = 85,
+ EBADARCH = 86,
+ ESHLIBVERS = 87,
+ EBADMACHO = 88,
+ ECANCELED = 89,
+ EIDRM = 90,
+ ENOMSG = 91,
+ EILSEQ = 92,
+ ENOATTR = 93,
+ EBADMSG = 94,
+ EMULTIHOP = 95,
+ ENODATA = 96,
+ ENOLINK = 97,
+ ENOSR = 98,
+ ENOSTR = 99,
+ EPROTO = 100,
+ ETIME = 101,
+ EOPNOTSUPP = 102,
+ ENOPOLICY = 103,
+ ENOTRECOVERABLE = 104,
+ EOWNERDEAD = 105,
+ EQFULL = 106,
+
+ pub const max = 107;
+
+ const LabelMap = std.EnumMap(SystemErrno, []const u8);
+ pub const labels: LabelMap = brk: {
+ var map: LabelMap = LabelMap.initFull("");
+ map.put(.E2BIG, "Argument list too long");
+ map.put(.EACCES, "Permission denied");
+ map.put(.EADDRINUSE, "Address already in use");
+ map.put(.EADDRNOTAVAIL, "Can’t assign requested address");
+ map.put(.EAFNOSUPPORT, "Address family not supported by protocol family");
+ map.put(.EAGAIN, "non-blocking and interrupt i/o. Resource temporarily unavailable");
+ map.put(.EALREADY, "Operation already in progress");
+ map.put(.EAUTH, "Authentication error");
+ map.put(.EBADARCH, "Bad CPU type in executable");
+ map.put(.EBADEXEC, "Program loading errors. Bad executable");
+ map.put(.EBADF, "Bad file descriptor");
+ map.put(.EBADMACHO, "Malformed Macho file");
+ map.put(.EBADMSG, "Bad message");
+ map.put(.EBADRPC, "RPC struct is bad");
+ map.put(.EBUSY, "Device / Resource busy");
+ map.put(.ECANCELED, "Operation canceled");
+ map.put(.ECHILD, "No child processes");
+ map.put(.ECONNABORTED, "Software caused connection abort");
+ map.put(.ECONNREFUSED, "Connection refused");
+ map.put(.ECONNRESET, "Connection reset by peer");
+ map.put(.EDEADLK, "Resource deadlock avoided");
+ map.put(.EDESTADDRREQ, "Destination address required");
+ map.put(.EDEVERR, "Device error, for example paper out");
+ map.put(.EDOM, "math software. Numerical argument out of domain");
+ map.put(.EDQUOT, "Disc quota exceeded");
+ map.put(.EEXIST, "File or folder exists");
+ map.put(.EFAULT, "Bad address");
+ map.put(.EFBIG, "File too large");
+ map.put(.EFTYPE, "Inappropriate file type or format");
+ map.put(.EHOSTDOWN, "Host is down");
+ map.put(.EHOSTUNREACH, "No route to host");
+ map.put(.EIDRM, "Identifier removed");
+ map.put(.EILSEQ, "Illegal byte sequence");
+ map.put(.EINPROGRESS, "Operation now in progress");
+ map.put(.EINTR, "Interrupted system call");
+ map.put(.EINVAL, "Invalid argument");
+ map.put(.EIO, "Input/output error");
+ map.put(.EISCONN, "Socket is already connected");
+ map.put(.EISDIR, "Is a directory");
+ map.put(.ELOOP, "Too many levels of symbolic links");
+ map.put(.EMFILE, "Too many open files");
+ map.put(.EMLINK, "Too many links");
+ map.put(.EMSGSIZE, "Message too long");
+ map.put(.EMULTIHOP, "Reserved");
+ map.put(.ENAMETOOLONG, "File name too long");
+ map.put(.ENEEDAUTH, "Need authenticator");
+ map.put(.ENETDOWN, "ipc/network software – operational errors Network is down");
+ map.put(.ENETRESET, "Network dropped connection on reset");
+ map.put(.ENETUNREACH, "Network is unreachable");
+ map.put(.ENFILE, "Too many open files in system");
+ map.put(.ENOATTR, "Attribute not found");
+ map.put(.ENOBUFS, "No buffer space available");
+ map.put(.ENODATA, "No message available on STREAM");
+ map.put(.ENODEV, "Operation not supported by device");
+ map.put(.ENOENT, "No such file or directory");
+ map.put(.ENOEXEC, "Exec format error");
+ map.put(.ENOLCK, "No locks available");
+ map.put(.ENOLINK, "Reserved");
+ map.put(.ENOMEM, "Cannot allocate memory");
+ map.put(.ENOMSG, "No message of desired type");
+ map.put(.ENOPOLICY, "No such policy registered");
+ map.put(.ENOPROTOOPT, "Protocol not available");
+ map.put(.ENOSPC, "No space left on device");
+ map.put(.ENOSR, "No STREAM resources");
+ map.put(.ENOSTR, "Not a STREAM");
+ map.put(.ENOSYS, "Function not implemented");
+ map.put(.ENOTBLK, "Block device required");
+ map.put(.ENOTCONN, "Socket is not connected");
+ map.put(.ENOTDIR, "Not a directory");
+ map.put(.ENOTEMPTY, "Directory not empty");
+ map.put(.ENOTRECOVERABLE, "State not recoverable");
+ map.put(.ENOTSOCK, "ipc/network software – argument errors. Socket operation on non-socket");
+ map.put(.ENOTSUP, "Operation not supported");
+ map.put(.ENOTTY, "Inappropriate ioctl for device");
+ map.put(.ENXIO, "Device not configured");
+ map.put(.EOVERFLOW, "Value too large to be stored in data type");
+ map.put(.EOWNERDEAD, "Previous owner died");
+ map.put(.EPERM, "Operation not permitted");
+ map.put(.EPFNOSUPPORT, "Protocol family not supported");
+ map.put(.EPIPE, "Broken pipe");
+ map.put(.EPROCLIM, "quotas & mush. Too many processes");
+ map.put(.EPROCUNAVAIL, "Bad procedure for program");
+ map.put(.EPROGMISMATCH, "Program version wrong");
+ map.put(.EPROGUNAVAIL, "RPC prog. not avail");
+ map.put(.EPROTO, "Protocol error");
+ map.put(.EPROTONOSUPPORT, "Protocol not supported");
+ map.put(.EPROTOTYPE, "Protocol wrong type for socket");
+ map.put(.EPWROFF, "Intelligent device errors. Device power is off");
+ map.put(.EQFULL, "Interface output queue is full");
+ map.put(.ERANGE, "Result too large");
+ map.put(.EREMOTE, "Too many levels of remote in path");
+ map.put(.EROFS, "Read-only file system");
+ map.put(.ERPCMISMATCH, "RPC version wrong");
+ map.put(.ESHLIBVERS, "Shared library version mismatch");
+ map.put(.ESHUTDOWN, "Can’t send after socket shutdown");
+ map.put(.ESOCKTNOSUPPORT, "Socket type not supported");
+ map.put(.ESPIPE, "Illegal seek");
+ map.put(.ESRCH, "No such process");
+ map.put(.ESTALE, "Network File System. Stale NFS file handle");
+ map.put(.ETIME, "STREAM ioctl timeout");
+ map.put(.ETIMEDOUT, "Operation timed out");
+ map.put(.ETOOMANYREFS, "Too many references: can’t splice");
+ map.put(.ETXTBSY, "Text file busy");
+ map.put(.EUSERS, "Too many users");
+ // map.put(.EWOULDBLOCK, "Operation would block");
+ map.put(.EXDEV, "Cross-device link");
+ break :brk map;
+ };
+};
+
+// Courtesy of https://github.com/nodejs/node/blob/master/deps/uv/src/unix/darwin-stub.h
+pub const struct_CFArrayCallBacks = opaque {};
+pub const CFIndex = c_long;
+pub const struct_CFRunLoopSourceContext = extern struct {
+ version: CFIndex,
+ info: ?*anyopaque,
+ pad: [7]?*anyopaque,
+ perform: ?fn (?*anyopaque) callconv(.C) void,
+};
+pub const struct_FSEventStreamContext = extern struct {
+ version: CFIndex,
+ info: ?*anyopaque,
+ pad: [3]?*anyopaque,
+};
+pub const struct_CFRange = extern struct {
+ location: CFIndex,
+ length: CFIndex,
+};
+pub const CFAbsoluteTime = f64;
+pub const CFTimeInterval = f64;
+pub const FSEventStreamEventFlags = c_int;
+pub const OSStatus = c_int;
+pub const CFArrayCallBacks = struct_CFArrayCallBacks;
+pub const CFRunLoopSourceContext = struct_CFRunLoopSourceContext;
+pub const FSEventStreamContext = struct_FSEventStreamContext;
+pub const FSEventStreamCreateFlags = u32;
+pub const FSEventStreamEventId = u64;
+pub const CFStringEncoding = c_uint;
+pub const CFAllocatorRef = ?*anyopaque;
+pub const CFArrayRef = ?*anyopaque;
+pub const CFBundleRef = ?*anyopaque;
+pub const CFDataRef = ?*anyopaque;
+pub const CFDictionaryRef = ?*anyopaque;
+pub const CFMutableDictionaryRef = ?*anyopaque;
+pub const CFRange = struct_CFRange;
+pub const CFRunLoopRef = ?*anyopaque;
+pub const CFRunLoopSourceRef = ?*anyopaque;
+pub const CFStringRef = ?*anyopaque;
+pub const CFTypeRef = ?*anyopaque;
+pub const FSEventStreamRef = ?*anyopaque;
+pub const IOOptionBits = u32;
+pub const io_iterator_t = c_uint;
+pub const io_object_t = c_uint;
+pub const io_service_t = c_uint;
+pub const io_registry_entry_t = c_uint;
+pub const FSEventStreamCallback = ?fn (FSEventStreamRef, ?*anyopaque, c_int, ?*anyopaque, [*c]const FSEventStreamEventFlags, [*c]const FSEventStreamEventId) callconv(.C) void;
+pub const kCFStringEncodingUTF8: CFStringEncoding = @bitCast(CFStringEncoding, @as(c_int, 134217984));
+pub const noErr: OSStatus = 0;
+pub const kFSEventStreamEventIdSinceNow: FSEventStreamEventId = @bitCast(FSEventStreamEventId, @as(c_longlong, -@as(c_int, 1)));
+pub const kFSEventStreamCreateFlagNoDefer: c_int = 2;
+pub const kFSEventStreamCreateFlagFileEvents: c_int = 16;
+pub const kFSEventStreamEventFlagEventIdsWrapped: c_int = 8;
+pub const kFSEventStreamEventFlagHistoryDone: c_int = 16;
+pub const kFSEventStreamEventFlagItemChangeOwner: c_int = 16384;
+pub const kFSEventStreamEventFlagItemCreated: c_int = 256;
+pub const kFSEventStreamEventFlagItemFinderInfoMod: c_int = 8192;
+pub const kFSEventStreamEventFlagItemInodeMetaMod: c_int = 1024;
+pub const kFSEventStreamEventFlagItemIsDir: c_int = 131072;
+pub const kFSEventStreamEventFlagItemModified: c_int = 4096;
+pub const kFSEventStreamEventFlagItemRemoved: c_int = 512;
+pub const kFSEventStreamEventFlagItemRenamed: c_int = 2048;
+pub const kFSEventStreamEventFlagItemXattrMod: c_int = 32768;
+pub const kFSEventStreamEventFlagKernelDropped: c_int = 4;
+pub const kFSEventStreamEventFlagMount: c_int = 64;
+pub const kFSEventStreamEventFlagRootChanged: c_int = 32;
+pub const kFSEventStreamEventFlagUnmount: c_int = 128;
+pub const kFSEventStreamEventFlagUserDropped: c_int = 2;
diff --git a/src/deps/PLCrashReport.bindings.h b/src/deps/PLCrashReport.bindings.h
deleted file mode 100644
index 2fbfc9bacb..0000000000
--- a/src/deps/PLCrashReport.bindings.h
+++ /dev/null
@@ -1,10 +0,0 @@
-#include
-#include
-
-extern bool PLCrashReportStart(const char *version, const char *basePath);
-extern void PLCrashReportHandler(void *context);
-
-extern void PLCrashReportGenerate();
-extern void *PLCrashReportLoadPending();
-
-extern uint16_t copyCrashReportPath(char *buf[1024]);
diff --git a/src/deps/PLCrashReport.m b/src/deps/PLCrashReport.m
deleted file mode 100644
index ecd0994244..0000000000
--- a/src/deps/PLCrashReport.m
+++ /dev/null
@@ -1,74 +0,0 @@
-#include "PLCrashReport.bindings.h"
-
-#include
-
-NSString *crash_folder;
-
-@interface PLCrashReporter (PrivateMethods)
-
-- (id)initWithApplicationIdentifier:(NSString *)applicationIdentifier
- appVersion:(NSString *)applicationVersion
- appMarketingVersion:(NSString *)applicationMarketingVersion
- configuration:(PLCrashReporterConfig *)configuration;
-
-@end
-
-void pl_crash_reporter_post_crash_callback(siginfo_t *info, ucontext_t *uap,
- void *context) {
- PLCrashReportHandler(context);
-}
-
-static PLCrashReporter *reporter;
-
-NSString *v;
-NSString *basePath_;
-static void *handler;
-bool PLCrashReportStart(const char *version, const char *basePath) {
- PLCrashReporterConfig *config;
- basePath_ = [NSString stringWithUTF8String:basePath];
-
- handler = &pl_crash_reporter_post_crash_callback;
- PLCrashReporterCallbacks callbacks = {
- .version = 0, .context = NULL, .handleSignal = handler};
- config = [[PLCrashReporterConfig alloc]
- initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeBSD
- symbolicationStrategy:
- PLCrashReporterSymbolicationStrategyNone
- shouldRegisterUncaughtExceptionHandler:YES
- basePath:basePath_];
-
- v = [[NSString alloc] initWithBytesNoCopy:version
- length:strlen(version)
- encoding:NSUTF8StringEncoding
- freeWhenDone:NO];
- reporter = [[PLCrashReporter alloc] initWithApplicationIdentifier:@"bun"
- appVersion:v
- appMarketingVersion:v
- configuration:config];
-
- [reporter setValue:basePath_ forKey:@"_crashReportDirectory"];
- [reporter setCrashCallbacks:&callbacks];
-
- return [reporter enableCrashReporter];
-}
-
-void PLCrashReportGenerate() { [reporter generateLiveReport]; }
-void *PLCrashReportLoadPending() {
- return [reporter loadPendingCrashReportData];
-}
-
-uint16_t copyCrashReportPath(char *buf[1024]) {
- NSString *crashReportPath = [reporter crashReportPath];
- [crashReportPath getBytes:buf
- maxLength:(1024 - 1)
- usedLength:NULL
- encoding:NSUTF8StringEncoding
- options:0
- range:NSMakeRange(0, [crashReportPath length])
- remainingRange:NULL];
- size_t len = [crashReportPath length];
- if (len > 1024) {
- len = 0;
- }
- return (uint16_t)len;
-}
diff --git a/src/deps/PLCrashReport.zig b/src/deps/PLCrashReport.zig
deleted file mode 100644
index 9625cf4414..0000000000
--- a/src/deps/PLCrashReport.zig
+++ /dev/null
@@ -1,42 +0,0 @@
-const root = @import("root");
-const std = @import("std");
-
-extern fn PLCrashReportStart(version: [*:0]const u8, base_path: [*:0]const u8) bool;
-extern fn PLCrashReportGenerate() void;
-extern fn PLCrashReportLoadPending() ?*anyopaque;
-extern fn copyCrashReportPath(buf: *[1024]u8) u16;
-
-pub export fn PLCrashReportHandler(_: ?*anyopaque) void {
- root.PLCrashReportHandler();
-}
-
-pub fn start(
- comptime version: [*:0]const u8,
-) bool {
- has_started = true;
- var base_path_buf: [1024]u8 = undefined;
- var base_path: [:0]const u8 = "";
- const crash_path = "/crash/" ++ version ++ "/";
- if (std.os.getenvZ("BUN_INSTALL")) |bun_install| {
- @memcpy(&base_path_buf, bun_install.ptr, bun_install.len);
- std.mem.copy(u8, base_path_buf[bun_install.len..], crash_path);
- base_path_buf[bun_install.len + crash_path.len] = 0;
- base_path = base_path_buf[0 .. bun_install.len + crash_path.len :0];
- } else {
- base_path = "/tmp/bun" ++ crash_path;
- base_path_buf["/tmp/bun".len + crash_path.len] = 0;
- }
- return PLCrashReportStart(version, base_path.ptr);
-}
-
-pub fn generate() void {
- return PLCrashReportGenerate();
-}
-var has_started = false;
-
-pub fn crashReportPath(buf: *[1024]u8) []const u8 {
- if (!has_started) return "";
-
- const len = copyCrashReportPath(buf);
- return buf[0..len];
-}
diff --git a/src/deps/backtrace.zig b/src/deps/backtrace.zig
new file mode 100644
index 0000000000..8448642de6
--- /dev/null
+++ b/src/deps/backtrace.zig
@@ -0,0 +1,159 @@
+pub const backtrace_state = struct_backtrace_state;
+pub const struct_backtrace_state = opaque {};
+pub const backtrace_error_callback = ?fn (
+ ?*anyopaque,
+ [*c]const u8,
+ c_int,
+) callconv(.C) void;
+pub extern fn backtrace_create_state(
+ filename: [*c]const u8,
+ threaded: c_int,
+ error_callback: backtrace_error_callback,
+ data: ?*anyopaque,
+) ?*struct_backtrace_state;
+pub const backtrace_full_callback = ?fn (
+ ?*anyopaque,
+ usize,
+ [*c]const u8,
+ c_int,
+ [*c]const u8,
+) callconv(.C) c_int;
+pub extern fn backtrace_full(
+ state: ?*struct_backtrace_state,
+ skip: c_int,
+ callback: backtrace_full_callback,
+ error_callback: backtrace_error_callback,
+ data: ?*anyopaque,
+) c_int;
+pub const backtrace_simple_callback = ?fn (?*anyopaque, usize) callconv(.C) c_int;
+pub extern fn backtrace_simple(
+ state: ?*struct_backtrace_state,
+ skip: c_int,
+ callback: backtrace_simple_callback,
+ error_callback: backtrace_error_callback,
+ data: ?*anyopaque,
+) c_int;
+pub extern fn backtrace_print(state: ?*struct_backtrace_state, skip: c_int, [*c]anyopaque) void;
+pub extern fn backtrace_pcinfo(
+ state: ?*struct_backtrace_state,
+ pc: usize,
+ callback: backtrace_full_callback,
+ error_callback: backtrace_error_callback,
+ data: ?*anyopaque,
+) c_int;
+pub const backtrace_syminfo_callback = ?fn (?*anyopaque, usize, [*c]const u8, usize, usize) callconv(.C) void;
+pub extern fn backtrace_syminfo(
+ state: ?*struct_backtrace_state,
+ addr: usize,
+ callback: backtrace_syminfo_callback,
+ error_callback: backtrace_error_callback,
+ data: ?*anyopaque,
+) c_int;
+
+pub const BACKTRACE_SUPPORTED = @as(c_int, 1);
+pub const BACKTRACE_USES_MALLOC = @as(c_int, 0);
+pub const BACKTRACE_SUPPORTS_THREADS = @as(c_int, 1);
+pub const BACKTRACE_SUPPORTS_DATA = @as(c_int, 1);
+
+fn error_callback(data: *anyopaque, msg: [*c]u8, errnum: c_int) callconv(.C) void {
+ _ = data;
+ _ = msg;
+ _ = errnum;
+}
+
+pub const StackFrame = struct {
+ pc: usize,
+ filename: []const u8,
+ function_name: []const u8,
+ line_number: c_int,
+};
+
+pub const PrintCallback = fn (ctx: ?*anyopaque, frame: StackFrame) void;
+
+var callback: PrintCallback = undefined;
+var callback_ctx: ?*anyopaque = null;
+
+const std = @import("std");
+
+noinline fn full_callback(_: ?*anyopaque, pc: usize, filename: [*c]const u8, line_number: c_int, function_name: [*c]const u8) callconv(.C) c_int {
+ var stack_frame = StackFrame{
+ .pc = pc,
+ .line_number = line_number,
+ .function_name = if (function_name) |fn_| std.mem.span(fn_) else "",
+ .filename = if (filename) |fn_| std.mem.span(fn_) else "",
+ };
+ callback(callback_ctx, stack_frame);
+ return 0;
+}
+
+var state: ?*backtrace_state = null;
+pub inline fn print() void {
+ state = backtrace_create_state(null, BACKTRACE_SUPPORTS_THREADS, null, null);
+ _ = backtrace_full(state, 2, full_callback, null, null);
+}
+
+const builtin = @import("builtin");
+const ErrorCallback = fn (sig: i32, addr: usize) void;
+var on_error: ?ErrorCallback = null;
+noinline fn sigaction_handler(sig: i32, info: *const std.os.siginfo_t, _: ?*const anyopaque) callconv(.C) void {
+ // Prevent recursive calls
+ os.sigaction(os.SIG.ABRT, null, null);
+ os.sigaction(os.SIG.BUS, null, null);
+ os.sigaction(os.SIG.FPE, null, null);
+ os.sigaction(os.SIG.ILL, null, null);
+ os.sigaction(os.SIG.SEGV, null, null);
+ os.sigaction(os.SIG.TRAP, null, null);
+
+ const addr = switch (comptime builtin.target.os.tag) {
+ .linux => @ptrToInt(info.fields.sigfault.addr),
+ .macos, .freebsd => @ptrToInt(info.addr),
+ .netbsd => @ptrToInt(info.info.reason.fault.addr),
+ .openbsd => @ptrToInt(info.data.fault.addr),
+ .solaris => @ptrToInt(info.reason.fault.addr),
+ else => unreachable,
+ };
+ if (on_error) |handle| handle(sig, addr);
+}
+
+pub fn reloadHandlers() void {
+ os.sigaction(os.SIG.ABRT, null, null);
+ os.sigaction(os.SIG.BUS, null, null);
+ os.sigaction(os.SIG.FPE, null, null);
+ os.sigaction(os.SIG.ILL, null, null);
+ os.sigaction(os.SIG.SEGV, null, null);
+ os.sigaction(os.SIG.TRAP, null, null);
+
+ var act = os.Sigaction{
+ .handler = .{ .sigaction = sigaction_handler },
+ .mask = os.empty_sigset,
+ .flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND),
+ };
+
+ os.sigaction(os.SIG.ABRT, &act, null);
+ os.sigaction(os.SIG.BUS, &act, null);
+ os.sigaction(os.SIG.FPE, &act, null);
+ os.sigaction(os.SIG.ILL, &act, null);
+ os.sigaction(os.SIG.SEGV, &act, null);
+ os.sigaction(os.SIG.TRAP, &act, null);
+}
+const os = std.os;
+pub fn start(ctx: ?*anyopaque, callback_: PrintCallback, onError: ErrorCallback) bool {
+ callback_ctx = ctx;
+ callback = callback_;
+ on_error = onError;
+
+ var act = os.Sigaction{
+ .handler = .{ .sigaction = sigaction_handler },
+ .mask = os.empty_sigset,
+ .flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND),
+ };
+
+ os.sigaction(os.SIG.ABRT, &act, null);
+ os.sigaction(os.SIG.BUS, &act, null);
+ os.sigaction(os.SIG.FPE, &act, null);
+ os.sigaction(os.SIG.ILL, &act, null);
+ os.sigaction(os.SIG.SEGV, &act, null);
+ os.sigaction(os.SIG.TRAP, &act, null);
+
+ return true;
+}
diff --git a/src/deps/libbacktrace b/src/deps/libbacktrace
new file mode 160000
index 0000000000..d0f5e95a87
--- /dev/null
+++ b/src/deps/libbacktrace
@@ -0,0 +1 @@
+Subproject commit d0f5e95a87a4d3e0a1ed6c069b5dae7cbab3ed2a
diff --git a/src/deps/mimalloc b/src/deps/mimalloc
index f412df7a2b..d2e727f0e8 160000
--- a/src/deps/mimalloc
+++ b/src/deps/mimalloc
@@ -1 +1 @@
-Subproject commit f412df7a2b64421e1f1d61fde6055a6ea288e8f5
+Subproject commit d2e727f0e871cd35305bdb7bc3983cf607441752
diff --git a/src/exact_size_matcher.zig b/src/exact_size_matcher.zig
index 19fbb51387..011adb7f8b 100644
--- a/src/exact_size_matcher.zig
+++ b/src/exact_size_matcher.zig
@@ -17,8 +17,37 @@ pub fn ExactSizeMatcher(comptime max_bytes: usize) type {
pub fn match(str: anytype) T {
switch (str.len) {
1...max_bytes - 1 => {
- var tmp = std.mem.zeroes([max_bytes]u8);
- std.mem.copy(u8, &tmp, str[0..str.len]);
+ var tmp: [max_bytes]u8 = undefined;
+ if (comptime std.meta.trait.isSlice(@TypeOf(str))) {
+ @memcpy(&tmp, str.ptr, str.len);
+ @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len);
+ } else {
+ @memcpy(&tmp, str, str.len);
+ @memset(tmp[str.len..], 0, tmp[str.len..].len);
+ }
+
+ return std.mem.readIntNative(T, &tmp);
+ },
+ max_bytes => {
+ return std.mem.readIntSliceNative(T, str);
+ },
+ 0 => {
+ return 0;
+ },
+ else => {
+ return std.math.maxInt(T);
+ },
+ }
+ }
+
+ pub fn matchLower(str: anytype) T {
+ switch (str.len) {
+ 1...max_bytes - 1 => {
+ var tmp: [max_bytes]u8 = undefined;
+ for (str) |char, i| {
+ tmp[i] = std.ascii.toLower(char);
+ }
+ @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len);
return std.mem.readIntNative(T, &tmp);
},
max_bytes => {
@@ -58,7 +87,7 @@ test "ExactSizeMatcher 5 letter" {
test "ExactSizeMatcher 4 letter" {
const Four = ExactSizeMatcher(4);
- const word = "from";
+ var word = "from".*;
try expect(Four.match(word) == Four.case("from"));
try expect(Four.match(word) != Four.case("fro"));
}
diff --git a/src/feature_flags.zig b/src/feature_flags.zig
index 42c1d17828..679ce28310 100644
--- a/src/feature_flags.zig
+++ b/src/feature_flags.zig
@@ -45,6 +45,8 @@ pub const allow_json_single_quotes = true;
pub const react_specific_warnings = true;
+pub const log_allocations = false;
+
pub const CSSInJSImportBehavior = enum {
// When you import a .css file and you reference the import in JavaScript
// Just return whatever the property key they referenced was
@@ -86,3 +88,5 @@ pub const disable_compression_in_http_client = false;
pub const use_libgit2 = true;
pub const atomic_file_watcher = env.isLinux;
+
+pub const node_streams = env.isDebug or env.isTest;
diff --git a/src/fs.zig b/src/fs.zig
index f2b6073c20..694a6d3a28 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -78,6 +78,10 @@ pub const BytecodeCacheFetcher = struct {
pub const FileSystem = struct {
allocator: std.mem.Allocator,
top_level_dir: string = "/",
+
+ // used on subsequent updates
+ top_level_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined,
+
fs: Implementation,
dirname_store: *DirnameStore,
@@ -170,7 +174,7 @@ pub const FileSystem = struct {
}
pub const DirEntry = struct {
- pub const EntryMap = hash_map.StringHashMap(*Entry);
+ pub const EntryMap = hash_map.StringHashMapUnmanaged(*Entry);
pub const EntryStore = allocators.BSSList(Entry, Preallocate.Counts.files);
dir: string,
fd: StoredFileDescriptorType = 0,
@@ -180,7 +184,7 @@ pub const FileSystem = struct {
// // dir.data.remove(name);
// }
- pub fn addEntry(dir: *DirEntry, entry: std.fs.Dir.Entry) !void {
+ pub fn addEntry(dir: *DirEntry, entry: std.fs.Dir.Entry, allocator: std.mem.Allocator, comptime Iterator: type, iterator: Iterator) !void {
var _kind: Entry.Kind = undefined;
switch (entry.kind) {
.Directory => {
@@ -228,7 +232,12 @@ pub const FileSystem = struct {
const stored_name = stored.base();
- try dir.data.put(stored.base_lowercase(), stored);
+ try dir.data.put(allocator, stored.base_lowercase(), stored);
+
+ if (comptime Iterator != void) {
+ iterator.next(stored, dir.fd);
+ }
+
if (comptime FeatureFlags.verbose_fs) {
if (_kind == .dir) {
Output.prettyln(" + {s}/", .{stored_name});
@@ -238,16 +247,12 @@ pub const FileSystem = struct {
}
}
- pub fn empty(dir: string, allocator: std.mem.Allocator) DirEntry {
- return DirEntry{ .dir = dir, .data = EntryMap.init(allocator) };
- }
-
- pub fn init(dir: string, allocator: std.mem.Allocator) DirEntry {
+ pub fn init(dir: string) DirEntry {
if (comptime FeatureFlags.verbose_fs) {
Output.prettyln("\n {s}", .{dir});
}
- return DirEntry{ .dir = dir, .data = EntryMap.init(allocator) };
+ return DirEntry{ .dir = dir, .data = EntryMap{} };
}
pub const Err = struct {
@@ -255,9 +260,9 @@ pub const FileSystem = struct {
canonical_error: anyerror,
};
- pub fn deinit(d: *DirEntry) void {
- d.data.allocator.free(d.dir);
- d.data.deinit();
+ pub fn deinit(d: *DirEntry, allocator: std.mem.Allocator) void {
+ d.data.deinit(allocator);
+ allocator.free(d.dir);
}
pub fn get(entry: *const DirEntry, _query: string) ?Entry.Lookup {
@@ -371,7 +376,8 @@ pub const FileSystem = struct {
pub fn kind(entry: *Entry, fs: *Implementation) Kind {
if (entry.need_stat) {
entry.need_stat = false;
- entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch unreachable;
+ // This is technically incorrect, but we are choosing not to handle errors here
+ entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch return entry.cache.kind;
}
return entry.cache.kind;
}
@@ -379,7 +385,9 @@ pub const FileSystem = struct {
pub fn symlink(entry: *Entry, fs: *Implementation) string {
if (entry.need_stat) {
entry.need_stat = false;
- entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch unreachable;
+ // This is technically incorrect, but we are choosing not to handle errors here
+ // This error can happen if the file was deleted between the time the directory was scanned and the time it was read
+ entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch return "";
}
return entry.cache.symlink.slice();
}
@@ -747,10 +755,13 @@ pub const FileSystem = struct {
fs: *RealFS,
_dir: string,
handle: std.fs.Dir,
+ comptime Iterator: type,
+ iterator: Iterator,
) !DirEntry {
var iter: std.fs.Dir.Iterator = handle.iterate();
- var dir = DirEntry.init(_dir, fs.allocator);
- errdefer dir.deinit();
+ var dir = DirEntry.init(_dir);
+ const allocator = fs.allocator;
+ errdefer dir.deinit(allocator);
if (FeatureFlags.store_file_descriptors) {
FileSystem.setMaxFd(handle.fd);
@@ -758,7 +769,7 @@ pub const FileSystem = struct {
}
while (try iter.next()) |_entry| {
- try dir.addEntry(_entry);
+ try dir.addEntry(_entry, allocator, Iterator, iterator);
}
return dir;
@@ -783,6 +794,10 @@ pub const FileSystem = struct {
threadlocal var temp_entries_option: EntriesOption = undefined;
pub fn readDirectory(fs: *RealFS, _dir: string, _handle: ?std.fs.Dir) !*EntriesOption {
+ return readDirectoryWithIterator(fs, _dir, _handle, void, void{});
+ }
+
+ pub fn readDirectoryWithIterator(fs: *RealFS, _dir: string, _handle: ?std.fs.Dir, comptime Iterator: type, iterator: Iterator) !*EntriesOption {
var dir = _dir;
var cache_result: ?allocators.Result = null;
if (comptime FeatureFlags.enable_entry_cache) {
@@ -821,6 +836,8 @@ pub const FileSystem = struct {
var entries = fs.readdir(
dir,
handle,
+ Iterator,
+ iterator,
) catch |err| {
return fs.readDirectoryError(dir, err) catch unreachable;
};
@@ -1064,6 +1081,10 @@ pub const Path = struct {
is_disabled: bool = false,
is_symlink: bool = false,
+ pub fn isBun(this: *const Path) bool {
+ return strings.eqlComptime(this.namespace, "bun");
+ }
+
pub const PackageRelative = struct {
path: string,
name: string,
@@ -1213,6 +1234,12 @@ pub const Path = struct {
}
};
+// pub fn customRealpath(allocator: std.mem.Allocator, path: string) !string {
+// var opened = try std.os.open(path, if (Environment.isLinux) std.os.O.PATH else std.os.O.RDONLY, 0);
+// defer std.os.close(opened);
+
+// }
+
test "PathName.init" {
var file = "/root/directory/file.ext".*;
const res = PathName.init(
diff --git a/src/generated_versions_list.zig b/src/generated_versions_list.zig
new file mode 100644
index 0000000000..5e2c720be9
--- /dev/null
+++ b/src/generated_versions_list.zig
@@ -0,0 +1,9 @@
+// AUTO-GENERATED FILE. Created via .scripts/write-versions.sh
+
+pub const webkit = "96e77eccfde8dc9c207520d8ced856d8bdb8d386";
+pub const mimalloc = "f412df7a2b64421e1f1d61fde6055a6ea288e8f5";
+pub const libarchive = "dc321febde83dd0f31158e1be61a7aedda65e7a2";
+pub const picohttpparser = "066d2b1e9ab820703db0837a7255d92d30f0c9f5";
+pub const boringssl = "b3ed071ecc4efb77afd0a025ea1078da19578bfd";
+pub const zlib = "959b4ea305821e753385e873ec4edfaa9a5d49b7";
+pub const zig = @import("std").fmt.comptimePrint("{}", .{@import("builtin").zig_version});
diff --git a/src/global.zig b/src/global.zig
index 772e7b6fef..046496029c 100644
--- a/src/global.zig
+++ b/src/global.zig
@@ -12,6 +12,7 @@ pub const C = @import("c.zig");
pub const FeatureFlags = @import("feature_flags.zig");
const root = @import("root");
+pub const meta = @import("./meta.zig");
pub const Output = struct {
// These are threadlocal so we don't have stdout/stderr writing on top of each other
@@ -215,6 +216,18 @@ pub const Output = struct {
return source.stream.writer();
}
+ pub fn resetTerminal() void {
+ if (!enable_ansi_colors) {
+ return;
+ }
+
+ if (enable_ansi_colors_stderr) {
+ _ = source.error_stream.write("\x1b[H\x1b[2J") catch 0;
+ } else {
+ _ = source.stream.write("\x1b[H\x1b[2J") catch 0;
+ }
+ }
+
pub fn flush() void {
if (Environment.isNative and source_set) {
source.buffered_stream.flush() catch {};
@@ -336,7 +349,7 @@ pub const Output = struct {
// - dim
// - reset
// - reset
- const ED = "\x1b[";
+ pub const ED = "\x1b[";
pub const color_map = std.ComptimeStringMap(string, .{
&.{ "black", ED ++ "30m" },
&.{ "blue", ED ++ "34m" },
@@ -349,7 +362,7 @@ pub const Output = struct {
&.{ "white", ED ++ "37m" },
&.{ "yellow", ED ++ "33m" },
});
-
+ pub const RESET = "\x1b[0m";
pub fn prettyFmt(comptime fmt: string, comptime is_enabled: bool) string {
comptime var new_fmt: [fmt.len * 4]u8 = undefined;
comptime var new_fmt_i: usize = 0;
@@ -415,7 +428,7 @@ pub const Output = struct {
}
if (is_reset) {
- const reset_sequence = "\x1b[0m";
+ const reset_sequence = RESET;
orig = new_fmt_i;
new_fmt_i += reset_sequence.len;
std.mem.copy(u8, new_fmt[orig..new_fmt_i], reset_sequence);
@@ -526,7 +539,10 @@ pub const Output = struct {
source.error_stream.writer().print(fmt, args) catch unreachable;
root.console_error(root.Uint8Array.fromSlice(source.err_buffer[0..source.error_stream.pos]));
} else {
- std.fmt.format(source.error_stream.writer(), fmt, args) catch unreachable;
+ if (enable_buffering)
+ std.fmt.format(source.buffered_error_stream.writer(), fmt, args) catch {}
+ else
+ std.fmt.format(source.error_stream.writer(), fmt, args) catch {};
}
}
};
@@ -548,12 +564,13 @@ pub const Global = struct {
long_running: bool = false,
};
- pub inline fn mimalloc_cleanup() void {
+ pub inline fn mimalloc_cleanup(force: bool) void {
if (comptime use_mimalloc) {
const Mimalloc = @import("./allocators/mimalloc.zig");
- Mimalloc.mi_collect(false);
+ Mimalloc.mi_collect(force);
}
}
+ pub const versions = @import("./generated_versions_list.zig");
// Enabling huge pages slows down bun by 8x or so
// Keeping this code for:
diff --git a/src/http.zig b/src/http.zig
index 844e36ac0a..243ad976c4 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -25,6 +25,7 @@ const Options = @import("./options.zig");
const Fallback = @import("./runtime.zig").Fallback;
const ErrorCSS = @import("./runtime.zig").ErrorCSS;
const ErrorJS = @import("./runtime.zig").ErrorJS;
+const Runtime = @import("./runtime.zig").Runtime;
const Css = @import("css_scanner.zig");
const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle;
const resolve_path = @import("./resolver/resolve_path.zig");
@@ -1069,6 +1070,9 @@ pub const RequestContext = struct {
env_loader: *DotEnv.Loader,
origin: ZigURL,
client_bundler: Bundler,
+ vm: *JavaScript.VirtualMachine = undefined,
+ start_timer: std.time.Timer = undefined,
+ entry_point: string = "",
pub fn handleJSError(
this: *HandlerThread,
@@ -1233,72 +1237,13 @@ pub const RequestContext = struct {
_spawn(handler) catch {};
}
- pub fn _spawn(handler: *HandlerThread) !void {
+ pub fn startJavaScript(handler: *HandlerThread) void {
defer {
javascript_disabled = true;
}
- var start_timer = std.time.Timer.start() catch unreachable;
-
- Output.Source.configureThread();
- @import("javascript/jsc/javascript_core_c_api.zig").JSCInitialize();
-
- js_ast.Stmt.Data.Store.create(std.heap.c_allocator);
- js_ast.Expr.Data.Store.create(std.heap.c_allocator);
-
- var vm = JavaScript.VirtualMachine.init(
- std.heap.c_allocator,
- handler.args,
- handler.existing_bundle,
- handler.log,
- handler.env_loader,
- ) catch |err| {
- handler.handleJSError(.create_vm, err) catch {};
- return;
- };
- vm.bundler.log = handler.log;
- std.debug.assert(JavaScript.VirtualMachine.vm_loaded);
- javascript_vm = vm;
- vm.bundler.options.origin = handler.origin;
- const boot = vm.bundler.options.framework.?.server.path;
- std.debug.assert(boot.len > 0);
- errdefer vm.deinit();
- vm.watcher = handler.watcher;
+ var vm = handler.vm;
+ const entry_point = handler.entry_point;
{
- defer vm.flush();
- vm.bundler.configureRouter(false) catch |err| {
- handler.handleJSError(.configure_router, err) catch {};
- return;
- };
- vm.bundler.configureDefines() catch |err| {
- handler.handleJSError(.configure_defines, err) catch {};
- return;
- };
-
- var entry_point = boot;
- if (!std.fs.path.isAbsolute(entry_point)) {
- const resolved_entry_point = vm.bundler.resolver.resolve(
- std.fs.path.dirname(boot) orelse vm.bundler.fs.top_level_dir,
- vm.bundler.normalizeEntryPointPath(boot),
- .entry_point,
- ) catch |err| {
- try handler.handleJSError(
- .resolve_entry_point,
- err,
- );
- return;
- };
- entry_point = (resolved_entry_point.pathConst() orelse {
- handler.handleJSErrorFmt(
- .resolve_entry_point,
- error.EntryPointDisabled,
- "JavaScript VM failed to start due to disabled entry point: \"{s}\"",
- .{resolved_entry_point.path_pair.primary.text},
- ) catch {};
-
- return;
- }).text;
- }
-
var load_result = vm.loadEntryPoint(
entry_point,
) catch |err| {
@@ -1308,6 +1253,7 @@ pub const RequestContext = struct {
"JavaScript VM failed to start.\n{s}: while loading \"{s}\"",
.{ @errorName(err), entry_point },
) catch {};
+ vm.flush();
return;
};
@@ -1323,6 +1269,7 @@ pub const RequestContext = struct {
"JavaScript VM failed to start.\nwhile loading \"{s}\"",
.{entry_point},
) catch {};
+ vm.flush();
return;
},
}
@@ -1334,6 +1281,7 @@ pub const RequestContext = struct {
"error: Framework didn't run addEventListener(\"fetch\", callback), which means it can't accept HTTP requests.\nShutting down JS.",
.{},
) catch {};
+ vm.flush();
return;
}
}
@@ -1341,10 +1289,9 @@ pub const RequestContext = struct {
js_ast.Stmt.Data.Store.reset();
js_ast.Expr.Data.Store.reset();
JavaScript.Bun.flushCSSImports();
-
vm.flush();
- Output.printElapsed(@intToFloat(f64, (start_timer.read())) / std.time.ns_per_ms);
+ Output.printElapsed(@intToFloat(f64, (handler.start_timer.read())) / std.time.ns_per_ms);
if (vm.bundler.options.framework.?.display_name.len > 0) {
Output.prettyError(
@@ -1362,10 +1309,85 @@ pub const RequestContext = struct {
Output.flush();
- try runLoop(
+ runLoop(
vm,
handler,
- );
+ ) catch {};
+ }
+
+ pub fn _spawn(handler: *HandlerThread) !void {
+ handler.start_timer = std.time.Timer.start() catch unreachable;
+
+ Output.Source.configureThread();
+ @import("javascript/jsc/javascript_core_c_api.zig").JSCInitialize();
+
+ js_ast.Stmt.Data.Store.create(std.heap.c_allocator);
+ js_ast.Expr.Data.Store.create(std.heap.c_allocator);
+
+ var vm = JavaScript.VirtualMachine.init(
+ std.heap.c_allocator,
+ handler.args,
+ handler.existing_bundle,
+ handler.log,
+ handler.env_loader,
+ ) catch |err| {
+ handler.handleJSError(.create_vm, err) catch {};
+ javascript_disabled = true;
+ return;
+ };
+ vm.is_from_devserver = true;
+ vm.bundler.log = handler.log;
+ std.debug.assert(JavaScript.VirtualMachine.vm_loaded);
+ javascript_vm = vm;
+ vm.bundler.options.origin = handler.origin;
+ const boot = vm.bundler.options.framework.?.server.path;
+ std.debug.assert(boot.len > 0);
+ errdefer vm.deinit();
+ vm.watcher = handler.watcher;
+ {
+ vm.bundler.configureRouter(false) catch |err| {
+ handler.handleJSError(.configure_router, err) catch {};
+ vm.flush();
+ javascript_disabled = true;
+ return;
+ };
+ vm.bundler.configureDefines() catch |err| {
+ handler.handleJSError(.configure_defines, err) catch {};
+ vm.flush();
+ javascript_disabled = true;
+ return;
+ };
+
+ var entry_point = boot;
+ if (!std.fs.path.isAbsolute(entry_point)) {
+ const resolved_entry_point = vm.bundler.resolver.resolve(
+ std.fs.path.dirname(boot) orelse vm.bundler.fs.top_level_dir,
+ vm.bundler.normalizeEntryPointPath(boot),
+ .entry_point,
+ ) catch |err| {
+ try handler.handleJSError(
+ .resolve_entry_point,
+ err,
+ );
+ javascript_disabled = true;
+ return;
+ };
+ entry_point = (resolved_entry_point.pathConst() orelse {
+ handler.handleJSErrorFmt(
+ .resolve_entry_point,
+ error.EntryPointDisabled,
+ "JavaScript VM failed to start due to disabled entry point: \"{s}\"",
+ .{resolved_entry_point.path_pair.primary.text},
+ ) catch {};
+ javascript_disabled = true;
+ return;
+ }).text;
+ }
+
+ handler.entry_point = entry_point;
+ }
+ handler.vm = vm;
+ vm.global.vm().holdAPILock(handler, JavaScript.OpaqueWrap(HandlerThread, startJavaScript));
}
var __arena: std.heap.ArenaAllocator = undefined;
@@ -1395,7 +1417,7 @@ pub const RequestContext = struct {
Output.flush();
JavaScript.VirtualMachine.vm.arena.deinit();
JavaScript.VirtualMachine.vm.has_loaded = false;
- mimalloc.mi_collect(false);
+ Global.mimalloc_cleanup(false);
}
var handler: *JavaScriptHandler = try channel.readItem();
@@ -1944,7 +1966,7 @@ pub const RequestContext = struct {
};
pub fn writeETag(this: *RequestContext, buffer: anytype) !bool {
- const strong_etag = std.hash.Wyhash.hash(1, buffer);
+ const strong_etag = std.hash.Wyhash.hash(0, buffer);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
this.appendHeader("ETag", etag_content_slice);
@@ -2074,12 +2096,12 @@ pub const RequestContext = struct {
// Always cache css & json files, even big ones
// css is especially important because we want to try and skip having the browser parse it whenever we can
if (buf.len < 16 * 16 * 16 * 16 or chunky._loader == .css or chunky._loader == .json) {
- const strong_etag = std.hash.Wyhash.hash(1, buf);
+ const strong_etag = std.hash.Wyhash.hash(0, buf);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
chunky.rctx.appendHeader("ETag", etag_content_slice);
if (chunky.rctx.header("If-None-Match")) |etag_header| {
- if (std.mem.eql(u8, etag_content_slice, etag_header)) {
+ if (strings.eqlLong(etag_content_slice, etag_header, true)) {
try chunky.rctx.sendNotModified();
return;
}
@@ -2176,12 +2198,12 @@ pub const RequestContext = struct {
.css => try ctx.sendNoContent(),
.js, .jsx, .ts, .tsx, .json => {
const buf = "export default {};";
- const strong_etag = comptime std.hash.Wyhash.hash(1, buf);
+ const strong_etag = comptime std.hash.Wyhash.hash(0, buf);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
ctx.appendHeader("ETag", etag_content_slice);
if (ctx.header("If-None-Match")) |etag_header| {
- if (std.mem.eql(u8, etag_content_slice, etag_header)) {
+ if (strings.eqlLong(etag_content_slice, etag_header, true)) {
try ctx.sendNotModified();
return;
}
@@ -2231,7 +2253,7 @@ pub const RequestContext = struct {
// if (result.mime_type.category != .html) {
// hash(absolute_file_path, size, mtime)
- var weak_etag = std.hash.Wyhash.init(1);
+ var weak_etag = std.hash.Wyhash.init(0);
weak_etag_buffer[0] = 'W';
weak_etag_buffer[1] = '/';
weak_etag.update(result.file.input.text);
@@ -2249,7 +2271,7 @@ pub const RequestContext = struct {
ctx.appendHeader("ETag", complete_weak_etag);
if (ctx.header("If-None-Match")) |etag_header| {
- if (strings.eql(complete_weak_etag, etag_header)) {
+ if (strings.eqlLong(complete_weak_etag, etag_header, true)) {
try ctx.sendNotModified();
return;
}
@@ -2325,13 +2347,13 @@ pub const RequestContext = struct {
const blob: Blob = brk: {
// It could be a blob either for macros or for JS thread
if (JavaScriptHandler.javascript_vm) |vm| {
- if (vm.blobs.get(id)) |blob| {
+ if (vm.blobs.?.get(id)) |blob| {
break :brk blob;
}
}
if (JavaScript.VirtualMachine.vm_loaded) {
- if (JavaScript.VirtualMachine.vm.blobs.get(id)) |blob| {
+ if (JavaScript.VirtualMachine.vm.blobs.?.get(id)) |blob| {
break :brk blob;
}
}
@@ -2366,6 +2388,9 @@ pub const RequestContext = struct {
if (strings.eqlComptime(path, "error.js")) {
const buffer = ErrorJS.sourceContent();
ctx.appendHeader("Content-Type", MimeType.javascript.value);
+ ctx.appendHeader("Cache-Control", "public, max-age=3600");
+ ctx.appendHeader("Age", "0");
+
if (FeatureFlags.strong_etags_for_built_files) {
const did_send = ctx.writeETag(buffer) catch false;
if (did_send) return;
@@ -2386,6 +2411,9 @@ pub const RequestContext = struct {
if (strings.eqlComptime(path, "erro.css")) {
const buffer = ErrorCSS.sourceContent();
ctx.appendHeader("Content-Type", MimeType.css.value);
+ ctx.appendHeader("Cache-Control", "public, max-age=3600");
+ ctx.appendHeader("Age", "0");
+
if (FeatureFlags.strong_etags_for_built_files) {
const did_send = ctx.writeETag(buffer) catch false;
if (did_send) return;
@@ -2418,6 +2446,28 @@ pub const RequestContext = struct {
return;
}
+ if (strings.eqlComptime(path, "runtime")) {
+ const buffer = Runtime.sourceContent();
+ ctx.appendHeader("Content-Type", MimeType.javascript.value);
+ ctx.appendHeader("Cache-Control", "public, max-age=3600");
+ ctx.appendHeader("Age", "0");
+ if (FeatureFlags.strong_etags_for_built_files) {
+ const did_send = ctx.writeETag(buffer) catch false;
+ if (did_send) return;
+ }
+
+ if (buffer.len == 0) {
+ return try ctx.sendNoContent();
+ }
+ const send_body = ctx.method == .GET;
+ defer ctx.done();
+ try ctx.writeStatus(200);
+ try ctx.prepareToSendBody(buffer.len, false);
+ if (!send_body) return;
+ _ = try ctx.writeSocket(buffer, SOCKET_FLAGS);
+ return;
+ }
+
try ctx.sendNotFound();
return;
}
diff --git a/src/identity_context.zig b/src/identity_context.zig
index b28cac1ccf..299907b345 100644
--- a/src/identity_context.zig
+++ b/src/identity_context.zig
@@ -12,7 +12,7 @@ pub fn IdentityContext(comptime Key: type) type {
/// When storing hashes as keys in a hash table, we don't want to hash the hashes or else we increase the chance of collisions. This is also marginally faster since it means hashing less stuff.
/// `ArrayIdentityContext` and `IdentityContext` are distinct because ArrayHashMap expects u32 hashes but HashMap expects u64 hashes.
-const ArrayIdentityContext = struct {
+pub const ArrayIdentityContext = struct {
pub fn hash(_: @This(), key: u32) u32 {
return key;
}
diff --git a/src/javascript/jsc/api/router.zig b/src/javascript/jsc/api/router.zig
index 2e2588e5af..e8ef4dc09c 100644
--- a/src/javascript/jsc/api/router.zig
+++ b/src/javascript/jsc/api/router.zig
@@ -39,17 +39,17 @@ script_src_buf_writer: ScriptSrcStream = undefined,
pub fn importRoute(
this: *Router,
- _: js.JSContextRef,
+ ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSObjectRef,
_: []const js.JSValueRef,
_: js.ExceptionRef,
) js.JSObjectRef {
- const prom = JSC.JSModuleLoader.loadAndEvaluateModule(VirtualMachine.vm.global, &ZigString.init(this.route.file_path));
+ const prom = JSC.JSModuleLoader.loadAndEvaluateModule(ctx.ptr(), &ZigString.init(this.route.file_path));
VirtualMachine.vm.tick();
- return prom.result(VirtualMachine.vm.global.vm()).asRef();
+ return prom.result(ctx.ptr().vm()).asRef();
}
pub fn match(
@@ -69,9 +69,9 @@ pub fn match(
return matchFetchEvent(ctx, To.Zig.ptr(FetchEvent, arguments[0]), exception);
}
- if (js.JSValueIsString(ctx, arguments[0])) {
- return matchPathName(ctx, arguments[0], exception);
- }
+ // if (js.JSValueIsString(ctx, arguments[0])) {
+ // return matchPathName(ctx, arguments[0], exception);
+ // }
if (js.JSValueIsObjectOfClass(ctx, arguments[0], Request.Class.get().*)) {
return matchRequest(ctx, To.Zig.ptr(Request, arguments[0]), exception);
@@ -88,20 +88,6 @@ fn matchRequest(
return createRouteObject(ctx, request.request_context, exception);
}
-fn matchPathNameString(
- _: js.JSContextRef,
- _: string,
- _: js.ExceptionRef,
-) js.JSObjectRef {}
-
-fn matchPathName(
- _: js.JSContextRef,
- _: js.JSStringRef,
- _: js.ExceptionRef,
-) js.JSObjectRef {
- return null;
-}
-
fn matchFetchEvent(
ctx: js.JSContextRef,
fetch_event: *const FetchEvent,
@@ -274,12 +260,12 @@ pub const Instance = NewClass(
pub fn getFilePath(
this: *Router,
- _: js.JSContextRef,
+ ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSStringRef,
_: js.ExceptionRef,
) js.JSValueRef {
- return ZigString.init(this.route.file_path).toValue(VirtualMachine.vm.global).asRef();
+ return ZigString.init(this.route.file_path).toValue(ctx.ptr()).asRef();
}
pub fn finalize(
@@ -292,22 +278,22 @@ pub fn finalize(
pub fn getPathname(
this: *Router,
- _: js.JSContextRef,
+ ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSStringRef,
_: js.ExceptionRef,
) js.JSValueRef {
- return ZigString.init(this.route.pathname).toValue(VirtualMachine.vm.global).asRef();
+ return ZigString.init(this.route.pathname).toValue(ctx.ptr()).asRef();
}
pub fn getRoute(
this: *Router,
- _: js.JSContextRef,
+ ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSStringRef,
_: js.ExceptionRef,
) js.JSValueRef {
- return ZigString.init(this.route.name).toValue(VirtualMachine.vm.global).asRef();
+ return ZigString.init(this.route.name).toValue(ctx.ptr()).asRef();
}
const KindEnum = struct {
@@ -332,17 +318,17 @@ const KindEnum = struct {
pub fn getKind(
this: *Router,
- _: js.JSContextRef,
+ ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSStringRef,
_: js.ExceptionRef,
) js.JSValueRef {
- return KindEnum.init(this.route.name).toValue(VirtualMachine.vm.global).asRef();
+ return KindEnum.init(this.route.name).toValue(ctx.ptr()).asRef();
}
threadlocal var query_string_values_buf: [256]string = undefined;
threadlocal var query_string_value_refs_buf: [256]ZigString = undefined;
-pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef {
+pub fn createQueryObject(ctx: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef {
const QueryObjectCreator = struct {
query: *QueryStringMap,
pub fn create(this: *@This(), obj: *JSObject, global: *JSGlobalObject) void {
@@ -369,7 +355,7 @@ pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.Excepti
var creator = QueryObjectCreator{ .query = map };
- var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, VirtualMachine.vm.global, map.getNameCount());
+ var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, ctx.ptr(), map.getNameCount());
return value.asRef();
}
@@ -440,7 +426,7 @@ pub fn getParams(
if (this.param_map) |*map| {
return createQueryObject(ctx, map, exception);
} else {
- return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef();
+ return JSValue.createEmptyObject(ctx.ptr(), 0).asRef();
}
}
@@ -473,6 +459,6 @@ pub fn getQuery(
if (this.query_string_map) |*map| {
return createQueryObject(ctx, map, exception);
} else {
- return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef();
+ return JSValue.createEmptyObject(ctx.ptr(), 0).asRef();
}
}
diff --git a/src/javascript/jsc/base.zig b/src/javascript/jsc/base.zig
index f51eb86d97..cf2ed1bad9 100644
--- a/src/javascript/jsc/base.zig
+++ b/src/javascript/jsc/base.zig
@@ -13,7 +13,9 @@ const C = _global.C;
const JavaScript = @import("./javascript.zig");
const ResolveError = JavaScript.ResolveError;
const BuildError = JavaScript.BuildError;
+const JSC = @import("../../jsc.zig");
const WebCore = @import("./webcore/response.zig");
+const Test = @import("./test/jest.zig");
const Fetch = WebCore.Fetch;
const Response = WebCore.Response;
const Request = WebCore.Request;
@@ -128,6 +130,190 @@ pub const To = struct {
};
}
+ pub fn withType(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef {
+ return withTypeClone(Type, value, context, exception, false);
+ }
+
+ pub fn withTypeClone(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef, clone: bool) JSC.C.JSValueRef {
+ if (comptime std.meta.trait.isNumber(Type)) {
+ return JSC.JSValue.jsNumberWithType(Type, value).asRef();
+ }
+
+ var zig_str: JSC.ZigString = undefined;
+
+ return switch (comptime Type) {
+ void => JSC.C.JSValueMakeUndefined(context),
+ bool => JSC.C.JSValueMakeBoolean(context, value),
+ []const u8, [:0]const u8, [*:0]const u8, []u8, [:0]u8, [*:0]u8 => brk: {
+ zig_str = ZigString.init(value);
+ const val = zig_str.toValueAuto(context.ptr());
+
+ break :brk val.asObjectRef();
+ },
+ []const PathString, []const []const u8, []const []u8, [][]const u8, [][:0]const u8, [][:0]u8 => {
+ var zig_strings_buf: [32]ZigString = undefined;
+ var zig_strings: []ZigString = if (value.len < 32)
+ &zig_strings_buf
+ else
+ (_global.default_allocator.alloc(ZigString, value.len) catch unreachable);
+ defer if (zig_strings.ptr != &zig_strings_buf)
+ _global.default_allocator.free(zig_strings);
+
+ for (value) |path_string, i| {
+ if (comptime Type == []const PathString) {
+ zig_strings[i] = ZigString.init(path_string.slice());
+ } else {
+ zig_strings[i] = ZigString.init(path_string);
+ }
+ }
+
+ var array = JSC.JSValue.createStringArray(context.ptr(), zig_strings.ptr, zig_strings.len, clone).asObjectRef();
+
+ if (clone) {
+ for (value) |path_string| {
+ if (comptime Type == []const PathString) {
+ _global.default_allocator.free(path_string.slice());
+ } else {
+ _global.default_allocator.free(path_string);
+ }
+ }
+ _global.default_allocator.free(value);
+ }
+
+ return array;
+ },
+
+ JSC.C.JSValueRef => value,
+
+ else => {
+ const Info: std.builtin.TypeInfo = comptime @typeInfo(Type);
+ if (comptime Info == .Enum) {
+ const Enum: std.builtin.TypeInfo.Enum = Info.Enum;
+ if (comptime !std.meta.trait.isNumber(Enum.tag_type)) {
+ zig_str = JSC.ZigString.init(@tagName(value));
+ return zig_str.toValue(context.ptr()).asObjectRef();
+ }
+ }
+
+ // Recursion can stack overflow here
+ if (comptime std.meta.trait.isSlice(Type)) {
+ const Child = std.meta.Child(Type);
+
+ const prefill = 32;
+ if (value.len <= prefill) {
+ var array: [prefill]JSC.C.JSValueRef = undefined;
+ var i: u8 = 0;
+ const len = @minimum(@intCast(u8, value.len), prefill);
+ while (i < len and exception.* == null) : (i += 1) {
+ array[i] = if (comptime Child == JSC.C.JSValueRef)
+ value[i]
+ else
+ To.JS.withType(Child, value[i], context, exception);
+ }
+
+ if (exception.* != null) {
+ return null;
+ }
+
+ // TODO: this function copies to a MarkedArgumentsBuffer
+ // That copy is unnecessary.
+ const obj = JSC.C.JSObjectMakeArray(context, len, &array, exception);
+
+ if (exception.* != null) {
+ return null;
+ }
+ return obj;
+ }
+
+ {
+ var array = _global.default_allocator.alloc(JSC.C.JSValueRef, value.len) catch unreachable;
+ defer _global.default_allocator.free(array);
+ var i: usize = 0;
+ while (i < value.len and exception.* == null) : (i += 1) {
+ array[i] = if (comptime Child == JSC.C.JSValueRef)
+ value[i]
+ else
+ To.JS.withType(Child, value[i], context, exception);
+ }
+
+ if (exception.* != null) {
+ return null;
+ }
+
+ // TODO: this function copies to a MarkedArgumentsBuffer
+ // That copy is unnecessary.
+ const obj = JSC.C.JSObjectMakeArray(context, value.len, array.ptr, exception);
+ if (exception.* != null) {
+ return null;
+ }
+
+ return obj;
+ }
+ }
+
+ if (comptime std.meta.trait.isZigString(Type)) {
+ zig_str = JSC.ZigString.init(value);
+ return zig_str.toValue(context.ptr()).asObjectRef();
+ }
+
+ if (comptime Info == .Pointer) {
+ const Child = comptime std.meta.Child(Type);
+ if (comptime std.meta.trait.isContainer(Child) and @hasDecl(Child, "Class") and @hasDecl(Child.Class, "isJavaScriptCoreClass")) {
+ return Child.Class.make(context, value);
+ }
+ }
+
+ if (comptime Info == .Struct) {
+ if (comptime @hasDecl(Type, "Class") and @hasDecl(Type.Class, "isJavaScriptCoreClass")) {
+ if (comptime !@hasDecl(Type, "finalize")) {
+ @compileError(comptime std.fmt.comptimePrint("JSC class {s} must implement finalize to prevent memory leaks", .{Type.Class.name}));
+ }
+
+ if (comptime !@hasDecl(Type, "toJS")) {
+ var val = _global.default_allocator.create(Type) catch unreachable;
+ val.* = value;
+ return Type.Class.make(context, val);
+ }
+ }
+ }
+
+ const res = value.toJS(context, exception);
+
+ if (@TypeOf(res) == JSC.C.JSValueRef) {
+ return res;
+ } else if (@TypeOf(res) == JSC.JSValue) {
+ return res.asObjectRef();
+ }
+ },
+ };
+ }
+
+ pub fn PropertyGetter(
+ comptime Type: type,
+ ) type {
+ return comptime fn (
+ this: ObjectPtrType(Type),
+ ctx: js.JSContextRef,
+ _: js.JSValueRef,
+ _: js.JSStringRef,
+ exception: js.ExceptionRef,
+ ) js.JSValueRef;
+ }
+
+ pub fn Getter(comptime Type: type, comptime field: std.meta.FieldEnum(Type)) PropertyGetter(Type) {
+ return struct {
+ pub fn rfn(
+ this: ObjectPtrType(Type),
+ ctx: js.JSContextRef,
+ _: js.JSValueRef,
+ _: js.JSStringRef,
+ exception: js.ExceptionRef,
+ ) js.JSValueRef {
+ return withType(std.meta.fieldInfo(Type, field).field_type, @field(this, @tagName(field)), ctx, exception);
+ }
+ }.rfn;
+ }
+
pub fn Callback(
comptime ZigContextType: type,
comptime ctxfn: fn (
@@ -150,7 +336,7 @@ pub const To = struct {
) callconv(.C) js.JSValueRef {
if (comptime ZigContextType == anyopaque) {
return ctxfn(
- js.JSObjectGetPrivate(function) or js.jsObjectGetPrivate(thisObject),
+ js.JSObjectGetPrivate(function) orelse js.JSObjectGetPrivate(thisObject) orelse undefined,
ctx,
function,
thisObject,
@@ -232,86 +418,12 @@ pub const Properties = struct {
pub const follow = "follow";
};
- pub const UTF16 = struct {
- pub const module: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.module);
- pub const globalThis: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.globalThis);
- pub const exports: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.exports);
- pub const log: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.log);
- pub const debug: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.debug);
- pub const info: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.info);
- pub const error_: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.error_);
- pub const warn: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.warn);
- pub const console: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.console);
- pub const require: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.require);
- pub const description: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.description);
- pub const name: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.name);
- pub const initialize_bundled_module = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.initialize_bundled_module);
- pub const load_module_function: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.load_module_function);
- pub const window: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.window);
- pub const default: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.default);
- pub const include: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.include);
-
- pub const GET: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.GET);
- pub const PUT: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PUT);
- pub const POST: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.POST);
- pub const PATCH: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PATCH);
- pub const HEAD: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.HEAD);
- pub const OPTIONS: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.OPTIONS);
-
- pub const navigate: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.navigate);
- pub const follow: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.follow);
- };
-
pub const Refs = struct {
- pub var filepath: js.JSStringRef = undefined;
-
- pub var module: js.JSStringRef = undefined;
- pub var globalThis: js.JSStringRef = undefined;
- pub var exports: js.JSStringRef = undefined;
- pub var log: js.JSStringRef = undefined;
- pub var debug: js.JSStringRef = undefined;
- pub var info: js.JSStringRef = undefined;
- pub var error_: js.JSStringRef = undefined;
- pub var warn: js.JSStringRef = undefined;
- pub var console: js.JSStringRef = undefined;
- pub var require: js.JSStringRef = undefined;
- pub var description: js.JSStringRef = undefined;
- pub var name: js.JSStringRef = undefined;
- pub var initialize_bundled_module: js.JSStringRef = undefined;
- pub var load_module_function: js.JSStringRef = undefined;
- pub var window: js.JSStringRef = undefined;
- pub var default: js.JSStringRef = undefined;
- pub var include: js.JSStringRef = undefined;
- pub var GET: js.JSStringRef = undefined;
- pub var PUT: js.JSStringRef = undefined;
- pub var POST: js.JSStringRef = undefined;
- pub var PATCH: js.JSStringRef = undefined;
- pub var HEAD: js.JSStringRef = undefined;
- pub var OPTIONS: js.JSStringRef = undefined;
-
pub var empty_string_ptr = [_]u8{0};
pub var empty_string: js.JSStringRef = undefined;
-
- pub var navigate: js.JSStringRef = undefined;
- pub var follow: js.JSStringRef = undefined;
-
- pub const env: js.JSStringRef = undefined;
};
pub fn init() void {
- inline for (std.meta.fieldNames(UTF8)) |name| {
- @field(Refs, name) = js.JSStringCreateStatic(
- @field(UTF8, name).ptr,
- @field(UTF8, name).len,
- );
-
- if (comptime Environment.isDebug) {
- std.debug.assert(
- js.JSStringIsEqualToString(@field(Refs, name), @field(UTF8, name).ptr, @field(UTF8, name).len),
- );
- }
- }
-
Refs.empty_string = js.JSStringCreateWithUTF8CString(&Refs.empty_string_ptr);
}
};
@@ -720,6 +832,8 @@ pub const ClassOptions = struct {
ts: d.ts.decl = d.ts.decl{ .empty = 0 },
};
+// work around a comptime bug
+
pub fn NewClass(
comptime ZigType: type,
comptime options: ClassOptions,
@@ -728,13 +842,16 @@ pub fn NewClass(
) type {
const read_only = options.read_only;
const singleton = options.singleton;
+ _ = read_only;
return struct {
const name = options.name;
+ pub const isJavaScriptCoreClass = true;
const ClassDefinitionCreator = @This();
const function_names = std.meta.fieldNames(@TypeOf(staticFunctions));
const function_name_literals = function_names;
var function_name_refs: [function_names.len]js.JSStringRef = undefined;
+ var function_name_refs_set = false;
var class_name_str = name[0.. :0].ptr;
var static_functions = brk: {
@@ -750,24 +867,10 @@ pub fn NewClass(
);
break :brk funcs;
};
- var instance_functions = std.mem.zeroes([function_names.len]js.JSObjectRef);
const property_names = std.meta.fieldNames(@TypeOf(properties));
- var property_name_refs = std.mem.zeroes([property_names.len]js.JSStringRef);
+ var property_name_refs: [property_names.len]js.JSStringRef = undefined;
+ var property_name_refs_set: bool = false;
const property_name_literals = property_names;
- var static_properties = brk: {
- var props: [property_names.len + 1]js.JSStaticValue = undefined;
- std.mem.set(
- js.JSStaticValue,
- &props,
- js.JSStaticValue{
- .name = @intToPtr([*c]const u8, 0),
- .getProperty = null,
- .setProperty = null,
- .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone,
- },
- );
- break :brk props;
- };
pub var ref: js.JSClassRef = null;
pub var loaded = false;
@@ -822,8 +925,6 @@ pub fn NewClass(
pub const Constructor = ConstructorWrapper.rfn;
- pub const static_value_count = static_properties.len;
-
pub fn get() callconv(.C) [*c]js.JSClassRef {
if (!loaded) {
loaded = true;
@@ -883,39 +984,6 @@ pub fn NewClass(
return ClassGetter;
}
- pub fn getPropertyCallback(
- ctx: js.JSContextRef,
- obj: js.JSObjectRef,
- prop: js.JSStringRef,
- exception: js.ExceptionRef,
- ) callconv(.C) js.JSValueRef {
- var pointer = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx);
-
- if (singleton) {
- inline for (function_names) |_, i| {
- if (js.JSStringIsEqual(prop, function_name_refs[i])) {
- return instance_functions[i];
- }
- }
- unreachable;
- } else {
- inline for (property_names) |propname, i| {
- if (js.JSStringIsEqual(prop, property_name_refs[i])) {
- return @field(
- properties,
- propname,
- )(pointer, ctx, obj, exception);
- }
- }
-
- if (comptime std.meta.trait.hasFn("onMissingProperty")(ZigType)) {
- return pointer.onMissingProperty(ctx, obj, prop, exception);
- }
- }
-
- return js.JSValueMakeUndefined(ctx);
- }
-
fn StaticProperty(comptime id: usize) type {
return struct {
pub fn getter(
@@ -943,6 +1011,13 @@ pub fn NewClass(
);
},
.Struct => {
+ comptime {
+ if (!@hasField(@TypeOf(@field(properties, property_names[id])), "get")) {
+ @compileError(
+ "Cannot get static property " ++ property_names[id] ++ " of " ++ name ++ " because it is a struct without a getter",
+ );
+ }
+ }
const func = @field(
@field(
properties,
@@ -988,7 +1063,7 @@ pub fn NewClass(
value: js.JSValueRef,
exception: js.ExceptionRef,
) callconv(.C) bool {
- var this = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx);
+ var this = GetJSPrivateData(ZigType, obj) orelse return false;
switch (comptime @typeInfo(@TypeOf(@field(
properties,
@@ -1180,6 +1255,41 @@ pub fn NewClass(
return decl;
}
+ pub fn getPropertyNames(
+ _: js.JSContextRef,
+ _: js.JSObjectRef,
+ props: js.JSPropertyNameAccumulatorRef,
+ ) callconv(.C) void {
+ if (comptime property_name_refs.len > 0) {
+ comptime var i: usize = 0;
+ if (!property_name_refs_set) {
+ property_name_refs_set =true;
+ inline while (i < property_name_refs.len) : (i += 1) {
+ property_name_refs[i] = js.JSStringCreateStatic(property_names[i].ptr, property_names[i].len);
+ }
+ comptime i = 0;
+ }
+ inline while (i < property_name_refs.len) : (i += 1) {
+ js.JSPropertyNameAccumulatorAddName(props, property_name_refs[i]);
+ }
+ }
+
+ if (comptime function_name_refs.len > 0) {
+ comptime var j: usize = 0;
+ if (!function_name_refs_set) {
+ function_name_refs_set = true;
+ inline while (j < function_name_refs.len) : (j += 1) {
+ function_name_refs[j] = js.JSStringCreateStatic(function_names[j].ptr, function_names[j].len);
+ }
+ comptime j = 0;
+ }
+
+ inline while (j < function_name_refs.len) : (j += 1) {
+ js.JSPropertyNameAccumulatorAddName(props, function_name_refs[j]);
+ }
+ }
+ }
+
// This should only be run at comptime
pub fn typescriptClassDeclaration() d.ts.class {
comptime var class = options.ts.class;
@@ -1301,11 +1411,26 @@ pub fn NewClass(
return comptime class;
}
+ var static_properties = brk: {
+ var props: [property_names.len + 1]js.JSStaticValue = undefined;
+ std.mem.set(
+ js.JSStaticValue,
+ &props,
+ js.JSStaticValue{
+ .name = @intToPtr([*c]const u8, 0),
+ .getProperty = null,
+ .setProperty = null,
+ .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone,
+ },
+ );
+ break :brk props;
+ };
+
pub fn define() js.JSClassDefinition {
var def = js.JSClassDefinition{
.version = 0,
.attributes = js.JSClassAttributes.kJSClassAttributeNone,
- .className = class_name_str,
+ .className = name.ptr[0..name.len :0],
.parentClass = null,
.staticValues = null,
.staticFunctions = null,
@@ -1322,58 +1447,59 @@ pub fn NewClass(
.convertToType = null,
};
- if (static_functions.len > 0) {
- std.mem.set(js.JSStaticFunction, &static_functions, std.mem.zeroes(js.JSStaticFunction));
- var count: usize = 0;
- inline for (function_name_literals) |_, i| {
- switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_names[i])))) {
+ // These workaround stage1 compiler bugs
+ var JSStaticValue_empty = std.mem.zeroes(js.JSStaticValue);
+ var count: usize = 0;
+
+ if (comptime static_functions.len > 0) {
+ inline for (function_name_literals) |function_name_literal, i| {
+ _ = i;
+ switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_name_literal)))) {
.Struct => {
- if (comptime strings.eqlComptime(function_names[i], "constructor")) {
+ if (comptime strings.eqlComptime(function_name_literal, "constructor")) {
def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor.rfn).rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "finalize")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) {
def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize.rfn).rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "call")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "call")) {
def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call.rfn).rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "callAsFunction")) {
- const ctxfn = @field(staticFunctions, function_names[i]).rfn;
+ } else if (comptime strings.eqlComptime(function_name_literal, "callAsFunction")) {
+ const ctxfn = @field(staticFunctions, function_name_literal).rfn;
const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn;
const PointerType = std.meta.Child(Func.args[0].arg_type.?);
- var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback(
+ def.callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback(
PointerType,
ctxfn,
).rfn;
-
- def.callAsFunction = callback;
- } else if (comptime strings.eqlComptime(function_names[i], "hasProperty")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "hasProperty")) {
def.hasProperty = @field(staticFunctions, "hasProperty").rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "getProperty")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "getProperty")) {
def.getProperty = @field(staticFunctions, "getProperty").rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "setProperty")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "setProperty")) {
def.setProperty = @field(staticFunctions, "setProperty").rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "deleteProperty")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "deleteProperty")) {
def.deleteProperty = @field(staticFunctions, "deleteProperty").rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "getPropertyNames")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) {
def.getPropertyNames = @field(staticFunctions, "getPropertyNames").rfn;
+ } else if (comptime strings.eqlComptime(function_name_literal, "convertToType")) {
+ def.convertToType = @field(staticFunctions, "convertToType").rfn;
} else {
- const CtxField = @field(staticFunctions, function_names[i]);
+ const CtxField = comptime @field(staticFunctions, function_name_literal);
if (comptime !@hasField(@TypeOf(CtxField), "rfn")) {
- @compileError("Expected " ++ options.name ++ "." ++ function_names[i] ++ " to have .rfn");
+ @compileError("Expected " ++ options.name ++ "." ++ function_name_literal ++ " to have .rfn");
}
const ctxfn = CtxField.rfn;
const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn;
const PointerType = if (Func.args[0].arg_type.? == void) void else std.meta.Child(Func.args[0].arg_type.?);
- var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback(
- PointerType,
- ctxfn,
- ).rfn;
-
static_functions[count] = js.JSStaticFunction{
.name = (function_names[i][0.. :0]).ptr,
- .callAsFunction = callback,
+ .callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback(
+ PointerType,
+ ctxfn,
+ ).rfn,
.attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone,
};
@@ -1381,27 +1507,30 @@ pub fn NewClass(
}
},
.Fn => {
- if (comptime strings.eqlComptime(function_names[i], "constructor")) {
+ if (comptime strings.eqlComptime(function_name_literal, "constructor")) {
def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor).rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "finalize")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) {
def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize).rfn;
- } else if (comptime strings.eqlComptime(function_names[i], "call")) {
+ } else if (comptime strings.eqlComptime(function_name_literal, "call")) {
def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call).rfn;
+ } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) {
+ def.getPropertyNames = To.JS.Callback(ZigType, staticFunctions.getPropertyNames).rfn;
+ } else if (comptime strings.eqlComptime(function_name_literal, "hasInstance")) {
+ def.hasInstance = staticFunctions.hasInstance;
} else {
- var callback = To.JS.Callback(
- ZigType,
- @field(staticFunctions, function_names[i]),
- ).rfn;
static_functions[count] = js.JSStaticFunction{
.name = (function_names[i][0.. :0]).ptr,
- .callAsFunction = callback,
+ .callAsFunction = To.JS.Callback(
+ ZigType,
+ @field(staticFunctions, function_name_literal),
+ ).rfn,
.attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone,
};
count += 1;
}
},
- else => unreachable,
+ else => {},
}
// if (singleton) {
@@ -1413,13 +1542,9 @@ pub fn NewClass(
def.staticFunctions = static_functions[0..count].ptr;
}
- if (property_names.len > 0) {
- inline for (comptime property_name_literals) |prop_name, i| {
- property_name_refs[i] = js.JSStringCreateStatic(
- prop_name.ptr,
- prop_name.len,
- );
- static_properties[i] = std.mem.zeroes(js.JSStaticValue);
+ if (comptime property_names.len > 0) {
+ inline for (property_name_literals) |_, i| {
+ static_properties[i] = JSStaticValue_empty;
static_properties[i].getProperty = StaticProperty(i).getter;
const field = comptime @field(properties, property_names[i]);
@@ -1429,7 +1554,7 @@ pub fn NewClass(
}
static_properties[i].name = property_names[i][0.. :0].ptr;
}
- def.staticValues = (&static_properties);
+ def.staticValues = &static_properties;
}
def.className = class_name_str;
@@ -1443,38 +1568,97 @@ pub fn NewClass(
def.callAsFunction = throwInvalidFunctionError;
}
- if (!singleton)
+ if (def.getPropertyNames == null) {
+ def.getPropertyNames = getPropertyNames;
+ }
+
+ if (!singleton and def.hasInstance == null)
def.hasInstance = customHasInstance;
return def;
}
};
}
+const JSValue = JSC.JSValue;
+const ZigString = JSC.ZigString;
+
+pub const PathString = _global.PathString;
+
threadlocal var error_args: [1]js.JSValueRef = undefined;
pub fn JSError(
- allocator: std.mem.Allocator,
+ _: std.mem.Allocator,
comptime fmt: string,
args: anytype,
ctx: js.JSContextRef,
exception: ExceptionValueRef,
) void {
+ @setCold(true);
+
if (comptime std.meta.fields(@TypeOf(args)).len == 0) {
- var message = js.JSStringCreateWithUTF8CString(fmt[0.. :0]);
- defer js.JSStringRelease(message);
- error_args[0] = js.JSValueMakeString(ctx, message);
+ var zig_str = JSC.ZigString.init(fmt);
+ zig_str.detectEncoding();
+ error_args[0] = zig_str.toValueAuto(ctx.ptr()).asObjectRef();
exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null);
} else {
- var buf = std.fmt.allocPrintZ(allocator, fmt, args) catch unreachable;
- defer allocator.free(buf);
+ var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable;
+ var zig_str = JSC.ZigString.init(buf);
+ zig_str.detectEncoding();
- var message = js.JSStringCreateWithUTF8CString(buf);
- defer js.JSStringRelease(message);
-
- error_args[0] = js.JSValueMakeString(ctx, message);
+ error_args[0] = zig_str.toValueGC(ctx.ptr()).asObjectRef();
exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null);
}
}
+pub fn throwTypeError(
+ code: JSC.Node.ErrorCode,
+ comptime fmt: string,
+ args: anytype,
+ ctx: js.JSContextRef,
+ exception: ExceptionValueRef,
+) void {
+ exception.* = toTypeError(code, fmt, args, ctx).asObjectRef();
+}
+
+pub fn toTypeError(
+ code: JSC.Node.ErrorCode,
+ comptime fmt: string,
+ args: anytype,
+ ctx: js.JSContextRef,
+) JSC.JSValue {
+ @setCold(true);
+ var zig_str: JSC.ZigString = undefined;
+ if (comptime std.meta.fields(@TypeOf(args)).len == 0) {
+ zig_str = JSC.ZigString.init(fmt);
+ zig_str.detectEncoding();
+ } else {
+ var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable;
+ zig_str = JSC.ZigString.init(buf);
+ zig_str.detectEncoding();
+ zig_str.mark();
+ }
+ const code_str = ZigString.init(@tagName(code));
+ return JSC.JSValue.createTypeError(&zig_str, &code_str, ctx.ptr());
+}
+
+pub fn throwInvalidArguments(
+ comptime fmt: string,
+ args: anytype,
+ ctx: js.JSContextRef,
+ exception: ExceptionValueRef,
+) void {
+ @setCold(true);
+ return throwTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx, exception);
+}
+
+pub fn toInvalidArguments(
+ comptime fmt: string,
+ args: anytype,
+ ctx: js.JSContextRef,
+) JSC.JSValue {
+ @setCold(true);
+ return toTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx);
+}
+
pub fn getAllocator(_: js.JSContextRef) std.mem.Allocator {
return default_allocator;
}
@@ -1491,14 +1675,78 @@ pub const ArrayBuffer = struct {
typed_array_type: js.JSTypedArrayType,
- pub inline fn slice(this: *const ArrayBuffer) []u8 {
+ encoding: JSC.Node.Encoding = JSC.Node.Encoding.utf8,
+
+ pub const Stream = std.io.FixedBufferStream([]u8);
+
+ pub inline fn stream(this: ArrayBuffer) Stream {
+ return Stream{ .pos = 0, .buf = this.slice() };
+ }
+
+ pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer {
+ return ArrayBuffer{
+ .byte_len = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteLength(ctx, value.asObjectRef(), exception)),
+ .offset = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteOffset(ctx, value.asObjectRef(), exception)),
+ .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetTypedArrayBytesPtr(ctx, value.asObjectRef(), exception).?),
+ // TODO
+ .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array,
+ .len = @truncate(u32, JSC.C.JSObjectGetTypedArrayLength(ctx, value.asObjectRef(), exception)),
+ };
+ }
+
+ pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer {
+ var buffer = ArrayBuffer{
+ .byte_len = @truncate(u32, JSC.C.JSObjectGetArrayBufferByteLength(ctx, value.asObjectRef(), exception)),
+ .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetArrayBufferBytesPtr(ctx, value.asObjectRef(), exception).?),
+ // TODO
+ .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array,
+ .len = 0,
+ .offset = 0,
+ };
+ buffer.len = buffer.byte_len;
+ return buffer;
+ }
+
+ pub inline fn slice(this: *const @This()) []u8 {
return this.ptr[this.offset .. this.offset + this.byte_len];
}
};
pub const MarkedArrayBuffer = struct {
buffer: ArrayBuffer,
- allocator: std.mem.Allocator,
+ allocator: ?std.mem.Allocator = null,
+
+ pub const Stream = ArrayBuffer.Stream;
+
+ pub inline fn stream(this: *MarkedArrayBuffer) Stream {
+ return this.buffer.stream();
+ }
+
+ pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer {
+ return MarkedArrayBuffer{
+ .allocator = null,
+ .buffer = ArrayBuffer.fromTypedArray(ctx, value, exception),
+ };
+ }
+ pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer {
+ return MarkedArrayBuffer{
+ .allocator = null,
+ .buffer = ArrayBuffer.fromArrayBuffer(ctx, value, exception),
+ };
+ }
+
+ pub fn fromString(str: []const u8, allocator: std.mem.Allocator) !MarkedArrayBuffer {
+ var buf = try allocator.dupe(u8, str);
+ return MarkedArrayBuffer.fromBytes(buf, allocator, js.JSTypedArrayType.kJSTypedArrayTypeUint8Array);
+ }
+
+ pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?MarkedArrayBuffer {
+ return switch (value.jsType()) {
+ JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.DataView => fromTypedArray(global.ref(), value, exception),
+ JSC.JSValue.JSType.ArrayBuffer => fromArrayBuffer(global.ref(), value, exception),
+ else => null,
+ };
+ }
pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: js.JSTypedArrayType) MarkedArrayBuffer {
return MarkedArrayBuffer{
@@ -1507,10 +1755,16 @@ pub const MarkedArrayBuffer = struct {
};
}
+ pub inline fn slice(this: *const @This()) []u8 {
+ return this.buffer.slice();
+ }
+
pub fn destroy(this: *MarkedArrayBuffer) void {
const content = this.*;
- content.allocator.free(content.buffer.slice());
- content.allocator.destroy(this);
+ if (this.allocator) |allocator| {
+ allocator.free(content.buffer.slice());
+ allocator.destroy(this);
+ }
}
pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: js.JSTypedArrayType) !*MarkedArrayBuffer {
@@ -1520,9 +1774,11 @@ pub const MarkedArrayBuffer = struct {
return container;
}
- pub fn toJSObjectRef(this: *MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef {
- return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, this, exception);
+ pub fn toJSObjectRef(this: *const MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef {
+ return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, @intToPtr([*]u8, @ptrToInt(this)), exception);
}
+
+ pub const toJS = toJSObjectRef;
};
export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) void {
@@ -1535,10 +1791,19 @@ export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) vo
pub fn castObj(obj: js.JSObjectRef, comptime Type: type) *Type {
return JSPrivateDataPtr.from(js.JSObjectGetPrivate(obj)).as(Type);
}
+
const JSNode = @import("../../js_ast.zig").Macro.JSNode;
const LazyPropertiesObject = @import("../../js_ast.zig").Macro.LazyPropertiesObject;
const ModuleNamespace = @import("../../js_ast.zig").Macro.ModuleNamespace;
const FetchTaskletContext = Fetch.FetchTasklet.FetchTaskletContext;
+const Expect = Test.Expect;
+const DescribeScope = Test.DescribeScope;
+const TestScope = Test.TestScope;
+const ExpectPrototype = Test.ExpectPrototype;
+const NodeFS = JSC.Node.NodeFS;
+const DirEnt = JSC.Node.DirEnt;
+const Stats = JSC.Node.Stats;
+const BigIntStats = JSC.Node.BigIntStats;
pub const JSPrivateDataPtr = TaggedPointerUnion(.{
ResolveError,
BuildError,
@@ -1552,6 +1817,13 @@ pub const JSPrivateDataPtr = TaggedPointerUnion(.{
LazyPropertiesObject,
ModuleNamespace,
FetchTaskletContext,
+ DescribeScope,
+ Expect,
+ ExpectPrototype,
+ NodeFS,
+ Stats,
+ BigIntStats,
+ DirEnt,
});
pub inline fn GetJSPrivateData(comptime Type: type, ref: js.JSObjectRef) ?*Type {
@@ -1567,6 +1839,7 @@ pub const JSPropertyNameIterator = struct {
if (this.i >= this.count) return null;
const i = this.i;
this.i += 1;
+
return js.JSPropertyNameArrayGetNameAtIndex(this.array, i);
}
};
diff --git a/src/javascript/jsc/bindings/BunBuiltinNames.h b/src/javascript/jsc/bindings/BunBuiltinNames.h
new file mode 100644
index 0000000000..7a666df61c
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunBuiltinNames.h
@@ -0,0 +1,85 @@
+// clang-format off
+
+#pragma once
+
+#include "helpers.h"
+#include "root.h"
+#include
+
+
+namespace Bun {
+
+using namespace JSC;
+
+
+#if !defined(BUN_ADDITIONAL_PRIVATE_IDENTIFIERS)
+#define BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro)
+#endif
+
+
+
+
+#define BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(macro) \
+ macro(filePath) \
+ macro(syscall) \
+ macro(errno) \
+ macro(code) \
+ macro(path) \
+ macro(dir) \
+ macro(versions) \
+ macro(argv) \
+ macro(execArgv) \
+ macro(nextTick) \
+ macro(version) \
+ macro(title) \
+ macro(pid) \
+ macro(ppid) \
+ macro(chdir) \
+ macro(cwd) \
+ macro(process) \
+ macro(map) \
+ macro(addEventListener) \
+ macro(removeEventListener) \
+ macro(prependEventListener) \
+ macro(write) \
+ macro(end) \
+ macro(close) \
+ macro(destroy) \
+ macro(cork) \
+ macro(uncork) \
+ macro(isPaused) \
+ macro(read) \
+ macro(pipe) \
+ macro(unpipe) \
+ macro(once) \
+ macro(on) \
+ macro(unshift) \
+ macro(resume) \
+ macro(pause) \
+ BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) \
+
+class BunBuiltinNames {
+public:
+ // FIXME: Remove the __attribute__((nodebug)) when is fixed.
+#if COMPILER(CLANG)
+ __attribute__((nodebug))
+#endif
+ explicit BunBuiltinNames(JSC::VM& vm)
+ : m_vm(vm)
+ BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(INITIALIZE_BUILTIN_NAMES)
+ {
+#define EXPORT_NAME(name) m_vm.propertyNames->appendExternalName(name##PublicName(), name##PrivateName());
+ BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(EXPORT_NAME)
+#undef EXPORT_NAME
+ }
+
+
+ BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_IDENTIFIER_ACCESSOR)
+
+private:
+ JSC::VM& m_vm;
+ BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_NAMES)
+};
+
+} // namespace Bun
+
diff --git a/src/javascript/jsc/bindings/BunClientData.cpp b/src/javascript/jsc/bindings/BunClientData.cpp
new file mode 100644
index 0000000000..a86720a855
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunClientData.cpp
@@ -0,0 +1,33 @@
+
+#include "BunClientData.h"
+#include "root.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+// #include "BunGCOutputConstraint.h"
+
+namespace Bun {
+using namespace JSC;
+
+JSVMClientData::JSVMClientData(VM &vm) : m_builtinNames(vm) {}
+
+JSVMClientData::~JSVMClientData() {}
+
+void JSVMClientData::create(VM *vm) {
+ JSVMClientData *clientData = new JSVMClientData(*vm);
+ vm->clientData = clientData; // ~VM deletes this pointer.
+
+ // vm->heap.addMarkingConstraint(makeUnique(*vm, *clientData));
+
+ // vm->m_typedArrayController = adoptRef(new WebCoreTypedArrayController(
+ // type == WorkerThreadType::DedicatedWorker || type == WorkerThreadType::Worklet));
+}
+
+} // namespace Bun
\ No newline at end of file
diff --git a/src/javascript/jsc/bindings/BunClientData.h b/src/javascript/jsc/bindings/BunClientData.h
new file mode 100644
index 0000000000..cd506365f1
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunClientData.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include "BunBuiltinNames.h"
+#include "root.h"
+#include
+#include
+#include
+
+namespace Bun {
+using namespace JSC;
+
+class JSVMClientData : public JSC::VM::ClientData {
+ WTF_MAKE_NONCOPYABLE(JSVMClientData);
+ WTF_MAKE_FAST_ALLOCATED;
+
+ public:
+ explicit JSVMClientData(JSC::VM &);
+
+ virtual ~JSVMClientData();
+
+ static void create(JSC::VM *);
+
+ BunBuiltinNames &builtinNames() { return m_builtinNames; }
+
+ // Vector &outputConstraintSpaces() { return m_outputConstraintSpaces; }
+
+ // template void forEachOutputConstraintSpace(const Func &func) {
+ // for (auto *space : m_outputConstraintSpaces) func(*space);
+ // }
+
+ private:
+ BunBuiltinNames m_builtinNames;
+
+ // Vector m_outputConstraintSpaces;
+};
+
+static JSVMClientData *clientData(JSC::VM &vm) {
+ return static_cast(vm.clientData);
+}
+
+} // namespace Bun
diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp
new file mode 100644
index 0000000000..bc99ef2e22
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp
@@ -0,0 +1,47 @@
+
+
+// #include "BunGCOutputConstraint.h"
+
+// #include "BunClientData.h"
+// #include
+// #include
+// #include
+// #include
+// #include
+// #include
+
+// namespace Bun {
+
+// using namespace JSC;
+
+// BunGCOutputConstraint::BunGCOutputConstraint(VM &vm, Bun::JSVMClientData &clientData)
+// : MarkingConstraint("Domo", "DOM Output", ConstraintVolatility::SeldomGreyed,
+// ConstraintConcurrency::Concurrent, ConstraintParallelism::Parallel),
+// m_vm(vm),
+// m_clientData(clientData),
+// m_lastExecutionVersion(vm.heap.mutatorExecutionVersion()) {}
+
+// template void BunGCOutputConstraint::executeImplImpl(Visitor &visitor) {
+// Heap &heap = m_vm.heap;
+
+// if (heap.mutatorExecutionVersion() == m_lastExecutionVersion) return;
+
+// m_lastExecutionVersion = heap.mutatorExecutionVersion();
+
+// m_clientData.forEachOutputConstraintSpace([&](Subspace &subspace) {
+// auto func = [](Visitor &visitor, HeapCell *heapCell, HeapCell::Kind) {
+// SetRootMarkReasonScope rootScope(visitor, RootMarkReason::DOMGCOutput);
+// JSCell *cell = static_cast(heapCell);
+// cell->methodTable(visitor.vm())->visitOutputConstraints(cell, visitor);
+// };
+
+// RefPtr> task =
+// subspace.template forEachMarkedCellInParallel(func);
+// visitor.addParallelConstraintTask(task);
+// });
+// }
+
+// void BunGCOutputConstraint::executeImpl(AbstractSlotVisitor &visitor) { executeImplImpl(visitor);
+// } void BunGCOutputConstraint::executeImpl(SlotVisitor &visitor) { executeImplImpl(visitor); }
+
+// } // namespace Bun
diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.h b/src/javascript/jsc/bindings/BunGCOutputConstraint.h
new file mode 100644
index 0000000000..521b0da8cb
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.h
@@ -0,0 +1,34 @@
+
+// #pragma once
+
+// #include "root.h"
+// #include
+
+// namespace JSC {
+// class VM;
+// }
+
+// namespace Bun {
+
+// class JSVMClientData;
+
+// class BunGCOutputConstraint : public JSC::MarkingConstraint {
+// WTF_MAKE_FAST_ALLOCATED;
+
+// public:
+// BunGCOutputConstraint(JSC::VM &, Bun::JSVMClientData &);
+// ~BunGCOutputConstraint(){};
+
+// protected:
+// void executeImpl(JSC::AbstractSlotVisitor &) override;
+// void executeImpl(JSC::SlotVisitor &) override;
+
+// private:
+// template void executeImplImpl(Visitor &);
+
+// JSC::VM &m_vm;
+// JSVMClientData &m_clientData;
+// uint64_t m_lastExecutionVersion;
+// };
+
+// } // namespace Bun
diff --git a/src/javascript/jsc/bindings/BunStream.cpp b/src/javascript/jsc/bindings/BunStream.cpp
new file mode 100644
index 0000000000..8c45feb40b
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunStream.cpp
@@ -0,0 +1,485 @@
+#include "BunStream.h"
+#include
+#include
+
+namespace Bun {
+using JSGlobalObject = JSC::JSGlobalObject;
+using Exception = JSC::Exception;
+using JSValue = JSC::JSValue;
+using JSString = JSC::JSString;
+using JSModuleLoader = JSC::JSModuleLoader;
+using JSModuleRecord = JSC::JSModuleRecord;
+using Identifier = JSC::Identifier;
+using SourceOrigin = JSC::SourceOrigin;
+using JSObject = JSC::JSObject;
+using JSNonFinalObject = JSC::JSNonFinalObject;
+namespace JSCastingHelpers = JSC::JSCastingHelpers;
+
+static ReadableEvent getReadableEvent(const WTF::String &eventName);
+static ReadableEvent getReadableEvent(const WTF::String &eventName) {
+ if (eventName == "close")
+ return ReadableEvent__Close;
+ else if (eventName == "data")
+ return ReadableEvent__Data;
+ else if (eventName == "end")
+ return ReadableEvent__End;
+ else if (eventName == "error")
+ return ReadableEvent__Error;
+ else if (eventName == "pause")
+ return ReadableEvent__Pause;
+ else if (eventName == "readable")
+ return ReadableEvent__Readable;
+ else if (eventName == "resume")
+ return ReadableEvent__Resume;
+ else if (eventName == "open")
+ return ReadableEvent__Open;
+ else
+ return ReadableEventUser;
+}
+
+static WritableEvent getWritableEvent(const WTF::String &eventName);
+static WritableEvent getWritableEvent(const WTF::String &eventName) {
+ if (eventName == "close")
+ return WritableEvent__Close;
+ else if (eventName == "drain")
+ return WritableEvent__Drain;
+ else if (eventName == "error")
+ return WritableEvent__Error;
+ else if (eventName == "finish")
+ return WritableEvent__Finish;
+ else if (eventName == "pipe")
+ return WritableEvent__Pipe;
+ else if (eventName == "unpipe")
+ return WritableEvent__Unpipe;
+ else if (eventName == "open")
+ return WritableEvent__Open;
+ else
+ return WritableEventUser;
+}
+
+// clang-format off
+#define DEFINE_CALLBACK_FUNCTION_BODY(TypeName, ZigFunction) JSC::VM& vm = globalObject->vm(); \
+ auto* thisObject = JSC::jsDynamicCast(vm, callFrame->thisValue()); \
+ auto scope = DECLARE_THROW_SCOPE(vm); \
+ if (!thisObject) \
+ return throwVMTypeError(globalObject, scope); \
+ auto argCount = static_cast(callFrame->argumentCount()); \
+ WTF::Vector arguments; \
+ arguments.reserveInitialCapacity(argCount); \
+ if (argCount) { \
+ for (uint16_t i = 0; i < argCount; ++i) { \
+ arguments.uncheckedAppend(JSC::JSValue::encode(callFrame->uncheckedArgument(i))); \
+ } \
+ } \
+ JSC::JSValue result = JSC::JSValue::decode( \
+ ZigFunction(thisObject->state, globalObject, arguments.data(), argCount) \
+ ); \
+ JSC::JSObject *obj = result.getObject(); \
+ if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { \
+ scope.throwException(globalObject, obj); \
+ return JSC::JSValue::encode(JSC::jsUndefined()); \
+ } \
+ if (UNLIKELY(scope.exception())) \
+ return JSC::JSValue::encode(JSC::jsUndefined()); \
+ return JSC::JSValue::encode(result);
+
+// clang-format on
+// static JSC_DECLARE_HOST_FUNCTION(Writable__addEventListener);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__addEventListener);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__prependListener);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__prependListener);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__prependOnceListener);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__prependOnceListener);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__setMaxListeners);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__setMaxListeners);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__getMaxListeners);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__getMaxListeners);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__setDefaultEncoding);
+static JSC_DECLARE_HOST_FUNCTION(Readable__on);
+// static JSC_DECLARE_HOST_FUNCTION(Readable__off);
+static JSC_DECLARE_HOST_FUNCTION(Readable__once);
+static JSC_DECLARE_HOST_FUNCTION(Readable__pause);
+static JSC_DECLARE_HOST_FUNCTION(Readable__pipe);
+static JSC_DECLARE_HOST_FUNCTION(Readable__read);
+static JSC_DECLARE_HOST_FUNCTION(Readable__resume);
+static JSC_DECLARE_HOST_FUNCTION(Readable__unpipe);
+static JSC_DECLARE_HOST_FUNCTION(Readable__unshift);
+
+static JSC_DECLARE_HOST_FUNCTION(Writable__close);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__off);
+static JSC_DECLARE_HOST_FUNCTION(Writable__cork);
+static JSC_DECLARE_HOST_FUNCTION(Writable__destroy);
+static JSC_DECLARE_HOST_FUNCTION(Writable__end);
+static JSC_DECLARE_HOST_FUNCTION(Writable__on);
+static JSC_DECLARE_HOST_FUNCTION(Writable__once);
+static JSC_DECLARE_HOST_FUNCTION(Writable__uncork);
+static JSC_DECLARE_HOST_FUNCTION(Writable__write);
+
+static JSC_DEFINE_HOST_FUNCTION(Readable__on,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); }
+ JSC::VM &vm = globalObject->vm();
+ auto scope = DECLARE_THROW_SCOPE(vm);
+
+ auto thisObject = JSC::jsDynamicCast(vm, callFrame->thisValue());
+ if (UNLIKELY(!thisObject)) {
+ scope.release();
+ JSC::throwVMTypeError(globalObject, scope);
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto eventName = callFrame->argument(0).toStringOrNull(globalObject);
+ if (UNLIKELY(!eventName)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ ReadableEvent event = getReadableEvent(eventName->value(globalObject));
+ if (event == ReadableEventUser) {
+ // TODO:
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto listener = callFrame->argument(1);
+ JSC::JSObject *object = listener.getObject();
+ if (UNLIKELY(!object) || !listener.isCallable(vm)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ Bun__Readable__addEventListener(thisObject->state, globalObject, event,
+ JSC::JSValue::encode(listener), true);
+
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
+extern "C" Bun__Readable *JSC__JSValue__getReadableStreamState(JSC__JSValue value, JSC__VM *vm) {
+ auto *thisObject = JSC::jsDynamicCast(*vm, JSC::JSValue::decode(value));
+ if (UNLIKELY(!thisObject)) { return nullptr; }
+ return thisObject->state;
+}
+extern "C" Bun__Writable *JSC__JSValue__getWritableStreamState(JSC__JSValue value, JSC__VM *vm) {
+ auto *thisObject = JSC::jsDynamicCast(*vm, JSC::JSValue::decode(value));
+ if (UNLIKELY(!thisObject)) { return nullptr; }
+ return thisObject->state;
+}
+
+const JSC::ClassInfo Readable::s_info = {"Readable", &Base::s_info, nullptr, nullptr,
+ CREATE_METHOD_TABLE(Readable)};
+
+const JSC::ClassInfo Writable::s_info = {"Writable", &Base::s_info, nullptr, nullptr,
+ CREATE_METHOD_TABLE(Writable)};
+
+static JSC_DEFINE_HOST_FUNCTION(Readable__once,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); }
+ JSC::VM &vm = globalObject->vm();
+ auto scope = DECLARE_THROW_SCOPE(vm);
+
+ auto thisObject = JSC::jsDynamicCast(vm, callFrame->thisValue());
+ if (UNLIKELY(!thisObject)) {
+ scope.release();
+ JSC::throwVMTypeError(globalObject, scope);
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto eventName = callFrame->argument(0).toStringOrNull(globalObject);
+ if (UNLIKELY(!eventName)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ ReadableEvent event = getReadableEvent(eventName->value(globalObject));
+ if (event == ReadableEventUser) {
+ // TODO:
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto listener = callFrame->argument(1);
+ JSC::JSObject *object = listener.getObject();
+ if (UNLIKELY(!object) || !listener.isCallable(vm)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ Bun__Readable__addEventListener(thisObject->state, globalObject, event,
+ JSC::JSValue::encode(listener), true);
+
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Writable__on,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); }
+ JSC::VM &vm = globalObject->vm();
+ auto scope = DECLARE_THROW_SCOPE(vm);
+
+ auto thisObject = JSC::jsDynamicCast(vm, callFrame->thisValue());
+ if (UNLIKELY(!thisObject)) {
+ scope.release();
+ JSC::throwVMTypeError(globalObject, scope);
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto eventName = callFrame->argument(0).toStringOrNull(globalObject);
+ if (UNLIKELY(!eventName)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ WritableEvent event = getWritableEvent(eventName->value(globalObject));
+ if (event == WritableEventUser) {
+ // TODO:
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto listener = callFrame->argument(1);
+ JSC::JSObject *object = listener.getObject();
+ if (UNLIKELY(!object) || !listener.isCallable(vm)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ Bun__Writable__addEventListener(thisObject->state, globalObject, event,
+ JSC::JSValue::encode(listener), false);
+
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Writable__once,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); }
+ JSC::VM &vm = globalObject->vm();
+ auto scope = DECLARE_THROW_SCOPE(vm);
+
+ auto thisObject = JSC::jsDynamicCast(vm, callFrame->thisValue());
+ if (UNLIKELY(!thisObject)) {
+ scope.release();
+ JSC::throwVMTypeError(globalObject, scope);
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto eventName = callFrame->argument(0).toStringOrNull(globalObject);
+ if (UNLIKELY(!eventName)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ WritableEvent event = getWritableEvent(eventName->value(globalObject));
+ if (event == WritableEventUser) {
+ // TODO:
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ auto listener = callFrame->argument(1);
+ JSC::JSObject *object = listener.getObject();
+ if (UNLIKELY(!object) || !listener.isCallable(vm)) {
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+ }
+
+ Bun__Writable__addEventListener(thisObject->state, globalObject, event,
+ JSC::JSValue::encode(listener), true);
+
+ scope.release();
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Readable__read,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__read);
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Readable__pipe,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pipe);
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Readable__resume,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__resume);
+}
+static JSC_DEFINE_HOST_FUNCTION(Readable__unpipe,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unpipe);
+}
+static JSC_DEFINE_HOST_FUNCTION(Readable__pause,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pause);
+}
+static JSC_DEFINE_HOST_FUNCTION(Readable__unshift,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unshift);
+}
+
+// static JSC_DECLARE_HOST_FUNCTION(Readable__isPaused);
+// static JSC_DECLARE_HOST_FUNCTION(Writable__setDefaultEncoding);
+
+// static DEFINE_CALLBACK_FUNCTION(Writable__setDefaultEncoding, Bun::Writable,
+// Bun__Writable__setDefaultEncoding);
+
+static JSC_DEFINE_HOST_FUNCTION(Writable__write,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__write);
+}
+static JSC_DEFINE_HOST_FUNCTION(Writable__end,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__end);
+}
+static JSC_DEFINE_HOST_FUNCTION(Writable__close,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__close);
+}
+static JSC_DEFINE_HOST_FUNCTION(Writable__destroy,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__destroy);
+}
+static JSC_DEFINE_HOST_FUNCTION(Writable__cork,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__cork);
+}
+static JSC_DEFINE_HOST_FUNCTION(Writable__uncork,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__uncork);
+}
+
+extern "C" JSC__JSValue Bun__Readable__create(Bun__Readable *state,
+ JSC__JSGlobalObject *globalObject) {
+ JSC::JSValue result = JSC::JSValue(Readable::create(
+ globalObject->vm(), state,
+ Readable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype())));
+
+ return JSC::JSValue::encode(result);
+}
+extern "C" JSC__JSValue Bun__Writable__create(Bun__Writable *state,
+ JSC__JSGlobalObject *globalObject) {
+ JSC::JSValue result = JSC::JSValue(Writable::create(
+ globalObject->vm(), state,
+ Writable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype())));
+
+ return JSC::JSValue::encode(result);
+}
+
+Readable::~Readable() {
+ if (this->state) { Bun__Readable__deinit(this->state); }
+}
+
+Writable::~Writable() {
+ if (this->state) { Bun__Writable__deinit(this->state); }
+}
+
+void Readable::finishCreation(JSC::VM &vm) {
+ Base::finishCreation(vm);
+ auto clientData = Bun::clientData(vm);
+ auto *globalObject = this->globalObject();
+
+ putDirect(vm, clientData->builtinNames().onPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().onPublicName().string(), Readable__on),
+ 0);
+ putDirect(vm, clientData->builtinNames().oncePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().oncePublicName().string(),
+ Readable__once),
+ 0);
+ putDirect(vm, clientData->builtinNames().pausePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().pausePublicName().string(),
+ Readable__pause),
+ 0);
+ putDirect(vm, clientData->builtinNames().pipePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().pipePublicName().string(),
+ Readable__pipe),
+ 0);
+ putDirect(vm, clientData->builtinNames().readPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().readPublicName().string(),
+ Readable__read),
+ 0);
+ putDirect(vm, clientData->builtinNames().resumePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().resumePublicName().string(),
+ Readable__resume),
+ 0);
+ putDirect(vm, clientData->builtinNames().unpipePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().unpipePublicName().string(),
+ Readable__unpipe),
+ 0);
+ putDirect(vm, clientData->builtinNames().unshiftPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().unshiftPublicName().string(),
+ Readable__unshift),
+ 0);
+}
+
+void Writable::finishCreation(JSC::VM &vm) {
+ Base::finishCreation(vm);
+ auto clientData = Bun::clientData(vm);
+
+ auto *globalObject = this->globalObject();
+
+ putDirect(vm, clientData->builtinNames().onPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().onPublicName().string(), Writable__on),
+ 0);
+
+ putDirect(vm, clientData->builtinNames().oncePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().oncePublicName().string(),
+ Writable__once),
+ 0);
+
+ putDirect(vm, clientData->builtinNames().closePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().closePublicName().string(),
+ Writable__close),
+ 0);
+ putDirect(vm, clientData->builtinNames().corkPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().corkPublicName().string(),
+ Writable__cork),
+ 0);
+ putDirect(vm, clientData->builtinNames().destroyPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().destroyPublicName().string(),
+ Writable__destroy),
+ 0);
+ putDirect(vm, clientData->builtinNames().endPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().endPublicName().string(), Writable__end),
+ 0);
+ putDirect(vm, clientData->builtinNames().onPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().onPublicName().string(), Writable__on),
+ 0);
+ putDirect(vm, clientData->builtinNames().oncePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().oncePublicName().string(),
+ Writable__once),
+ 0);
+ putDirect(vm, clientData->builtinNames().uncorkPublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().uncorkPublicName().string(),
+ Writable__uncork),
+ 0);
+ putDirect(vm, clientData->builtinNames().writePublicName(),
+ JSFunction::create(vm, globalObject, 2,
+ clientData->builtinNames().writePublicName().string(),
+ Writable__write),
+ 0);
+}
+
+} // namespace Bun
\ No newline at end of file
diff --git a/src/javascript/jsc/bindings/BunStream.h b/src/javascript/jsc/bindings/BunStream.h
new file mode 100644
index 0000000000..37762d6897
--- /dev/null
+++ b/src/javascript/jsc/bindings/BunStream.h
@@ -0,0 +1,82 @@
+#pragma once
+
+#include "BunBuiltinNames.h"
+#include "BunClientData.h"
+#include "root.h"
+
+namespace Bun {
+
+using namespace JSC;
+
+class Readable : public JSC::JSNonFinalObject {
+ using Base = JSC::JSNonFinalObject;
+
+ public:
+ Bun__Readable *state;
+ Readable(JSC::VM &vm, Bun__Readable *readable, JSC::Structure *structure) : Base(vm, structure) {
+ state = readable;
+ }
+
+ ~Readable();
+
+ DECLARE_INFO;
+
+ static constexpr unsigned StructureFlags = Base::StructureFlags;
+
+ template
+ static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) {
+ return &vm.cellSpace;
+ }
+
+ static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject,
+ JSC::JSValue prototype) {
+ return JSC::Structure::create(vm, globalObject, prototype,
+ JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());
+ }
+
+ static Readable *create(JSC::VM &vm, Bun__Readable *state, JSC::Structure *structure) {
+ Readable *accessor =
+ new (NotNull, JSC::allocateCell(vm.heap)) Readable(vm, state, structure);
+ accessor->finishCreation(vm);
+ return accessor;
+ }
+
+ void finishCreation(JSC::VM &vm);
+};
+
+class Writable : public JSC::JSNonFinalObject {
+ using Base = JSC::JSNonFinalObject;
+
+ public:
+ Bun__Writable *state;
+ Writable(JSC::VM &vm, Bun__Writable *writable, JSC::Structure *structure) : Base(vm, structure) {
+ state = writable;
+ }
+
+ DECLARE_INFO;
+
+ static constexpr unsigned StructureFlags = Base::StructureFlags;
+
+ template
+ static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) {
+ return &vm.cellSpace;
+ }
+
+ static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject,
+ JSC::JSValue prototype) {
+ return JSC::Structure::create(vm, globalObject, prototype,
+ JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());
+ }
+
+ static Writable *create(JSC::VM &vm, Bun__Writable *state, JSC::Structure *structure) {
+ Writable *accessor =
+ new (NotNull, JSC::allocateCell(vm.heap)) Writable(vm, state, structure);
+ accessor->finishCreation(vm);
+ return accessor;
+ }
+ ~Writable();
+
+ void finishCreation(JSC::VM &vm);
+};
+
+} // namespace Bun
\ No newline at end of file
diff --git a/src/javascript/jsc/bindings/Process.cpp b/src/javascript/jsc/bindings/Process.cpp
new file mode 100644
index 0000000000..754c1d96b5
--- /dev/null
+++ b/src/javascript/jsc/bindings/Process.cpp
@@ -0,0 +1,340 @@
+#include "Process.h"
+#include
+#include
+
+#pragma mark - Node.js Process
+
+namespace Zig {
+
+using JSGlobalObject = JSC::JSGlobalObject;
+using Exception = JSC::Exception;
+using JSValue = JSC::JSValue;
+using JSString = JSC::JSString;
+using JSModuleLoader = JSC::JSModuleLoader;
+using JSModuleRecord = JSC::JSModuleRecord;
+using Identifier = JSC::Identifier;
+using SourceOrigin = JSC::SourceOrigin;
+using JSObject = JSC::JSObject;
+using JSNonFinalObject = JSC::JSNonFinalObject;
+namespace JSCastingHelpers = JSC::JSCastingHelpers;
+
+static JSC_DECLARE_CUSTOM_SETTER(Process_setTitle);
+static JSC_DECLARE_CUSTOM_GETTER(Process_getArgv);
+static JSC_DECLARE_CUSTOM_SETTER(Process_setArgv);
+static JSC_DECLARE_CUSTOM_GETTER(Process_getTitle);
+static JSC_DECLARE_CUSTOM_GETTER(Process_getVersionsLazy);
+static JSC_DECLARE_CUSTOM_SETTER(Process_setVersionsLazy);
+
+static JSC_DECLARE_CUSTOM_GETTER(Process_getPID);
+static JSC_DECLARE_CUSTOM_GETTER(Process_getPPID);
+
+static JSC_DECLARE_HOST_FUNCTION(Process_functionCwd);
+
+static JSC_DECLARE_HOST_FUNCTION(Process_functionNextTick);
+static JSC_DEFINE_HOST_FUNCTION(Process_functionNextTick,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ JSC::VM &vm = globalObject->vm();
+ auto argCount = callFrame->argumentCount();
+ if (argCount == 0) {
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::throwTypeError(globalObject, scope, "nextTick requires 1 argument (a function)"_s);
+ return JSC::JSValue::encode(JSC::JSValue{});
+ }
+
+ JSC::JSValue job = callFrame->uncheckedArgument(0);
+
+ if (!job.isObject() || !job.getObject()->isCallable(vm)) {
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::throwTypeError(globalObject, scope, "nextTick expects a function"_s);
+ return JSC::JSValue::encode(JSC::JSValue{});
+ }
+
+ switch (argCount) {
+
+ case 1: {
+ // This is a JSC builtin function
+ globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job));
+ break;
+ }
+
+ case 2:
+ case 3:
+ case 4:
+ case 5: {
+ JSC::JSValue argument0 = callFrame->uncheckedArgument(1);
+ JSC::JSValue argument1 = argCount > 2 ? callFrame->uncheckedArgument(2) : JSC::JSValue{};
+ JSC::JSValue argument2 = argCount > 3 ? callFrame->uncheckedArgument(3) : JSC::JSValue{};
+ JSC::JSValue argument3 = argCount > 4 ? callFrame->uncheckedArgument(4) : JSC::JSValue{};
+ globalObject->queueMicrotask(
+ JSC::createJSMicrotask(vm, job, argument0, argument1, argument2, argument3));
+ break;
+ }
+
+ default: {
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::throwTypeError(globalObject, scope,
+ "nextTick doesn't support more than 4 arguments currently"_s);
+ return JSC::JSValue::encode(JSC::JSValue{});
+
+ break;
+ }
+
+ // JSC::MarkedArgumentBuffer args;
+ // for (unsigned i = 1; i < callFrame->argumentCount(); i++) {
+ // args.append(callFrame->uncheckedArgument(i));
+ // }
+
+ // JSC::ArgList argsList(args);
+ // JSC::gcProtect(job);
+ // JSC::JSFunction *callback = JSC::JSNativeStdFunction::create(
+ // vm, globalObject, 0, String(),
+ // [job, &argsList](JSC::JSGlobalObject *globalObject, JSC::CallFrame *callFrame) {
+ // JSC::VM &vm = globalObject->vm();
+ // auto callData = getCallData(vm, job);
+
+ // return JSC::JSValue::encode(JSC::call(globalObject, job, callData, job, argsList));
+ // });
+
+ // globalObject->queueMicrotask(JSC::createJSMicrotask(vm, JSC::JSValue(callback)));
+ }
+
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
+static JSC_DECLARE_HOST_FUNCTION(Process_functionChdir);
+
+static JSC_DEFINE_HOST_FUNCTION(Process_functionChdir,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+
+ ZigString str = ZigString{nullptr, 0};
+ if (callFrame->argumentCount() > 0) {
+ str = Zig::toZigString(callFrame->uncheckedArgument(0).toWTFString(globalObject));
+ }
+
+ JSC::JSValue result = JSC::JSValue::decode(Bun__Process__setCwd(globalObject, &str));
+ JSC::JSObject *obj = result.getObject();
+ if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) {
+ scope.throwException(globalObject, obj);
+ return JSValue::encode(JSC::jsUndefined());
+ }
+
+ return JSC::JSValue::encode(result);
+}
+
+void Process::finishCreation(JSC::VM &vm) {
+ Base::finishCreation(vm);
+ auto clientData = Bun::clientData(vm);
+
+ putDirectCustomAccessor(vm, clientData->builtinNames().pidPublicName(),
+ JSC::CustomGetterSetter::create(vm, Process_getPID, nullptr),
+ static_cast(JSC::PropertyAttribute::CustomValue));
+
+ putDirectCustomAccessor(vm, clientData->builtinNames().ppidPublicName(),
+ JSC::CustomGetterSetter::create(vm, Process_getPPID, nullptr),
+ static_cast(JSC::PropertyAttribute::CustomValue));
+
+ putDirectCustomAccessor(vm, clientData->builtinNames().titlePublicName(),
+ JSC::CustomGetterSetter::create(vm, Process_getTitle, Process_setTitle),
+ static_cast(JSC::PropertyAttribute::CustomValue));
+
+ putDirectCustomAccessor(vm, clientData->builtinNames().argvPublicName(),
+ JSC::CustomGetterSetter::create(vm, Process_getArgv, Process_setArgv),
+ static_cast(JSC::PropertyAttribute::CustomValue));
+
+ this->putDirect(vm, clientData->builtinNames().nextTickPublicName(),
+ JSC::JSFunction::create(vm, JSC::jsCast(globalObject()), 0,
+ WTF::String("nextTick"), Process_functionNextTick),
+ 0);
+
+ this->putDirect(vm, clientData->builtinNames().cwdPublicName(),
+ JSC::JSFunction::create(vm, JSC::jsCast(globalObject()), 0,
+ WTF::String("cwd"), Process_functionCwd),
+ 0);
+
+ this->putDirect(vm, clientData->builtinNames().chdirPublicName(),
+ JSC::JSFunction::create(vm, JSC::jsCast(globalObject()), 0,
+ WTF::String("chdir"), Process_functionChdir),
+ 0);
+
+ putDirectCustomAccessor(
+ vm, clientData->builtinNames().versionsPublicName(),
+ JSC::CustomGetterSetter::create(vm, Process_getVersionsLazy, Process_setVersionsLazy), 0);
+ // this should be transpiled out, but just incase
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"),
+ JSC::JSValue(false));
+
+ this->putDirect(this->vm(), clientData->builtinNames().versionPublicName(),
+ JSC::jsString(this->vm(), WTF::String(Bun__version)));
+
+ // this gives some way of identifying at runtime whether the SSR is happening in node or not.
+ // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS"
+ // but it must be something that won't evaluate to truthy in Node.js
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"), JSC::JSValue(true));
+#if defined(__APPLE__)
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"),
+ JSC::jsString(this->vm(), WTF::String("darwin")));
+#else
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"),
+ JSC::jsString(this->vm(), WTF::String("linux")));
+#endif
+
+#if defined(__x86_64__)
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"),
+ JSC::jsString(this->vm(), WTF::String("x64")));
+#elif defined(__i386__)
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"),
+ JSC::jsString(this->vm(), WTF::String("x86")));
+#elif defined(__arm__)
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"),
+ JSC::jsString(this->vm(), WTF::String("arm")));
+#elif defined(__aarch64__)
+ this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"),
+ JSC::jsString(this->vm(), WTF::String("arm64")));
+#endif
+}
+
+const JSC::ClassInfo Process::s_info = {"Process", &Base::s_info, nullptr, nullptr,
+ CREATE_METHOD_TABLE(Process)};
+
+JSC_DEFINE_CUSTOM_GETTER(Process_getTitle, (JSC::JSGlobalObject * globalObject,
+ JSC::EncodedJSValue thisValue, JSC::PropertyName)) {
+ ZigString str;
+ Bun__Process__getTitle(globalObject, &str);
+ return JSValue::encode(Zig::toJSStringValue(str, globalObject));
+}
+
+JSC_DEFINE_CUSTOM_SETTER(Process_setTitle,
+ (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue,
+ JSC::EncodedJSValue value, JSC::PropertyName)) {
+ JSC::VM &vm = globalObject->vm();
+
+ JSC::JSObject *thisObject = JSC::jsDynamicCast(vm, JSValue::decode(thisValue));
+ JSC::JSString *jsString = JSC::jsDynamicCast(vm, JSValue::decode(value));
+ if (!thisObject || !jsString) { return false; }
+
+ ZigString str = Zig::toZigString(jsString, globalObject);
+ Bun__Process__setTitle(globalObject, &str);
+
+ return true;
+}
+
+JSC_DEFINE_CUSTOM_GETTER(Process_getArgv, (JSC::JSGlobalObject * globalObject,
+ JSC::EncodedJSValue thisValue, JSC::PropertyName)) {
+ JSC::VM &vm = globalObject->vm();
+
+ Zig::Process *thisObject = JSC::jsDynamicCast(vm, JSValue::decode(thisValue));
+ if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); }
+ auto clientData = Bun::clientData(vm);
+
+ if (JSC::JSValue argv = thisObject->getIfPropertyExists(
+ globalObject, clientData->builtinNames().argvPrivateName())) {
+ return JSValue::encode(argv);
+ }
+
+ JSC::EncodedJSValue argv_ = Bun__Process__getArgv(globalObject);
+ thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(),
+ JSC::JSValue::decode(argv_));
+
+ return argv_;
+}
+
+JSC_DEFINE_CUSTOM_SETTER(Process_setArgv,
+ (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue,
+ JSC::EncodedJSValue value, JSC::PropertyName)) {
+ JSC::VM &vm = globalObject->vm();
+
+ JSC::JSObject *thisObject = JSC::jsDynamicCast(vm, JSValue::decode(thisValue));
+ if (!thisObject) { return false; }
+
+ auto clientData = Bun::clientData(vm);
+
+ return thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(),
+ JSC::JSValue::decode(value));
+}
+
+JSC_DEFINE_CUSTOM_GETTER(Process_getPID, (JSC::JSGlobalObject * globalObject,
+ JSC::EncodedJSValue thisValue, JSC::PropertyName)) {
+ return JSC::JSValue::encode(JSC::JSValue(getpid()));
+}
+
+JSC_DEFINE_CUSTOM_GETTER(Process_getPPID, (JSC::JSGlobalObject * globalObject,
+ JSC::EncodedJSValue thisValue, JSC::PropertyName)) {
+ return JSC::JSValue::encode(JSC::JSValue(getppid()));
+}
+
+JSC_DEFINE_CUSTOM_GETTER(Process_getVersionsLazy,
+ (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue,
+ JSC::PropertyName)) {
+ JSC::VM &vm = globalObject->vm();
+ auto clientData = Bun::clientData(vm);
+
+ Zig::Process *thisObject = JSC::jsDynamicCast(vm, JSValue::decode(thisValue));
+ if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); }
+
+ if (JSC::JSValue argv = thisObject->getIfPropertyExists(
+ globalObject, clientData->builtinNames().versionsPrivateName())) {
+ return JSValue::encode(argv);
+ }
+
+ JSC::JSObject *object =
+ JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 9);
+
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "node"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String("17.0.0"))));
+ object->putDirect(
+ vm, JSC::Identifier::fromString(vm, "bun"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__version + 1 /* prefix with v */))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_webkit))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "mimalloc"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_mimalloc))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "libarchive"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_libarchive))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "picohttpparser"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_picohttpparser))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "boringssl"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_boringssl))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "zlib"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zlib))));
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "zig"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zig))));
+
+ object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"),
+ JSC::JSValue(JSC::jsString(vm, WTF::String("67"))));
+
+ thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(), object);
+ return JSC::JSValue::encode(object);
+}
+JSC_DEFINE_CUSTOM_SETTER(Process_setVersionsLazy,
+ (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue,
+ JSC::EncodedJSValue value, JSC::PropertyName)) {
+
+ JSC::VM &vm = globalObject->vm();
+ auto clientData = Bun::clientData(vm);
+
+ Zig::Process *thisObject = JSC::jsDynamicCast(vm, JSValue::decode(thisValue));
+ if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); }
+
+ thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(),
+ JSC::JSValue::decode(value));
+
+ return true;
+}
+
+static JSC_DEFINE_HOST_FUNCTION(Process_functionCwd,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::JSValue result = JSC::JSValue::decode(Bun__Process__getCwd(globalObject));
+ JSC::JSObject *obj = result.getObject();
+ if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) {
+ scope.throwException(globalObject, obj);
+ return JSValue::encode(JSC::jsUndefined());
+ }
+
+ return JSC::JSValue::encode(result);
+}
+
+} // namespace Zig
\ No newline at end of file
diff --git a/src/javascript/jsc/bindings/Process.h b/src/javascript/jsc/bindings/Process.h
new file mode 100644
index 0000000000..7e025bc3a5
--- /dev/null
+++ b/src/javascript/jsc/bindings/Process.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include "BunBuiltinNames.h"
+#include "BunClientData.h"
+#include "root.h"
+
+namespace Zig {
+
+class Process : public JSC::JSNonFinalObject {
+ using Base = JSC::JSNonFinalObject;
+
+ public:
+ Process(JSC::VM &vm, JSC::Structure *structure) : Base(vm, structure) {}
+
+ DECLARE_INFO;
+
+ static constexpr unsigned StructureFlags = Base::StructureFlags;
+
+ template
+ static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) {
+ return &vm.cellSpace;
+ }
+
+ static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject,
+ JSC::JSValue prototype) {
+ return JSC::Structure::create(vm, globalObject, prototype,
+ JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());
+ }
+
+ static Process *create(JSC::VM &vm, JSC::Structure *structure) {
+ Process *accessor = new (NotNull, JSC::allocateCell(vm.heap)) Process(vm, structure);
+ accessor->finishCreation(vm);
+ return accessor;
+ }
+
+ void finishCreation(JSC::VM &vm);
+};
+
+} // namespace Zig
\ No newline at end of file
diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.cpp b/src/javascript/jsc/bindings/ZigGlobalObject.cpp
index e113e4df29..0329024a49 100644
--- a/src/javascript/jsc/bindings/ZigGlobalObject.cpp
+++ b/src/javascript/jsc/bindings/ZigGlobalObject.cpp
@@ -26,6 +26,7 @@
#include
#include
#include
+#include
// #include
#include
#include
@@ -51,6 +52,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -68,6 +70,8 @@
#include
#include
+#include "BunClientData.h"
+
#include "ZigSourceProvider.h"
using JSGlobalObject = JSC::JSGlobalObject;
@@ -82,21 +86,20 @@ using JSObject = JSC::JSObject;
using JSNonFinalObject = JSC::JSNonFinalObject;
namespace JSCastingHelpers = JSC::JSCastingHelpers;
-bool has_loaded_jsc = false;
+static bool has_loaded_jsc = false;
extern "C" void JSCInitialize() {
if (has_loaded_jsc) return;
+ has_loaded_jsc = true;
+
JSC::Options::useSourceProviderCache() = true;
JSC::Options::useUnlinkedCodeBlockJettisoning() = false;
JSC::Options::exposeInternalModuleLoader() = true;
JSC::Options::useSharedArrayBuffer() = true;
// JSC::Options::useAtMethod() = true;
-
// std::set_terminate([]() { Zig__GlobalObject__onCrash(); });
WTF::initializeMainThread();
JSC::initialize();
- // Gigacage::disablePrimitiveGigacage();
- has_loaded_jsc = true;
}
extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObjectClass, int count,
@@ -104,6 +107,8 @@ extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObje
auto heapSize = JSC::LargeHeap;
JSC::VM &vm = JSC::VM::create(heapSize).leakRef();
+ Bun::JSVMClientData::create(&vm);
+
vm.heap.acquireAccess();
#if ENABLE(WEBASSEMBLY)
JSC::Wasm::enableFastMemory();
@@ -257,33 +262,80 @@ void GlobalObject::setConsole(void *console) {
this->setConsoleClient(makeWeakPtr(m_console));
}
+#pragma mark - Globals
+
+static JSC_DECLARE_CUSTOM_SETTER(property_lazyProcessSetter);
+static JSC_DECLARE_CUSTOM_GETTER(property_lazyProcessGetter);
+
+JSC_DEFINE_CUSTOM_SETTER(property_lazyProcessSetter,
+ (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue,
+ JSC::EncodedJSValue value, JSC::PropertyName)) {
+ return false;
+}
+
+static JSClassRef dot_env_class_ref;
+JSC_DEFINE_CUSTOM_GETTER(property_lazyProcessGetter,
+ (JSC::JSGlobalObject * _globalObject, JSC::EncodedJSValue thisValue,
+ JSC::PropertyName)) {
+ Zig::GlobalObject *globalObject = reinterpret_cast(_globalObject);
+ if (LIKELY(globalObject->m_process))
+ return JSValue::encode(JSC::JSValue(globalObject->m_process));
+
+ JSC::VM &vm = globalObject->vm();
+
+ globalObject->m_process = Zig::Process::create(
+ vm, Zig::Process::createStructure(vm, globalObject, globalObject->objectPrototype()));
+
+ {
+ auto jsClass = dot_env_class_ref;
+
+ JSC::JSCallbackObject *object =
+ JSC::JSCallbackObject::create(
+ globalObject, globalObject->callbackObjectStructure(), jsClass, nullptr);
+ if (JSObject *prototype = jsClass->prototype(globalObject))
+ object->setPrototypeDirect(vm, prototype);
+
+ globalObject->m_process->putDirect(vm, JSC::Identifier::fromString(vm, "env"),
+ JSC::JSValue(object),
+ JSC::PropertyAttribute::DontDelete | 0);
+ }
+
+ return JSC::JSValue::encode(JSC::JSValue(globalObject->m_process));
+}
+
+static JSC_DECLARE_HOST_FUNCTION(functionQueueMicrotask);
+
+static JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask,
+ (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) {
+ JSC::VM &vm = globalObject->vm();
+
+ if (callFrame->argumentCount() == 0) {
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::throwTypeError(globalObject, scope, "queueMicrotask requires 1 argument (a function)"_s);
+ return JSC::JSValue::encode(JSC::JSValue{});
+ }
+
+ JSC::JSValue job = callFrame->argument(0);
+
+ if (!job.isObject() || !job.getObject()->isCallable(vm)) {
+ auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
+ JSC::throwTypeError(globalObject, scope, "queueMicrotask expects a function"_s);
+ return JSC::JSValue::encode(JSC::JSValue{});
+ }
+
+ // This is a JSC builtin function
+ globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job));
+
+ return JSC::JSValue::encode(JSC::jsUndefined());
+}
+
// This is not a publicly exposed API currently.
// This is used by the bundler to make Response, Request, FetchEvent,
// and any other objects available globally.
void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) {
WTF::Vector extraStaticGlobals;
- extraStaticGlobals.reserveCapacity((size_t)count + 2);
+ extraStaticGlobals.reserveCapacity((size_t)count + 3);
- // This is not nearly a complete implementation. It's just enough to make some npm packages that
- // were compiled with Webpack to run without crashing in this environment.
- JSC::JSObject *process = JSC::constructEmptyObject(this, this->objectPrototype(), 4);
-
- // this should be transpiled out, but just incase
- process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"),
- JSC::JSValue(false));
-
- // this gives some way of identifying at runtime whether the SSR is happening in node or not.
- // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS"
- // but it must be something that won't evaluate to truthy in Node.js
- process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"),
- JSC::JSValue(true));
-#if defined(__APPLE__)
- process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"),
- JSC::jsString(this->vm(), WTF::String("darwin")));
-#else
- process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"),
- JSC::jsString(this->vm(), WTF::String("linux")));
-#endif
int i = 0;
for (; i < count - 1; i++) {
auto jsClass = globals[i];
@@ -300,23 +352,38 @@ void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) {
// The last one must be "process.env"
// Runtime-support is for if they change
- {
- auto jsClass = globals[i];
+ dot_env_class_ref = globals[i];
- JSC::JSCallbackObject *object =
- JSC::JSCallbackObject::create(this, this->callbackObjectStructure(),
- jsClass, nullptr);
- if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(), prototype);
+ // // The last one must be "process.env"
+ // // Runtime-support is for if they change
+ // {
+ // auto jsClass = globals[i];
- process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"),
- JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0);
- }
+ // JSC::JSCallbackObject *object =
+ // JSC::JSCallbackObject::create(this, this->callbackObjectStructure(),
+ // jsClass, nullptr);
+ // if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(),
+ // prototype);
+ // process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"),
+ // JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0);
+ // }
+
+ JSC::Identifier queueMicrotaskIdentifier = JSC::Identifier::fromString(vm(), "queueMicrotask"_s);
extraStaticGlobals.uncheckedAppend(
- GlobalPropertyInfo{JSC::Identifier::fromString(vm(), "process"), JSC::JSValue(process),
+ GlobalPropertyInfo{queueMicrotaskIdentifier,
+ JSC::JSFunction::create(vm(), JSC::jsCast(this), 0,
+ "queueMicrotask", functionQueueMicrotask),
JSC::PropertyAttribute::DontDelete | 0});
+ auto clientData = Bun::clientData(vm());
+
this->addStaticGlobals(extraStaticGlobals.data(), extraStaticGlobals.size());
+ putDirectCustomAccessor(
+ vm(), clientData->builtinNames().processPublicName(),
+ JSC::CustomGetterSetter::create(vm(), property_lazyProcessGetter, property_lazyProcessSetter),
+ JSC::PropertyAttribute::CustomValue | 0);
+
extraStaticGlobals.releaseBuffer();
}
@@ -418,7 +485,6 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje
JSModuleRecord *record,
JSValue val) {
- ZigString specifier = Zig::toZigString(key, globalObject);
JSC::VM &vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -426,7 +492,16 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje
JSC::constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure());
RETURN_IF_EXCEPTION(scope, nullptr);
- metaProperties->putDirect(vm, Identifier::fromString(vm, "filePath"), key);
+ auto clientData = Bun::clientData(vm);
+ JSString *keyString = key.toStringOrNull(globalObject);
+ if (UNLIKELY(!keyString)) { return metaProperties; }
+ auto view = keyString->value(globalObject);
+ auto index = view.reverseFind('/', view.length());
+ if (index != WTF::notFound) {
+ metaProperties->putDirect(vm, clientData->builtinNames().dirPublicName(),
+ JSC::jsSubstring(globalObject, keyString, 0, index));
+ }
+ metaProperties->putDirect(vm, clientData->builtinNames().pathPublicName(), key);
RETURN_IF_EXCEPTION(scope, nullptr);
// metaProperties->putDirect(vm, Identifier::fromString(vm, "resolve"),
diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.h b/src/javascript/jsc/bindings/ZigGlobalObject.h
index 64ece0c647..3d5d389e0e 100644
--- a/src/javascript/jsc/bindings/ZigGlobalObject.h
+++ b/src/javascript/jsc/bindings/ZigGlobalObject.h
@@ -9,11 +9,13 @@ class Identifier;
} // namespace JSC
+#include "Process.h"
#include "ZigConsoleClient.h"
#include
#include
#include
#include
+
namespace Zig {
class GlobalObject : public JSC::JSGlobalObject {
@@ -22,7 +24,7 @@ class GlobalObject : public JSC::JSGlobalObject {
public:
DECLARE_EXPORT_INFO;
static const JSC::GlobalObjectMethodTable s_globalObjectMethodTable;
-
+ Zig::Process *m_process;
static constexpr bool needsDestruction = true;
template
static JSC::IsoSubspace *subspaceFor(JSC::VM &vm) {
@@ -74,17 +76,14 @@ class JSMicrotaskCallback : public RefCounted {
public:
static Ref create(JSC::JSGlobalObject &globalObject,
Ref &&task) {
- return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task)));
+ return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task).leakRef()));
}
void call() {
auto protectedThis{makeRef(*this)};
JSC::VM &vm = m_globalObject->vm();
- JSC::JSLockHolder lock(vm);
- auto scope = DECLARE_CATCH_SCOPE(vm);
auto task = &m_task.get();
task->run(m_globalObject.get());
- scope.assertNoExceptionExceptTermination();
}
private:
diff --git a/src/javascript/jsc/bindings/bindings.cpp b/src/javascript/jsc/bindings/bindings.cpp
index 60b6a442e8..7af7d3a256 100644
--- a/src/javascript/jsc/bindings/bindings.cpp
+++ b/src/javascript/jsc/bindings/bindings.cpp
@@ -1,3 +1,4 @@
+#include "BunClientData.h"
#include "ZigGlobalObject.h"
#include "helpers.h"
#include "root.h"
@@ -6,8 +7,10 @@
#include
#include
#include
+#include
#include
#include
+#include
#include
#include
#include
@@ -20,6 +23,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -31,6 +35,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -39,6 +44,62 @@
extern "C" {
+JSC__JSValue SystemError__toErrorInstance(const SystemError *arg0,
+ JSC__JSGlobalObject *globalObject) {
+
+ static const char *system_error_name = "SystemError";
+ SystemError err = *arg0;
+
+ JSC::VM &vm = globalObject->vm();
+
+ auto scope = DECLARE_THROW_SCOPE(vm);
+ JSC::JSValue message = JSC::jsUndefined();
+ if (err.message.len > 0) { message = Zig::toJSString(err.message, globalObject); }
+
+ JSC::JSValue options = JSC::jsUndefined();
+
+ JSC::Structure *errorStructure = globalObject->errorStructure();
+ JSC::JSObject *result =
+ JSC::ErrorInstance::create(globalObject, errorStructure, message, options);
+
+ auto clientData = Bun::clientData(vm);
+
+ if (err.code.len > 0) {
+ JSC::JSValue code = Zig::toJSString(err.code, globalObject);
+ result->putDirect(vm, clientData->builtinNames().codePublicName(), code,
+ JSC::PropertyAttribute::DontDelete | 0);
+
+ result->putDirect(vm, vm.propertyNames->name, code, JSC::PropertyAttribute::DontEnum | 0);
+ } else {
+
+ result->putDirect(
+ vm, vm.propertyNames->name,
+ JSC::JSValue(JSC::jsOwnedString(
+ vm, WTF::String(WTF::StringImpl::createWithoutCopying(system_error_name, 11)))),
+ JSC::PropertyAttribute::DontEnum | 0);
+ }
+
+ if (err.path.len > 0) {
+ JSC::JSValue path = JSC::JSValue(Zig::toJSStringGC(err.path, globalObject));
+ result->putDirect(vm, clientData->builtinNames().pathPublicName(), path,
+ JSC::PropertyAttribute::DontDelete | 0);
+ }
+
+ if (err.syscall.len > 0) {
+ JSC::JSValue syscall = JSC::JSValue(Zig::toJSString(err.syscall, globalObject));
+ result->putDirect(vm, clientData->builtinNames().syscallPublicName(), syscall,
+ JSC::PropertyAttribute::DontDelete | 0);
+ }
+
+ result->putDirect(vm, clientData->builtinNames().errnoPublicName(), JSC::JSValue(err.errno_),
+ JSC::PropertyAttribute::DontDelete | 0);
+
+ RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue()));
+ scope.release();
+
+ return JSC::JSValue::encode(JSC::JSValue(result));
+}
+
JSC__JSValue
JSC__JSObject__create(JSC__JSGlobalObject *globalObject, size_t initialCapacity, void *arg2,
void (*ArgFn3)(void *arg0, JSC__JSObject *arg1, JSC__JSGlobalObject *arg2)) {
@@ -147,6 +208,19 @@ void JSC__JSValue__putRecord(JSC__JSValue objectValue, JSC__JSGlobalObject *glob
scope.release();
}
+void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject *arg1, uint32_t arg2,
+ ZigString *arg3) {
+ JSC::JSValue value = JSC::JSValue::decode(JSValue0);
+ WTF::String str = JSC::JSONStringify(arg1, value, (unsigned)arg2);
+ *arg3 = Zig::toZigString(str);
+}
+unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0) {
+ JSC::JSValue jsValue = JSC::JSValue::decode(JSValue0);
+ if (!jsValue.isCell()) return 0;
+
+ return jsValue.asCell()->type();
+}
+
// This is very naive!
JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject *arg1,
ZigString arg2) {
@@ -175,6 +249,12 @@ JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject *
// return nullptr;
}
+bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1,
+ JSC__JSGlobalObject *globalObject) {
+ return JSC::sameValue(globalObject, JSC::JSValue::decode(JSValue0),
+ JSC::JSValue::decode(JSValue1));
+}
+
// This is the same as the C API version, except it returns a JSValue which may be a *Exception
// We want that so we can return stack traces.
JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef object,
@@ -211,6 +291,44 @@ JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef obj
return JSC::JSValue::encode(result);
}
+JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object,
+ JSObjectRef thisObject,
+ size_t argumentCount,
+ const JSValueRef *arguments);
+
+JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object,
+ JSObjectRef thisObject,
+ size_t argumentCount,
+ const JSValueRef *arguments) {
+ JSC::JSGlobalObject *globalObject = toJS(ctx);
+ JSC::VM &vm = globalObject->vm();
+
+ JSC::JSLockHolder lock(vm);
+
+ if (!object) return JSC::JSValue::encode(JSC::JSValue());
+
+ JSC::JSObject *jsObject = toJS(object);
+ JSC::JSObject *jsThisObject = toJS(thisObject);
+
+ if (!jsThisObject) jsThisObject = globalObject->globalThis();
+
+ JSC::MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; i++) argList.append(toJS(globalObject, arguments[i]));
+
+ auto callData = getCallData(vm, jsObject);
+ if (callData.type == JSC::CallData::Type::None) return JSC::JSValue::encode(JSC::JSValue());
+
+ NakedPtr returnedException = nullptr;
+ auto result =
+ JSC::call(globalObject, jsObject, callData, jsThisObject, argList, returnedException);
+
+ if (returnedException.get()) {
+ return JSC::JSValue::encode(JSC::JSValue(returnedException.get()));
+ }
+
+ return JSC::JSValue::encode(result);
+}
+
#pragma mark - JSC::Exception
JSC__Exception *JSC__Exception__create(JSC__JSGlobalObject *arg0, JSC__JSObject *arg1,
@@ -236,10 +354,10 @@ JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue jsValue, JSC__JSGlobalObject *
return JSC::JSValue::encode(JSC::JSValue::decode(jsValue).toObject(arg1)->getIndex(arg1, arg3));
}
JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1,
- const ZigString * arg2) {
+ const ZigString *arg2) {
return JSC::JSValue::encode(arg0->getDirect(arg1->vm(), Zig::toIdentifier(*arg2, arg1)));
}
-void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString * key,
+void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString *key,
JSC__JSValue value) {
auto prop = Zig::toIdentifier(*key, arg1);
@@ -348,10 +466,85 @@ static JSC::JSValue doLink(JSC__JSGlobalObject *globalObject, JSC::JSValue modul
return JSC::linkAndEvaluateModule(globalObject, moduleKey, JSC::JSValue());
}
-JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, ZigString *arg1,
- size_t arg2) {
+JSC__JSValue JSC__JSValue__createRangeError(const ZigString *message, const ZigString *arg1,
+ JSC__JSGlobalObject *globalObject) {
+ JSC::VM &vm = globalObject->vm();
+ ZigString code = *arg1;
+ JSC::JSObject *rangeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject();
+ static const char *range_error_name = "RangeError";
+
+ rangeError->putDirect(
+ vm, vm.propertyNames->name,
+ JSC::JSValue(JSC::jsOwnedString(
+ vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))),
+ 0);
+
+ if (code.len > 0) {
+ auto clientData = Bun::clientData(vm);
+ JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject);
+ rangeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue,
+ JSC::PropertyAttribute::ReadOnly | 0);
+ }
+
+ return JSC::JSValue::encode(rangeError);
+}
+JSC__JSValue JSC__JSValue__createTypeError(const ZigString *message, const ZigString *arg1,
+ JSC__JSGlobalObject *globalObject) {
+ JSC::VM &vm = globalObject->vm();
+ ZigString code = *arg1;
+ JSC::JSObject *typeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject();
+ static const char *range_error_name = "TypeError";
+
+ typeError->putDirect(
+ vm, vm.propertyNames->name,
+ JSC::JSValue(JSC::jsOwnedString(
+ vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))),
+ 0);
+
+ if (code.len > 0) {
+ auto clientData = Bun::clientData(vm);
+ JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject);
+ typeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue, 0);
+ }
+
+ return JSC::JSValue::encode(typeError);
+}
+
+JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject *globalObject, ZigString *keys,
+ ZigString *values, size_t initialCapacity, bool clone) {
JSC::VM &vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
+ if (initialCapacity == 0) {
+ return JSC::JSValue::encode(JSC::constructEmptyObject(globalObject));
+ }
+
+ JSC::JSObject *object = nullptr;
+ {
+ JSC::ObjectInitializationScope initializationScope(vm);
+ object =
+ JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), initialCapacity);
+
+ if (!clone) {
+ for (size_t i = 0; i < initialCapacity; ++i) {
+ object->putDirect(
+ vm, JSC::PropertyName(JSC::Identifier::fromString(vm, Zig::toString(keys[i]))),
+ Zig::toJSStringValueGC(values[i], globalObject), 0);
+ }
+ } else {
+ for (size_t i = 0; i < initialCapacity; ++i) {
+ object->putDirect(vm, JSC::PropertyName(Zig::toIdentifier(keys[i], globalObject)),
+ Zig::toJSStringValueGC(values[i], globalObject), 0);
+ }
+ }
+ }
+
+ return JSC::JSValue::encode(object);
+}
+JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, ZigString *arg1,
+ size_t arg2, bool clone) {
+ JSC::VM &vm = globalObject->vm();
+ auto scope = DECLARE_THROW_SCOPE(vm);
+ if (arg2 == 0) { return JSC::JSValue::encode(JSC::JSArray::create(vm, 0)); }
JSC::JSArray *array = nullptr;
{
@@ -361,8 +554,14 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject,
globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous),
arg2))) {
- for (size_t i = 0; i < arg2; ++i) {
- array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i])));
+ if (!clone) {
+ for (size_t i = 0; i < arg2; ++i) {
+ array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toString(arg1[i])));
+ }
+ } else {
+ for (size_t i = 0; i < arg2; ++i) {
+ array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i])));
+ }
}
}
}
@@ -376,7 +575,7 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject,
JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *globalObject,
void **errors, uint16_t errors_count,
- const ZigString * arg3) {
+ const ZigString *arg3) {
JSC::VM &vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -411,34 +610,34 @@ JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *glob
// static JSC::JSNativeStdFunction* rejecterFunction;
// static bool resolverFunctionInitialized = false;
-JSC__JSValue ZigString__toValue(const ZigString * arg0, JSC__JSGlobalObject *arg1) {
+JSC__JSValue ZigString__toValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) {
return JSC::JSValue::encode(JSC::JSValue(JSC::jsOwnedString(arg1->vm(), Zig::toString(*arg0))));
}
-JSC__JSValue ZigString__toValueGC(const ZigString * arg0, JSC__JSGlobalObject *arg1) {
+JSC__JSValue ZigString__to16BitValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) {
+ auto str = WTF::String::fromUTF8(arg0->ptr, arg0->len);
+ return JSC::JSValue::encode(JSC::JSValue(JSC::jsString(arg1->vm(), str)));
+}
+
+JSC__JSValue ZigString__toValueGC(const ZigString *arg0, JSC__JSGlobalObject *arg1) {
return JSC::JSValue::encode(
- JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toString(*arg0))));
+ JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toStringCopy(*arg0))));
}
void JSC__JSValue__toZigString(JSC__JSValue JSValue0, ZigString *arg1, JSC__JSGlobalObject *arg2) {
JSC::JSValue value = JSC::JSValue::decode(JSValue0);
auto str = value.toWTFString(arg2);
- arg1->ptr = str.characters8();
+ if (str.is8Bit()) {
+ arg1->ptr = str.characters8();
+ } else {
+ arg1->ptr = Zig::taggedUTF16Ptr(str.characters16());
+ }
+
arg1->len = str.length();
}
+
JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) {
- JSC::VM &vm = globalObject->vm();
-
- auto scope = DECLARE_THROW_SCOPE(vm);
- JSC::JSValue message = Zig::toJSString(*str, globalObject);
- JSC::JSValue options = JSC::jsUndefined();
- JSC::Structure *errorStructure = globalObject->errorStructure();
- JSC::JSObject *result =
- JSC::ErrorInstance::create(globalObject, errorStructure, message, options);
- RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue()));
- scope.release();
-
- return JSC::JSValue::encode(JSC::JSValue(result));
+ return JSC::JSValue::encode(Zig::getErrorInstance(str, globalObject));
}
static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalObject,
@@ -447,7 +646,8 @@ static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalO
}
JSC__JSInternalPromise *
-JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject, const ZigString * arg1) {
+JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject,
+ const ZigString *arg1) {
globalObject->vm().drainMicrotasks();
auto name = Zig::toString(*arg1);
name.impl()->ref();
@@ -768,6 +968,22 @@ bWTF__String JSC__JSFunction__calculatedDisplayName(JSC__JSFunction *arg0, JSC__
};
#pragma mark - JSC::JSGlobalObject
+JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject *globalObject) {
+ JSC::VM &vm = globalObject->vm();
+
+ JSC::JSLockHolder lock(vm);
+ // JSC::DeferTermination deferScope(vm);
+ auto scope = DECLARE_THROW_SCOPE(vm);
+
+ JSC::HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler());
+ snapshotBuilder.buildSnapshot();
+
+ WTF::String jsonString = snapshotBuilder.json();
+ JSC::EncodedJSValue result = JSC::JSValue::encode(JSONParse(globalObject, jsonString));
+ scope.releaseAssertNoException();
+ return result;
+}
+
JSC__ArrayIteratorPrototype *
JSC__JSGlobalObject__arrayIteratorPrototype(JSC__JSGlobalObject *arg0) {
return arg0->arrayIteratorPrototype();
@@ -1006,6 +1222,45 @@ JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0) {
return JSC::JSValue::encode(JSC::jsNumber(arg0));
};
+JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject *globalObject, const ZigString *arg1,
+ const ZigString *arg2, JSC__JSValue JSValue3,
+ JSC__JSValue JSValue4) {
+ JSC::JSObject *object = JSC::constructEmptyObject(globalObject);
+ auto key1 = Zig::toIdentifier(*arg1, globalObject);
+ JSC::PropertyDescriptor descriptor1;
+ JSC::PropertyDescriptor descriptor2;
+
+ descriptor1.setEnumerable(1);
+ descriptor1.setConfigurable(1);
+ descriptor1.setWritable(1);
+ descriptor1.setValue(JSC::JSValue::decode(JSValue3));
+
+ auto key2 = Zig::toIdentifier(*arg2, globalObject);
+
+ descriptor2.setEnumerable(1);
+ descriptor2.setConfigurable(1);
+ descriptor2.setWritable(1);
+ descriptor2.setValue(JSC::JSValue::decode(JSValue4));
+
+ object->methodTable(globalObject->vm())
+ ->defineOwnProperty(object, globalObject, key2, descriptor2, true);
+ object->methodTable(globalObject->vm())
+ ->defineOwnProperty(object, globalObject, key1, descriptor1, true);
+
+ return JSC::JSValue::encode(object);
+}
+
+JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0,
+ JSC__JSGlobalObject *globalObject,
+ const unsigned char *arg1, uint32_t arg2) {
+
+ JSC::VM &vm = globalObject->vm();
+ JSC::JSObject *object = JSC::JSValue::decode(JSValue0).asCell()->getObject();
+ auto propertyName = JSC::PropertyName(
+ JSC::Identifier::fromString(vm, reinterpret_cast(arg1), (int)arg2));
+ return JSC::JSValue::encode(object->getIfPropertyExists(globalObject, propertyName));
+}
+
bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).asBoolean();
}
@@ -1274,9 +1529,10 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global,
if (err->isStackOverflowError()) { except->code = 253; }
if (err->isOutOfMemoryError()) { except->code = 8; }
- if (obj->hasProperty(global, global->vm().propertyNames->message)) {
- except->message = Zig::toZigString(
- obj->getDirect(global->vm(), global->vm().propertyNames->message).toWTFString(global));
+ if (JSC::JSValue message =
+ obj->getIfPropertyExists(global, global->vm().propertyNames->message)) {
+
+ except->message = Zig::toZigString(message, global);
} else {
except->message = Zig::toZigString(err->sanitizedMessageString(global));
@@ -1284,19 +1540,40 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global,
except->name = Zig::toZigString(err->sanitizedNameString(global));
except->runtime_type = err->runtimeTypeForCause();
- if (getFromSourceURL) {
- if (obj->hasProperty(global, global->vm().propertyNames->sourceURL)) {
- except->stack.frames_ptr[0].source_url = Zig::toZigString(
- obj->getDirect(global->vm(), global->vm().propertyNames->sourceURL).toWTFString(global));
+ auto clientData = Bun::clientData(global->vm());
- if (obj->hasProperty(global, global->vm().propertyNames->line)) {
- except->stack.frames_ptr[0].position.line =
- obj->getDirect(global->vm(), global->vm().propertyNames->line).toInt32(global);
+ if (JSC::JSValue syscall =
+ obj->getIfPropertyExists(global, clientData->builtinNames().syscallPublicName())) {
+ except->syscall = Zig::toZigString(syscall, global);
+ }
+
+ if (JSC::JSValue code =
+ obj->getIfPropertyExists(global, clientData->builtinNames().codePublicName())) {
+ except->code_ = Zig::toZigString(code, global);
+ }
+
+ if (JSC::JSValue path =
+ obj->getIfPropertyExists(global, clientData->builtinNames().pathPublicName())) {
+ except->path = Zig::toZigString(path, global);
+ }
+
+ if (JSC::JSValue errno_ =
+ obj->getIfPropertyExists(global, clientData->builtinNames().errnoPublicName())) {
+ except->errno_ = errno_.toInt32(global);
+ }
+
+ if (getFromSourceURL) {
+ if (JSC::JSValue sourceURL =
+ obj->getIfPropertyExists(global, global->vm().propertyNames->sourceURL)) {
+ except->stack.frames_ptr[0].source_url = Zig::toZigString(sourceURL, global);
+
+ if (JSC::JSValue line = obj->getIfPropertyExists(global, global->vm().propertyNames->line)) {
+ except->stack.frames_ptr[0].position.line = line.toInt32(global);
}
- if (obj->hasProperty(global, global->vm().propertyNames->column)) {
- except->stack.frames_ptr[0].position.column_start =
- obj->getDirect(global->vm(), global->vm().propertyNames->column).toInt32(global);
+ if (JSC::JSValue column =
+ obj->getIfPropertyExists(global, global->vm().propertyNames->column)) {
+ except->stack.frames_ptr[0].position.column_start = column.toInt32(global);
}
except->stack.frames_len = 1;
}
@@ -1469,8 +1746,36 @@ const WTF__StringImpl *JSC__PropertyName__uid(JSC__PropertyName *arg0) { return
#pragma mark - JSC::VM
+JSC__JSValue JSC__VM__runGC(JSC__VM *vm, bool sync) {
+ JSC::JSLockHolder lock(vm);
+
+ if (sync) {
+ vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full);
+ } else {
+ vm->heap.collectSync(JSC::CollectionScope::Full);
+ }
+
+ return JSC::JSValue::encode(JSC::jsNumber(vm->heap.sizeAfterLastFullCollection()));
+}
+
bool JSC__VM__isJITEnabled() { return JSC::Options::useJIT(); }
+void JSC__VM__clearExecutionTimeLimit(JSC__VM *vm) {
+ JSC::JSLockHolder locker(vm);
+ if (vm->watchdog()) vm->watchdog()->setTimeLimit(JSC::Watchdog::noTimeLimit);
+}
+void JSC__VM__setExecutionTimeLimit(JSC__VM *vm, double limit) {
+ JSC::JSLockHolder locker(vm);
+ JSC::Watchdog &watchdog = vm->ensureWatchdog();
+ watchdog.setTimeLimit(WTF::Seconds{limit});
+}
+
+bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM *arg1) {
+ JSC::Exception *exception =
+ JSC::jsDynamicCast(*arg1, JSC::JSValue::decode(JSValue0));
+ return exception != NULL && arg1->isTerminationException(exception);
+}
+
void JSC__VM__shrinkFootprint(JSC__VM *arg0) { arg0->shrinkFootprintWhenIdle(); };
void JSC__VM__whenIdle(JSC__VM *arg0, void (*ArgFn1)()) { arg0->whenIdle(ArgFn1); };
@@ -1485,6 +1790,11 @@ JSC__VM *JSC__VM__create(unsigned char HeapType0) {
return vm;
}
+void JSC__VM__holdAPILock(JSC__VM *arg0, void *ctx, void (*callback)(void *arg0)) {
+ JSC::JSLockHolder locker(arg0);
+ callback(ctx);
+}
+
void JSC__VM__deleteAllCode(JSC__VM *arg1, JSC__JSGlobalObject *globalObject) {
JSC::JSLockHolder locker(globalObject->vm());
diff --git a/src/javascript/jsc/bindings/bindings.zig b/src/javascript/jsc/bindings/bindings.zig
index 971782e0bd..a287174005 100644
--- a/src/javascript/jsc/bindings/bindings.zig
+++ b/src/javascript/jsc/bindings/bindings.zig
@@ -7,7 +7,7 @@ const hasRef = std.meta.trait.hasField("ref");
const C_API = @import("../../../jsc.zig").C;
const StringPointer = @import("../../../api/schema.zig").Api.StringPointer;
const Exports = @import("./exports.zig");
-
+const strings = _global.strings;
const ErrorableZigString = Exports.ErrorableZigString;
const ErrorableResolvedSource = Exports.ErrorableResolvedSource;
const ZigException = Exports.ZigException;
@@ -71,15 +71,6 @@ pub const JSObject = extern struct {
});
}
- pub fn putDirect(this: *JSObject, globalThis: *JSGlobalObject, prop: *const ZigString, value: JSValue) void {
- return cppFn("putDirect", .{
- this,
- globalThis,
- prop,
- value,
- });
- }
-
pub const Extern = [_][]const u8{
"putRecord",
"create",
@@ -87,18 +78,28 @@ pub const JSObject = extern struct {
"getIndex",
"putAtIndex",
"getDirect",
- "putDirect",
};
};
pub const ZigString = extern struct {
+ // TODO: align this to align(2)
+ // That would improve perf a bit
ptr: [*]const u8,
len: usize,
+
pub const shim = Shimmer("", "ZigString", @This());
pub const name = "ZigString";
pub const namespace = "";
+ pub inline fn is16Bit(this: *const ZigString) bool {
+ return (@ptrToInt(this.ptr) & (1 << 63)) != 0;
+ }
+
+ pub inline fn utf16Slice(this: *const ZigString) []align(1) const u16 {
+ return @ptrCast([*]align(1) const u16, this.ptr)[0..this.len];
+ }
+
pub fn fromStringPointer(ptr: StringPointer, buf: string, to: *ZigString) void {
to.* = ZigString{
.len = ptr.length,
@@ -110,6 +111,32 @@ pub const ZigString = extern struct {
return ZigString{ .ptr = slice_.ptr, .len = slice_.len };
}
+ pub fn detectEncoding(this: *ZigString) void {
+ for (this.slice()) |char| {
+ if (char > 127) {
+ this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 63));
+ return;
+ }
+ }
+ }
+
+ pub inline fn isGloballyAllocated(this: *ZigString) bool {
+ return (@ptrToInt(this.ptr) & (1 << 62)) != 0;
+ }
+
+ pub inline fn mark(this: *ZigString) void {
+ this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 62));
+ }
+
+ pub fn format(self: ZigString, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
+ if (self.is16Bit()) {
+ try strings.formatUTF16(self.utf16Slice(), writer);
+ return;
+ }
+
+ try writer.writeAll(self.slice());
+ }
+
pub inline fn toRef(slice_: []const u8, global: *JSGlobalObject) C_API.JSValueRef {
return init(slice_).toValue(global).asRef();
}
@@ -117,7 +144,11 @@ pub const ZigString = extern struct {
pub const Empty = ZigString{ .ptr = "", .len = 0 };
pub fn slice(this: *const ZigString) []const u8 {
- return this.ptr[0..std.math.min(this.len, 4096)];
+ return this.ptr[0..@minimum(this.len, std.math.maxInt(u32))];
+ }
+
+ pub fn sliceZBuf(this: ZigString, buf: *[std.fs.MAX_PATH_BYTES]u8) ![:0]const u8 {
+ return try std.fmt.bufPrintZ(buf, "{}", .{this});
}
pub inline fn full(this: *const ZigString) []const u8 {
@@ -125,13 +156,25 @@ pub const ZigString = extern struct {
}
pub fn trimmedSlice(this: *const ZigString) []const u8 {
- return std.mem.trim(u8, this.ptr[0..std.math.min(this.len, 4096)], " \r\n");
+ return std.mem.trim(u8, this.ptr[0..@minimum(this.len, std.math.maxInt(u32))], " \r\n");
+ }
+
+ pub fn toValueAuto(this: *const ZigString, global: *JSGlobalObject) JSValue {
+ if (!this.is16Bit()) {
+ return this.toValue(global);
+ } else {
+ return this.to16BitValue(global);
+ }
}
pub fn toValue(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toValue", .{ this, global });
}
+ pub fn to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue {
+ return shim.cppFn("to16BitValue", .{ this, global });
+ }
+
pub fn toValueGC(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toValueGC", .{ this, global });
}
@@ -141,7 +184,10 @@ pub const ZigString = extern struct {
return undefined;
}
- return C_API.JSStringCreateStatic(this.ptr, this.len);
+ return if (this.is16Bit())
+ C_API.JSStringCreateWithCharactersNoCopy(@ptrCast([*]const u16, @alignCast(@alignOf([*]const u16), this.ptr)), this.len)
+ else
+ C_API.JSStringCreateStatic(this.ptr, this.len);
}
pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
@@ -150,11 +196,34 @@ pub const ZigString = extern struct {
pub const Extern = [_][]const u8{
"toValue",
+ "to16BitValue",
"toValueGC",
"toErrorInstance",
};
};
+pub const SystemError = extern struct {
+ errno: c_int = 0,
+ /// label for errno
+ code: ZigString = ZigString.init(""),
+ message: ZigString = ZigString.init(""),
+ path: ZigString = ZigString.init(""),
+ syscall: ZigString = ZigString.init(""),
+
+ pub const shim = Shimmer("", "SystemError", @This());
+
+ pub const name = "SystemError";
+ pub const namespace = "";
+
+ pub fn toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue {
+ return shim.cppFn("toErrorInstance", .{ this, global });
+ }
+
+ pub const Extern = [_][]const u8{
+ "toErrorInstance",
+ };
+};
+
pub const ReturnableException = *?*Exception;
pub const JSCell = extern struct {
@@ -935,6 +1004,10 @@ pub const JSGlobalObject = extern struct {
return cppFn("createAggregateError", .{ globalObject, errors, errors_len, message });
}
+ pub fn generateHeapSnapshot(this: *JSGlobalObject) JSValue {
+ return cppFn("generateHeapSnapshot", .{this});
+ }
+
pub fn vm(this: *JSGlobalObject) *VM {
return cppFn("vm", .{this});
}
@@ -966,6 +1039,7 @@ pub const JSGlobalObject = extern struct {
"asyncGeneratorPrototype",
"asyncGeneratorFunctionPrototype",
"vm",
+ "generateHeapSnapshot",
// "createError",
// "throwError",
};
@@ -1230,11 +1304,181 @@ pub const JSValue = enum(i64) {
pub const include = "";
pub const name = "JSC::JSValue";
pub const namespace = "JSC";
+ pub const JSType = enum(u8) {
+ // The Cell value must come before any JS that is a JSCell.
+ Cell,
+ String,
+ HeapBigInt,
+ Symbol,
+
+ GetterSetter,
+ CustomGetterSetter,
+ APIValueWrapper,
+
+ NativeExecutable,
+
+ ProgramExecutable,
+ ModuleProgramExecutable,
+ EvalExecutable,
+ FunctionExecutable,
+
+ UnlinkedFunctionExecutable,
+
+ UnlinkedProgramCodeBlock,
+ UnlinkedModuleProgramCodeBlock,
+ UnlinkedEvalCodeBlock,
+ UnlinkedFunctionCodeBlock,
+
+ CodeBlock,
+
+ JSImmutableButterfly,
+ JSSourceCode,
+ JSScriptFetcher,
+ JSScriptFetchParameters,
+
+ // The Object value must come before any JS that is a subclass of JSObject.
+ Object,
+ FinalObject,
+ JSCallee,
+ JSFunction,
+ InternalFunction,
+ NullSetterFunction,
+ BooleanObject,
+ NumberObject,
+ ErrorInstance,
+ PureForwardingProxy,
+ DirectArguments,
+ ScopedArguments,
+ ClonedArguments,
+
+ // Start JSArray types.
+ Array,
+ DerivedArray,
+ // End JSArray types.
+
+ ArrayBuffer,
+
+ // Start JSArrayBufferView types. Keep in sync with the order of FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW.
+ Int8Array,
+ Uint8Array,
+ Uint8ClampedArray,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ BigInt64Array,
+ BigUint64Array,
+ DataView,
+ // End JSArrayBufferView types.
+
+ // JSScope <- JSWithScope
+ // <- StrictEvalActivation
+ // <- JSSymbolTableObject <- JSLexicalEnvironment <- JSModuleEnvironment
+ // <- JSSegmentedVariableObject <- JSGlobalLexicalEnvironment
+ // <- JSGlobalObject
+ // Start JSScope types.
+ // Start environment record types.
+ GlobalObject,
+ GlobalLexicalEnvironment,
+ LexicalEnvironment,
+ ModuleEnvironment,
+ StrictEvalActivation,
+ // End environment record types.
+ WithScope,
+ // End JSScope types.
+
+ ModuleNamespaceObject,
+ RegExpObject,
+ JSDate,
+ ProxyObject,
+ JSGenerator,
+ JSAsyncGenerator,
+ JSArrayIterator,
+ JSMapIterator,
+ JSSetIterator,
+ JSStringIterator,
+ JSPromise,
+ JSMap,
+ JSSet,
+ JSWeakMap,
+ JSWeakSet,
+ WebAssemblyModule,
+ // Start StringObject types.
+ StringObject,
+ DerivedStringObject,
+ // End StringObject types.
+
+ MaxJS = 0b11111111,
+ _,
+
+ pub fn isHidden(this: JSType) bool {
+ return switch (this) {
+ .APIValueWrapper,
+ .NativeExecutable,
+ .ProgramExecutable,
+ .ModuleProgramExecutable,
+ .EvalExecutable,
+ .FunctionExecutable,
+ .UnlinkedFunctionExecutable,
+ .UnlinkedProgramCodeBlock,
+ .UnlinkedModuleProgramCodeBlock,
+ .UnlinkedEvalCodeBlock,
+ .UnlinkedFunctionCodeBlock,
+ .CodeBlock,
+ .JSImmutableButterfly,
+ .JSSourceCode,
+ .JSScriptFetcher,
+ .InternalFunction,
+ .JSScriptFetchParameters,
+ => true,
+ else => false,
+ };
+ }
+
+ pub const LastMaybeFalsyCellPrimitive = JSType.HeapBigInt;
+ pub const LastJSCObject = JSType.DerivedStringObject; // This is the last "JSC" Object type. After this, we have embedder's (e.g., WebCore) extended object types.
+
+ pub inline fn isStringLike(this: JSType) bool {
+ return switch (this) {
+ .String, .StringObject, .DerivedStringObject => true,
+ else => false,
+ };
+ }
+ };
pub inline fn cast(ptr: anytype) JSValue {
return @intToEnum(JSValue, @intCast(i64, @ptrToInt(ptr)));
}
+ pub fn to(this: JSValue, comptime T: type) T {
+ return switch (comptime T) {
+ u32 => toU32(this),
+ u16 => toU16(this),
+ c_uint => @intCast(c_uint, toU32(this)),
+ c_int => @intCast(c_int, toInt32(this)),
+
+ // TODO: BigUint64?
+ u64 => @as(u64, toU32(this)),
+
+ u8 => @truncate(u8, toU32(this)),
+ i16 => @truncate(i16, toInt32(this)),
+ i8 => @truncate(i8, toInt32(this)),
+ i32 => @truncate(i32, toInt32(this)),
+
+ // TODO: BigInt64
+ i64 => @as(i64, toInt32(this)),
+ else => @compileError("Not implemented yet"),
+ };
+ }
+
+ pub fn jsType(
+ this: JSValue,
+ ) JSType {
+ return cppFn("jsType", .{this});
+ }
+
pub fn createEmptyObject(global: *JSGlobalObject, len: usize) JSValue {
return cppFn("createEmptyObject", .{ global, len });
}
@@ -1243,21 +1487,47 @@ pub const JSValue = enum(i64) {
return cppFn("putRecord", .{ value, global, key, values, values_len });
}
+ /// Create an object with exactly two properties
+ pub fn createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue {
+ return cppFn("createObject2", .{ global, key1, key2, value1, value2 });
+ }
+
pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue {
return cppFn("getErrorsProperty", .{ this, globalObject });
}
- pub fn jsNumber(number: anytype) JSValue {
- return switch (@TypeOf(number)) {
+
+ pub fn jsNumberWithType(comptime Number: type, number: Type) JSValue {
+ return switch (Number) {
f64 => @call(.{ .modifier = .always_inline }, jsNumberFromDouble, .{number}),
u8 => @call(.{ .modifier = .always_inline }, jsNumberFromChar, .{number}),
u16 => @call(.{ .modifier = .always_inline }, jsNumberFromU16, .{number}),
- i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{number}),
- i64 => @call(.{ .modifier = .always_inline }, jsNumberFromInt64, .{number}),
- u64 => @call(.{ .modifier = .always_inline }, jsNumberFromUint64, .{number}),
- else => @compileError("Type transformation missing for number of type: " ++ @typeName(@TypeOf(number))),
+ i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{@truncate(i32, number)}),
+ c_int, i64 => if (number > std.math.maxInt(i32))
+ jsNumberFromInt64(@truncate(i64, number))
+ else
+ jsNumberFromInt32(@intCast(i32, number)),
+
+ c_uint, u32 => if (number < std.math.maxInt(i32))
+ jsNumberFromInt32(@intCast(i32, number))
+ else
+ jsNumberFromUint64(@as(u64, number)),
+
+ else => @compileError("Type transformation missing for number of type: " ++ @typeName(Number)),
};
}
+ pub fn jsNumber(number: anytype) JSValue {
+ return jsNumberWithType(@TypeOf(number), number);
+ }
+
+ pub fn getReadableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeReadableStream {
+ return cppFn("getReadableStreamState", .{ value, vm });
+ }
+
+ pub fn getWritableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeWritableStream {
+ return cppFn("getWritableStreamState", .{ value, vm });
+ }
+
pub fn jsNull() JSValue {
return cppFn("jsNull", .{});
}
@@ -1274,11 +1544,22 @@ pub const JSValue = enum(i64) {
return cppFn("jsDoubleNumber", .{i});
}
- pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize) JSValue {
+ pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize, clone: bool) JSValue {
return cppFn("createStringArray", .{
globalThis,
str,
strings_count,
+ clone,
+ });
+ }
+
+ pub fn fromEntries(globalThis: *JSGlobalObject, keys: [*c]ZigString, values: [*c]ZigString, strings_count: usize, clone: bool) JSValue {
+ return cppFn("fromEntries", .{
+ globalThis,
+ keys,
+ values,
+ strings_count,
+ clone,
});
}
@@ -1392,6 +1673,10 @@ pub const JSValue = enum(i64) {
return cppFn("isException", .{ this, vm });
}
+ pub fn isTerminationException(this: JSValue, vm: *VM) bool {
+ return cppFn("isTerminationException", .{ this, vm });
+ }
+
pub fn toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void {
return cppFn("toZigException", .{ this, global, exception });
}
@@ -1415,6 +1700,10 @@ pub const JSValue = enum(i64) {
return cppFn("toWTFString", .{ this, globalThis });
}
+ pub fn jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *ZigString) void {
+ return cppFn("jsonStringify", .{ this, globalThis, indent, out });
+ }
+
// On exception, this returns null, to make exception checks faster.
pub fn toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) *JSString {
return cppFn("toStringOrNull", .{ this, globalThis });
@@ -1441,6 +1730,31 @@ pub const JSValue = enum(i64) {
return cppFn("eqlCell", .{ this, other });
}
+ // intended to be more lightweight than ZigString
+ pub fn getIfPropertyExistsImpl(this: JSValue, global: *JSGlobalObject, ptr: [*]const u8, len: u32) JSValue {
+ return cppFn("getIfPropertyExistsImpl", .{ this, global, ptr, len });
+ }
+
+ pub fn getIfPropertyExists(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue {
+ const value = getIfPropertyExistsImpl(this, global, property.ptr, @intCast(u32, property.len));
+ return if (@enumToInt(value) != 0) value else return null;
+ }
+
+ pub fn createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
+ return cppFn("createTypeError", .{ message, code, global });
+ }
+
+ pub fn createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue {
+ return cppFn("createRangeError", .{ message, code, global });
+ }
+
+ /// Object.is()
+ /// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽.
+ /// https://tc39.es/ecma262/#sec-samevalue
+ pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
+ return cppFn("isSameValue", .{ this, other, global });
+ }
+
pub fn asString(this: JSValue) *JSString {
return cppFn("asString", .{
this,
@@ -1476,7 +1790,7 @@ pub const JSValue = enum(i64) {
}
pub inline fn toU32(this: JSValue) u32 {
- return @intCast(u32, this.toInt32());
+ return @intCast(u32, @maximum(this.toInt32(), 0));
}
pub fn getLengthOfArray(this: JSValue, globalThis: *JSGlobalObject) u32 {
@@ -1514,10 +1828,10 @@ pub const JSValue = enum(i64) {
}
pub inline fn asVoid(this: JSValue) *anyopaque {
- return @intToPtr(*anyopaque, @intCast(usize, @enumToInt(this)));
+ return @intToPtr(*anyopaque, @bitCast(u64, @enumToInt(this)));
}
- pub const Extern = [_][]const u8{ "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" };
+ pub const Extern = [_][]const u8{ "getReadableStreamState", "getWritableStreamState", "fromEntries", "createTypeError", "createRangeError", "createObject2", "getIfPropertyExistsImpl", "jsType", "jsonStringify", "kind_", "isTerminationException", "isSameValue", "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" };
};
extern "c" fn Microtask__run(*Microtask, *JSGlobalObject) void;
@@ -1653,6 +1967,10 @@ pub const VM = extern struct {
return cppFn("isJITEnabled", .{});
}
+ pub fn holdAPILock(this: *VM, ctx: ?*anyopaque, callback: fn (ctx: ?*anyopaque) callconv(.C) void) void {
+ cppFn("holdAPILock", .{ this, ctx, callback });
+ }
+
pub fn deleteAllCode(
vm: *VM,
global_object: *JSGlobalObject,
@@ -1675,10 +1993,25 @@ pub const VM = extern struct {
});
}
+ pub fn runGC(vm: *VM, sync: bool) JSValue {
+ return cppFn("runGC", .{
+ vm,
+ sync,
+ });
+ }
+
pub fn setExecutionForbidden(vm: *VM, forbidden: bool) void {
cppFn("setExecutionForbidden", .{ vm, forbidden });
}
+ pub fn setExecutionTimeLimit(vm: *VM, timeout: f64) void {
+ return cppFn("setExecutionTimeLimit", .{ vm, timeout });
+ }
+
+ pub fn clearExecutionTimeLimit(vm: *VM) void {
+ return cppFn("clearExecutionTimeLimit", .{vm});
+ }
+
pub fn executionForbidden(vm: *VM) bool {
return cppFn("executionForbidden", .{
vm,
@@ -1717,7 +2050,7 @@ pub const VM = extern struct {
});
}
- pub const Extern = [_][]const u8{ "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint" };
+ pub const Extern = [_][]const u8{ "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" };
};
pub const ThrowScope = extern struct {
diff --git a/src/javascript/jsc/bindings/exports.zig b/src/javascript/jsc/bindings/exports.zig
index ee5878319a..190b505b6a 100644
--- a/src/javascript/jsc/bindings/exports.zig
+++ b/src/javascript/jsc/bindings/exports.zig
@@ -1,4 +1,4 @@
-const JSC = @import("./bindings.zig");
+const JSC = @import("../../../jsc.zig");
const Fs = @import("../../../fs.zig");
const CAPI = @import("../../../jsc.zig").C;
const JS = @import("../javascript.zig");
@@ -26,6 +26,7 @@ const JSModuleLoader = JSC.JSModuleLoader;
const JSModuleRecord = JSC.JSModuleRecord;
const Microtask = JSC.Microtask;
const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr;
+const Backtrace = @import("../../../deps/backtrace.zig");
pub const ZigGlobalObject = extern struct {
pub const shim = Shimmer("Zig", "GlobalObject", @This());
@@ -37,7 +38,9 @@ pub const ZigGlobalObject = extern struct {
pub const Interface: type = NewGlobalObject(JS.VirtualMachine);
pub fn create(class_ref: [*]CAPI.JSClassRef, count: i32, console: *anyopaque) *JSGlobalObject {
- return shim.cppFn("create", .{ class_ref, count, console });
+ var global = shim.cppFn("create", .{ class_ref, count, console });
+ Backtrace.reloadHandlers();
+ return global;
}
pub fn getModuleRegistryMap(global: *JSGlobalObject) *anyopaque {
@@ -169,6 +172,11 @@ pub const ZigErrorType = extern struct {
}
};
+/// do not use this reference directly, use JSC.Node.Readable
+pub const NodeReadableStream = JSC.Node.Readable.State;
+/// do not use this reference directly, use JSC.Node.Writable
+pub const NodeWritableStream = JSC.Node.Writable.State;
+
pub fn Errorable(comptime Type: type) type {
return extern struct {
result: Result,
@@ -301,6 +309,54 @@ pub const ZigStackFrameCode = enum(u8) {
}
};
+pub const Process = extern struct {
+ pub const shim = Shimmer("Bun", "Process", @This());
+ pub const name = "Process";
+ pub const namespace = shim.namespace;
+ const _bun: string = "bun";
+
+ pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void {
+ title.* = ZigString.init(_bun);
+ }
+
+ // TODO: https://github.com/nodejs/node/blob/master/deps/uv/src/unix/darwin-proctitle.c
+ pub fn setTitle(globalObject: *JSGlobalObject, _: *ZigString) callconv(.C) JSValue {
+ return ZigString.init(_bun).toValue(globalObject);
+ }
+
+ pub const getArgv = JSC.Node.Process.getArgv;
+ pub const getCwd = JSC.Node.Process.getCwd;
+ pub const setCwd = JSC.Node.Process.setCwd;
+
+ pub const Export = shim.exportFunctions(.{
+ .@"getTitle" = getTitle,
+ .@"setTitle" = setTitle,
+ .@"getArgv" = getArgv,
+ .@"getCwd" = getCwd,
+ .@"setCwd" = setCwd,
+ });
+
+ comptime {
+ if (!is_bindgen) {
+ @export(getTitle, .{
+ .name = Export[0].symbol_name,
+ });
+ @export(setTitle, .{
+ .name = Export[1].symbol_name,
+ });
+ @export(getArgv, .{
+ .name = Export[2].symbol_name,
+ });
+ @export(getCwd, .{
+ .name = Export[3].symbol_name,
+ });
+ @export(setCwd, .{
+ .name = Export[4].symbol_name,
+ });
+ }
+ }
+};
+
pub const ZigStackTrace = extern struct {
source_lines_ptr: [*c]ZigString,
source_lines_numbers: [*c]i32,
@@ -428,15 +484,18 @@ pub const ZigStackFrame = extern struct {
source_url: ZigString,
position: ZigStackFramePosition,
enable_color: bool,
- origin: *const ZigURL,
+ origin: ?*const ZigURL,
+
root_path: string = "",
pub fn format(this: SourceURLFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
- try writer.writeAll(this.origin.displayProtocol());
- try writer.writeAll("://");
- try writer.writeAll(this.origin.displayHostname());
- try writer.writeAll(":");
- try writer.writeAll(this.origin.port);
- try writer.writeAll("/blob:");
+ if (this.origin) |origin| {
+ try writer.writeAll(origin.displayProtocol());
+ try writer.writeAll("://");
+ try writer.writeAll(origin.displayHostname());
+ try writer.writeAll(":");
+ try writer.writeAll(origin.port);
+ try writer.writeAll("/blob:");
+ }
var source_slice = this.source_url.slice();
if (strings.startsWith(source_slice, this.root_path)) {
@@ -505,7 +564,7 @@ pub const ZigStackFrame = extern struct {
return NameFormatter{ .function_name = this.function_name, .code_type = this.code_type, .enable_color = enable_color };
}
- pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: *const ZigURL, comptime enable_color: bool) SourceURLFormatter {
+ pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: ?*const ZigURL, comptime enable_color: bool) SourceURLFormatter {
return SourceURLFormatter{ .source_url = this.source_url, .origin = origin, .root_path = root_path, .position = this.position, .enable_color = enable_color };
}
};
@@ -538,6 +597,16 @@ pub const ZigStackFramePosition = extern struct {
pub const ZigException = extern struct {
code: JSErrorCode,
runtime_type: JSRuntimeType,
+
+ /// SystemError only
+ errno: c_int = 0,
+ /// SystemError only
+ syscall: ZigString = ZigString.Empty,
+ /// SystemError only
+ system_code: ZigString = ZigString.Empty,
+ /// SystemError only
+ path: ZigString = ZigString.Empty,
+
name: ZigString,
message: ZigString,
stack: ZigStackTrace,
@@ -675,15 +744,40 @@ pub const ZigConsoleClient = struct {
};
}
- /// TODO: support %s %d %f %o %O
+ pub const MessageLevel = enum(u32) {
+ Log = 0,
+ Warning = 1,
+ Error = 2,
+ Debug = 3,
+ Info = 4,
+ _,
+ };
+
+ pub const MessageType = enum(u32) {
+ Log = 0,
+ Dir = 1,
+ DirXML = 2,
+ Table = 3,
+ Trace = 4,
+ StartGroup = 5,
+ StartGroupCollapsed = 6,
+ EndGroup = 7,
+ Clear = 8,
+ Assert = 9,
+ Timing = 10,
+ Profile = 11,
+ ProfileEnd = 12,
+ Image = 13,
+ _,
+ };
+
/// https://console.spec.whatwg.org/#formatter
pub fn messageWithTypeAndLevel(
//console_: ZigConsoleClient.Type,
_: ZigConsoleClient.Type,
- //message_type: u32,
- _: u32,
+ message_type: MessageType,
//message_level: u32,
- _: u32,
+ level: MessageLevel,
global: *JSGlobalObject,
vals: [*]JSValue,
len: usize,
@@ -693,129 +787,727 @@ pub const ZigConsoleClient = struct {
}
var console = JS.VirtualMachine.vm.console;
- var i: usize = 0;
- var buffered_writer = console.writer;
+
+ if (message_type == .Clear) {
+ Output.resetTerminal();
+ return;
+ }
+
+ if (message_type == .Assert and len == 0) {
+ const text = if (Output.enable_ansi_colors_stderr)
+ Output.prettyFmt("Assertion failed\n", true)
+ else
+ "Assertion failed\n";
+ console.error_writer.unbuffered_writer.writeAll(text) catch unreachable;
+ return;
+ }
+
+ const enable_colors = if (level == .Warning or level == .Error)
+ Output.enable_ansi_colors_stderr
+ else
+ Output.enable_ansi_colors_stdout;
+ var buffered_writer = if (level == .Warning or level == .Error)
+ console.error_writer
+ else
+ console.writer;
var writer = buffered_writer.writer();
- if (len == 1) {
- if (Output.enable_ansi_colors) {
- FormattableType.format(
- @TypeOf(buffered_writer.unbuffered_writer),
- buffered_writer.unbuffered_writer,
- vals[0],
- global,
- true,
- ) catch {};
- } else {
- FormattableType.format(
- @TypeOf(buffered_writer.unbuffered_writer),
- buffered_writer.unbuffered_writer,
- vals[0],
- global,
- false,
- ) catch {};
- }
+ const BufferedWriterType = @TypeOf(writer);
- _ = buffered_writer.unbuffered_writer.write("\n") catch 0;
+ var fmt: Formatter = undefined;
+ defer {
+ if (fmt.map_node) |node| {
+ node.data = fmt.map;
+ node.data.clearRetainingCapacity();
+ node.release();
+ }
+ }
+
+ if (len == 1) {
+ fmt = Formatter{ .remaining_values = &[_]JSValue{} };
+ const tag = Formatter.Tag.get(vals[0], global);
+
+ var unbuffered_writer = buffered_writer.unbuffered_writer.context.writer();
+ const UnbufferedWriterType = @TypeOf(unbuffered_writer);
+
+ if (tag.tag == .String) {
+ if (enable_colors) {
+ if (level == .Error) {
+ unbuffered_writer.writeAll(comptime Output.prettyFmt("", true)) catch unreachable;
+ }
+ fmt.format(
+ tag,
+ UnbufferedWriterType,
+ unbuffered_writer,
+ vals[0],
+ global,
+ true,
+ );
+ if (level == .Error) {
+ unbuffered_writer.writeAll(comptime Output.prettyFmt("", true)) catch unreachable;
+ }
+ } else {
+ fmt.format(
+ tag,
+ UnbufferedWriterType,
+ unbuffered_writer,
+ vals[0],
+ global,
+ false,
+ );
+ }
+ _ = unbuffered_writer.write("\n") catch 0;
+ } else {
+ defer buffered_writer.flush() catch {};
+ if (enable_colors) {
+ fmt.format(
+ tag,
+ BufferedWriterType,
+ writer,
+ vals[0],
+ global,
+ true,
+ );
+ } else {
+ fmt.format(
+ tag,
+ BufferedWriterType,
+ writer,
+ vals[0],
+ global,
+ false,
+ );
+ }
+ _ = writer.write("\n") catch 0;
+ }
return;
}
- var values = vals[0..len];
defer buffered_writer.flush() catch {};
- if (Output.enable_ansi_colors) {
- while (i < len) : (i += 1) {
- _ = if (i > 0) (writer.write(" ") catch 0);
+ var this_value: JSValue = vals[0];
+ fmt = Formatter{ .remaining_values = vals[0..len][1..] };
+ var tag: Formatter.Tag.Result = undefined;
- FormattableType.format(@TypeOf(writer), writer, values[i], global, true) catch {};
+ var any = false;
+ if (enable_colors) {
+ if (level == .Error) {
+ writer.writeAll(comptime Output.prettyFmt("", true)) catch unreachable;
+ }
+ while (true) {
+ if (any) {
+ _ = writer.write(" ") catch 0;
+ }
+ any = true;
+
+ tag = Formatter.Tag.get(this_value, global);
+ if (tag.tag == .String and fmt.remaining_values.len > 0) {
+ tag.tag = .StringPossiblyFormatted;
+ }
+
+ fmt.format(tag, BufferedWriterType, writer, this_value, global, true);
+ if (fmt.remaining_values.len == 0) {
+ break;
+ }
+
+ this_value = fmt.remaining_values[0];
+ fmt.remaining_values = fmt.remaining_values[1..];
+ }
+ if (level == .Error) {
+ writer.writeAll(comptime Output.prettyFmt("", true)) catch unreachable;
}
} else {
- while (i < len) : (i += 1) {
- _ = if (i > 0) (writer.write(" ") catch 0);
+ while (true) {
+ if (any) {
+ _ = writer.write(" ") catch 0;
+ }
+ any = true;
+ tag = Formatter.Tag.get(this_value, global);
+ if (tag.tag == .String and fmt.remaining_values.len > 0) {
+ tag.tag = .StringPossiblyFormatted;
+ }
- FormattableType.format(@TypeOf(writer), writer, values[i], global, false) catch {};
+ fmt.format(tag, BufferedWriterType, writer, this_value, global, false);
+ if (fmt.remaining_values.len == 0)
+ break;
+
+ this_value = fmt.remaining_values[0];
+ fmt.remaining_values = fmt.remaining_values[1..];
}
}
_ = writer.write("\n") catch 0;
}
- const FormattableType = enum {
- Error,
- String,
- Undefined,
- Double,
- Integer,
- Null,
- Boolean,
- const CellType = CAPI.CellType;
- threadlocal var name_buf: [512]u8 = undefined;
- pub fn format(comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) anyerror!void {
- if (comptime @hasDecl(@import("root"), "bindgen")) {
- return;
+ pub const Formatter = struct {
+ remaining_values: []JSValue,
+ map: Visited.Map = undefined,
+ map_node: ?*Visited.Pool.Node = null,
+ hide_native: bool = false,
+
+ // For detecting circular references
+ pub const Visited = struct {
+ const ObjectPool = @import("../../../pool.zig").ObjectPool;
+ pub const Map = std.AutoHashMap(i64, void);
+ pub const Pool = ObjectPool(
+ Map,
+ struct {
+ pub fn init(allocator: std.mem.Allocator) anyerror!Map {
+ return Map.init(allocator);
+ }
+ }.init,
+ true,
+ );
+ };
+
+ pub const Tag = enum {
+ StringPossiblyFormatted,
+ String,
+ Undefined,
+ Double,
+ Integer,
+ Null,
+ Boolean,
+ Array,
+ Object,
+ Function,
+ Class,
+ Error,
+ TypedArray,
+ Map,
+ Set,
+ Symbol,
+ BigInt,
+
+ GlobalObject,
+ Private,
+ Promise,
+
+ JSON,
+ NativeCode,
+ ArrayBuffer,
+
+ pub inline fn canHaveCircularReferences(tag: Tag) bool {
+ return tag == .Array or tag == .Object or tag == .Map or tag == .Set;
}
- if (value.isCell()) {
- if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| {
- const priv_data = JSPrivateDataPtr.from(private_data_ptr);
- switch (priv_data.tag()) {
- .BuildError => {
- const build_error = priv_data.as(JS.BuildError);
- try build_error.msg.formatWriter(Writer, writer, enable_ansi_colors);
- return;
- },
- .ResolveError => {
- const resolve_error = priv_data.as(JS.ResolveError);
- try resolve_error.msg.formatWriter(Writer, writer, enable_ansi_colors);
- return;
- },
- else => {},
- }
+ const Result = struct {
+ tag: Tag,
+ cell: JSValue.JSType = JSValue.JSType.Cell,
+ };
+
+ pub fn get(value: JSValue, globalThis: *JSGlobalObject) Result {
+ if (value.isInt32()) {
+ return .{
+ .tag = .Integer,
+ };
+ } else if (value.isNumber()) {
+ return .{
+ .tag = .Double,
+ };
+ } else if (value.isUndefined()) {
+ return .{
+ .tag = .Undefined,
+ };
+ } else if (value.isNull()) {
+ return .{
+ .tag = .Null,
+ };
+ } else if (value.isBoolean()) {
+ return .{
+ .tag = .Boolean,
+ };
}
- switch (@intToEnum(CellType, value.asCell().getType())) {
- CellType.ErrorInstanceType => {
- JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors);
- return;
- },
+ const js_type = value.jsType();
- CellType.GlobalObjectType => {
- _ = try writer.write("[globalThis]");
- return;
+ if (js_type.isHidden()) return .{ .tag = .NativeCode };
+
+ if (CAPI.JSObjectGetPrivate(value.asObjectRef()) != null)
+ return .{
+ .tag = .Private,
+ };
+
+ // If we check an Object has a method table and it does not
+ // it will crash
+ const callable = js_type != .Object and value.isCallable(globalThis.vm());
+
+ if (value.isClass(globalThis) and !callable) {
+ // Temporary workaround
+ // console.log(process.env) shows up as [class JSCallbackObject]
+ // We want to print it like an object
+ if (CAPI.JSValueIsObjectOfClass(globalThis.ref(), value.asObjectRef(), JSC.Bun.EnvironmentVariables.Class.get().?[0])) {
+ return .{
+ .tag = .Object,
+ };
+ }
+ return .{
+ .tag = .Class,
+ };
+ }
+
+ if (callable) {
+ return .{
+ .tag = .Function,
+ };
+ }
+
+ return .{
+ .tag = switch (js_type) {
+ JSValue.JSType.ErrorInstance => .Error,
+ JSValue.JSType.NumberObject => .Double,
+ JSValue.JSType.DerivedArray, JSValue.JSType.Array => .Array,
+ JSValue.JSType.DerivedStringObject, JSValue.JSType.String, JSValue.JSType.StringObject => .String,
+ JSValue.JSType.RegExpObject,
+ JSValue.JSType.Symbol,
+ => .String,
+ JSValue.JSType.BooleanObject => .Boolean,
+ JSValue.JSType.JSFunction => .Function,
+ JSValue.JSType.JSWeakMap, JSValue.JSType.JSMap => .Map,
+ JSValue.JSType.JSWeakSet, JSValue.JSType.JSSet => .Set,
+ JSValue.JSType.JSDate => .JSON,
+ JSValue.JSType.JSPromise => .Promise,
+ JSValue.JSType.Object, JSValue.JSType.FinalObject => .Object,
+
+ JSValue.JSType.Int8Array,
+ JSValue.JSType.Uint8Array,
+ JSValue.JSType.Uint8ClampedArray,
+ JSValue.JSType.Int16Array,
+ JSValue.JSType.Uint16Array,
+ JSValue.JSType.Int32Array,
+ JSValue.JSType.Uint32Array,
+ JSValue.JSType.Float32Array,
+ JSValue.JSType.Float64Array,
+ JSValue.JSType.BigInt64Array,
+ JSValue.JSType.BigUint64Array,
+ => .TypedArray,
+
+ // None of these should ever exist here
+ // But we're going to check anyway
+ .GetterSetter,
+ .CustomGetterSetter,
+ .APIValueWrapper,
+ .NativeExecutable,
+ .ProgramExecutable,
+ .ModuleProgramExecutable,
+ .EvalExecutable,
+ .FunctionExecutable,
+ .UnlinkedFunctionExecutable,
+ .UnlinkedProgramCodeBlock,
+ .UnlinkedModuleProgramCodeBlock,
+ .UnlinkedEvalCodeBlock,
+ .UnlinkedFunctionCodeBlock,
+ .CodeBlock,
+ .JSImmutableButterfly,
+ .JSSourceCode,
+ .JSScriptFetcher,
+ .JSScriptFetchParameters,
+ .JSCallee,
+ .GlobalLexicalEnvironment,
+ .LexicalEnvironment,
+ .ModuleEnvironment,
+ .StrictEvalActivation,
+ .WithScope,
+ => .NativeCode,
+ else => .JSON,
+ },
+ .cell = js_type,
+ };
+ }
+ };
+
+ const CellType = CAPI.CellType;
+ threadlocal var name_buf: [512]u8 = undefined;
+
+ fn writeWithFormatting(
+ this: *Formatter,
+ comptime Writer: type,
+ writer_: Writer,
+ comptime Slice: type,
+ slice_: Slice,
+ globalThis: *JSGlobalObject,
+ comptime enable_ansi_colors: bool,
+ ) void {
+ var writer = WrappedWriter(Writer){ .ctx = writer_ };
+ var slice = slice_;
+ var i: u32 = 0;
+ var len: u32 = @truncate(u32, slice.len);
+ while (i < len) : (i += 1) {
+ switch (slice[i]) {
+ '%' => {
+ i += 1;
+ if (i >= len)
+ break;
+
+ const token = switch (slice[i]) {
+ 's' => Tag.String,
+ 'f' => Tag.Double,
+ 'o' => Tag.Undefined,
+ 'O' => Tag.Object,
+ 'd', 'i' => Tag.Integer,
+ else => continue,
+ };
+
+ // Flush everything up to the %
+ const end = slice[0 .. i - 1];
+ writer.writeAll(end);
+ slice = slice[@minimum(slice.len, i + 1)..];
+ i = 0;
+ len = @truncate(u32, slice.len);
+ const next_value = this.remaining_values[0];
+ this.remaining_values = this.remaining_values[1..];
+ switch (token) {
+ Tag.String => this.printAs(Tag.String, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors),
+ Tag.Double => this.printAs(Tag.Double, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors),
+ Tag.Object => this.printAs(Tag.Object, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors),
+ Tag.Integer => this.printAs(Tag.Integer, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors),
+
+ // undefined is overloaded to mean the '%o" field
+ Tag.Undefined => this.format(Tag.get(next_value, globalThis), Writer, writer_, next_value, globalThis, enable_ansi_colors),
+
+ else => unreachable,
+ }
+ if (this.remaining_values.len == 0) break;
+ },
+ '\\' => {
+ i += 1;
+ if (i >= len)
+ break;
+ if (slice[i] == '%') i += 2;
},
else => {},
}
}
- if (value.isInt32()) {
- try writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{value.toInt32()});
- } else if (value.isNumber()) {
- try writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{value.asNumber()});
- } else if (value.isUndefined()) {
- try writer.print(comptime Output.prettyFmt("undefined", enable_ansi_colors), .{});
- } else if (value.isNull()) {
- try writer.print(comptime Output.prettyFmt("null", enable_ansi_colors), .{});
- } else if (value.isBoolean()) {
- if (value.toBoolean()) {
- try writer.print(comptime Output.prettyFmt("true", enable_ansi_colors), .{});
- } else {
- try writer.print(comptime Output.prettyFmt("false", enable_ansi_colors), .{});
+ if (slice.len > 0) writer.writeAll(slice);
+ }
+
+ pub fn WrappedWriter(comptime Writer: type) type {
+ return struct {
+ ctx: Writer,
+
+ pub fn print(self: *@This(), comptime fmt: string, args: anytype) void {
+ self.ctx.print(fmt, args) catch unreachable;
+ }
+
+ pub inline fn writeAll(self: *@This(), buf: []const u8) void {
+ self.ctx.writeAll(buf) catch unreachable;
+ }
+ };
+ }
+
+ pub fn printAs(
+ this: *Formatter,
+ comptime Format: Formatter.Tag,
+ comptime Writer: type,
+ writer_: Writer,
+ value: JSValue,
+ globalThis: *JSGlobalObject,
+ jsType: JSValue.JSType,
+ comptime enable_ansi_colors: bool,
+ ) void {
+ var writer = WrappedWriter(Writer){ .ctx = writer_ };
+
+ if (comptime Format.canHaveCircularReferences()) {
+ if (this.map_node == null) {
+ this.map_node = Visited.Pool.get(default_allocator);
+ this.map_node.?.data.clearRetainingCapacity();
+ this.map = this.map_node.?.data;
+ }
+
+ var entry = this.map.getOrPut(@enumToInt(value)) catch unreachable;
+ if (entry.found_existing) {
+ writer.writeAll(comptime Output.prettyFmt("[Circular]", enable_ansi_colors));
+ return;
}
- // } else if (value.isSymbol()) {
- // try writer.print(comptime Output.prettyFmt("Symbol(\"{s}\")", enable_ansi_colors), .{ value.getDescriptionProperty() });
- } else if (value.isClass(globalThis)) {
- var printable = ZigString.init(&name_buf);
- value.getClassName(globalThis, &printable);
- try writer.print("[class {s}]", .{printable.slice()});
- } else if (value.isCallable(globalThis.vm())) {
- var printable = ZigString.init(&name_buf);
- value.getNameProperty(globalThis, &printable);
- try writer.print("[Function {s}]", .{printable.slice()});
- } else {
- var str = value.toWTFString(JS.VirtualMachine.vm.global);
- _ = try writer.write(str.slice());
}
+
+ switch (comptime Format) {
+ .StringPossiblyFormatted => {
+ var str = ZigString.init("");
+ value.toZigString(&str, globalThis);
+
+ if (!str.is16Bit()) {
+ const slice = str.slice();
+ this.writeWithFormatting(Writer, writer_, @TypeOf(slice), slice, globalThis, enable_ansi_colors);
+ } else {
+ // TODO: UTF16
+ writer.print("{}", .{str});
+ }
+ },
+ .String => {
+ var str = ZigString.init("");
+ value.toZigString(&str, globalThis);
+ if (jsType == .RegExpObject) {
+ writer.print(comptime Output.prettyFmt("", enable_ansi_colors), .{});
+ }
+
+ writer.print("{}", .{str});
+
+ if (jsType == .RegExpObject) {
+ writer.print(comptime Output.prettyFmt("", enable_ansi_colors), .{});
+ }
+ },
+ .Integer => {
+ writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{value.toInt32()});
+ },
+ .Double => {
+ writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{value.asNumber()});
+ },
+ .Undefined => {
+ writer.print(comptime Output.prettyFmt("undefined", enable_ansi_colors), .{});
+ },
+ .Null => {
+ writer.print(comptime Output.prettyFmt("null", enable_ansi_colors), .{});
+ },
+ .Error => {
+ JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors);
+ },
+ .Class => {
+ var printable = ZigString.init(&name_buf);
+ value.getClassName(globalThis, &printable);
+ if (printable.len == 0) {
+ writer.print(comptime Output.prettyFmt("[class]", enable_ansi_colors), .{});
+ } else {
+ writer.print(comptime Output.prettyFmt("[class {}]", enable_ansi_colors), .{printable});
+ }
+ },
+ .Function => {
+ var printable = ZigString.init(&name_buf);
+ value.getNameProperty(globalThis, &printable);
+
+ if (printable.len == 0) {
+ writer.print(comptime Output.prettyFmt("[Function]", enable_ansi_colors), .{});
+ } else {
+ writer.print(comptime Output.prettyFmt("[Function: {}]", enable_ansi_colors), .{printable});
+ }
+ },
+ .Array => {
+ const len = value.getLengthOfArray(globalThis);
+ if (len == 0) {
+ writer.writeAll("[]");
+ return;
+ }
+
+ writer.writeAll("[ ");
+ var i: u32 = 0;
+ var ref = value.asObjectRef();
+ while (i < len) : (i += 1) {
+ if (i > 0) {
+ writer.writeAll(", ");
+ }
+
+ const element = JSValue.fromRef(CAPI.JSObjectGetPropertyAtIndex(globalThis.ref(), ref, i, null));
+ const tag = Tag.get(element, globalThis);
+
+ if (tag.cell.isStringLike()) {
+ if (comptime enable_ansi_colors) {
+ writer.writeAll(comptime Output.prettyFmt("", true));
+ }
+ writer.writeAll("\"");
+ }
+
+ this.format(tag, Writer, writer_, element, globalThis, enable_ansi_colors);
+
+ if (tag.cell.isStringLike()) {
+ writer.writeAll("\"");
+ if (comptime enable_ansi_colors) {
+ writer.writeAll(comptime Output.prettyFmt("", true));
+ }
+ }
+ }
+
+ writer.writeAll(" ]");
+ },
+ .Private => {
+ if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| {
+ const priv_data = JSPrivateDataPtr.from(private_data_ptr);
+ switch (priv_data.tag()) {
+ .BuildError => {
+ const build_error = priv_data.as(JS.BuildError);
+ build_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {};
+ return;
+ },
+ .ResolveError => {
+ const resolve_error = priv_data.as(JS.ResolveError);
+ resolve_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {};
+ return;
+ },
+ else => {},
+ }
+ }
+
+ writer.writeAll("[native code]");
+ },
+ .NativeCode => {
+ writer.writeAll("[native code]");
+ },
+ .Promise => {
+ writer.writeAll("Promise { " ++ comptime Output.prettyFmt("", enable_ansi_colors));
+
+ switch (JSPromise.status(@ptrCast(*JSPromise, value.asObjectRef().?), globalThis.vm())) {
+ JSPromise.Status.Pending => {
+ writer.writeAll("");
+ },
+ JSPromise.Status.Fulfilled => {
+ writer.writeAll("");
+ },
+ JSPromise.Status.Rejected => {
+ writer.writeAll("");
+ },
+ }
+
+ writer.writeAll(comptime Output.prettyFmt("", enable_ansi_colors) ++ " }");
+ },
+ .Boolean => {
+ if (value.toBoolean()) {
+ writer.writeAll(comptime Output.prettyFmt("true", enable_ansi_colors));
+ } else {
+ writer.writeAll(comptime Output.prettyFmt("false", enable_ansi_colors));
+ }
+ },
+ .GlobalObject => {
+ writer.writeAll(comptime Output.prettyFmt("[globalThis]", enable_ansi_colors));
+ },
+ .Map => {},
+ .Set => {},
+ .JSON => {
+ var str = ZigString.init("");
+ value.jsonStringify(globalThis, 0, &str);
+ if (jsType == JSValue.JSType.JSDate) {
+ // in the code for printing dates, it never exceeds this amount
+ var iso_string_buf: [36]u8 = undefined;
+ var out_buf: []const u8 = std.fmt.bufPrint(&iso_string_buf, "{}", .{str}) catch "";
+ if (out_buf.len > 2) {
+ // trim the quotes
+ out_buf = out_buf[1 .. out_buf.len - 1];
+ }
+
+ writer.print(comptime Output.prettyFmt("{s}", enable_ansi_colors), .{out_buf});
+ return;
+ }
+
+ writer.print("{}", .{str});
+ },
+ .Object => {
+ var object = value.asObjectRef();
+ var array = CAPI.JSObjectCopyPropertyNames(globalThis.ref(), object);
+ defer CAPI.JSPropertyNameArrayRelease(array);
+ const count_ = CAPI.JSPropertyNameArrayGetCount(array);
+ var i: usize = 0;
+
+ var name_str = ZigString.init("");
+ value.getPrototype(globalThis).getNameProperty(globalThis, &name_str);
+
+ if (name_str.len > 0 and !strings.eqlComptime(name_str.slice(), "Object")) {
+ writer.print("{} ", .{name_str});
+ }
+
+ if (count_ == 0) {
+ writer.writeAll("{ }");
+ return;
+ }
+
+ writer.writeAll("{ ");
+
+ while (i < count_) : (i += 1) {
+ var property_name_ref = CAPI.JSPropertyNameArrayGetNameAtIndex(array, i);
+ defer CAPI.JSStringRelease(property_name_ref);
+ var prop = CAPI.JSStringGetCharacters8Ptr(property_name_ref)[0..CAPI.JSStringGetLength(property_name_ref)];
+
+ var property_value = CAPI.JSObjectGetProperty(globalThis.ref(), object, property_name_ref, null);
+ const tag = Tag.get(JSValue.fromRef(property_value), globalThis);
+
+ if (tag.cell.isHidden()) continue;
+
+ writer.print(
+ comptime Output.prettyFmt("{s}: ", enable_ansi_colors),
+ .{prop[0..@minimum(prop.len, 128)]},
+ );
+
+ if (tag.cell.isStringLike()) {
+ if (comptime enable_ansi_colors) {
+ writer.writeAll(comptime Output.prettyFmt("", true));
+ }
+ writer.writeAll("\"");
+ }
+
+ this.format(tag, Writer, writer_, JSValue.fromRef(property_value), globalThis, enable_ansi_colors);
+
+ if (tag.cell.isStringLike()) {
+ writer.writeAll("\"");
+ if (comptime enable_ansi_colors) {
+ writer.writeAll(comptime Output.prettyFmt("", true));
+ }
+ }
+
+ if (i + 1 < count_) {
+ writer.writeAll(", ");
+ }
+ }
+
+ writer.writeAll(" }");
+ },
+ .TypedArray => {
+ const len = value.getLengthOfArray(globalThis);
+ if (len == 0) {
+ writer.writeAll("[]");
+ return;
+ }
+
+ writer.writeAll("[ ");
+ var i: u32 = 0;
+ var buffer = JSC.Buffer.fromJS(globalThis, value, null).?;
+ const slice = buffer.slice();
+ while (i < len) : (i += 1) {
+ if (i > 0) {
+ writer.writeAll(", ");
+ }
+
+ writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{slice[i]});
+ }
+
+ writer.writeAll(" ]");
+ },
+ else => {},
+ }
+ }
+
+ pub fn format(this: *Formatter, result: Tag.Result, comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) void {
+ if (comptime @hasDecl(@import("root"), "bindgen")) {
+ return;
+ }
+
+ // This looks incredibly redudant. We make the Formatter.Tag a
+ // comptime var so we have to repeat it here. The rationale there is
+ // it _should_ limit the stack usage because each version of the
+ // function will be relatively small
+ return switch (result.tag) {
+ .StringPossiblyFormatted => this.printAs(.StringPossiblyFormatted, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .String => this.printAs(.String, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Undefined => this.printAs(.Undefined, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Double => this.printAs(.Double, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Integer => this.printAs(.Integer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Null => this.printAs(.Null, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Boolean => this.printAs(.Boolean, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Array => this.printAs(.Array, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Object => this.printAs(.Object, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Function => this.printAs(.Function, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Class => this.printAs(.Class, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Error => this.printAs(.Error, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .TypedArray => this.printAs(.TypedArray, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Map => this.printAs(.Map, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Set => this.printAs(.Set, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Symbol => this.printAs(.Symbol, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .BigInt => this.printAs(.BigInt, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .GlobalObject => this.printAs(.GlobalObject, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Private => this.printAs(.Private, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .Promise => this.printAs(.Promise, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .JSON => this.printAs(.JSON, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .NativeCode => this.printAs(.NativeCode, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ .ArrayBuffer => this.printAs(.ArrayBuffer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors),
+ };
}
};
@@ -926,12 +1618,16 @@ pub const ZigConsoleClient = struct {
// console
_: ZigConsoleClient.Type,
// global
- _: *JSGlobalObject,
+ globalThis: *JSGlobalObject,
// chars
_: [*]const u8,
// len
_: usize,
- ) callconv(.C) void {}
+ ) callconv(.C) void {
+ // TODO: this does an extra JSONStringify and we don't need it to!
+ var snapshot: [1]JSValue = .{globalThis.generateHeapSnapshot()};
+ ZigConsoleClient.messageWithTypeAndLevel(undefined, MessageType.Log, MessageLevel.Debug, globalThis, &snapshot, 1);
+ }
pub fn timeStamp(
// console
_: ZigConsoleClient.Type,
@@ -1120,3 +1816,12 @@ comptime {
@export(ErrorCode.ParserError, .{ .name = "Zig_ErrorCodeParserError" });
@export(ErrorCode.JSErrorObject, .{ .name = "Zig_ErrorCodeJSErrorObject" });
}
+
+comptime {
+ if (!is_bindgen) {
+ _ = Process.getTitle;
+ _ = Process.setTitle;
+ std.testing.refAllDecls(NodeReadableStream);
+ std.testing.refAllDecls(NodeWritableStream);
+ }
+}
diff --git a/src/javascript/jsc/bindings/header-gen.zig b/src/javascript/jsc/bindings/header-gen.zig
index bdf1778ad2..9a9b9314fc 100644
--- a/src/javascript/jsc/bindings/header-gen.zig
+++ b/src/javascript/jsc/bindings/header-gen.zig
@@ -103,7 +103,7 @@ pub const C_Generator = struct {
pub fn gen_func(
self: *Self,
comptime name: []const u8,
- comptime func: FnDecl,
+ comptime func: anytype,
comptime meta: FnMeta,
comptime _: []const []const u8,
comptime rewrite_return: bool,
@@ -121,16 +121,21 @@ pub const C_Generator = struct {
.export_zig => self.write("ZIG_DECL "),
}
+ const return_type: type = comptime if (@TypeOf(func.return_type) == ?type)
+ (func.return_type orelse void)
+ else
+ func.return_type;
+
if (comptime rewrite_return) {
self.writeType(void);
} else {
- self.writeType(comptime func.return_type);
+ self.writeType(comptime return_type);
}
self.write(" " ++ name ++ "(");
if (comptime rewrite_return) {
- self.writeType(comptime func.return_type);
+ self.writeType(comptime return_type);
self.write("_buf ret_value");
if (comptime meta.args.len > 0) {
@@ -515,9 +520,15 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
pub fn processStaticExport(comptime _: Self, _: anytype, gen: *C_Generator, comptime static_export: StaticExport) void {
const fn_meta = comptime @typeInfo(static_export.Type).Fn;
+ const DeclData = static_export.Decl().data;
+
gen.gen_func(
comptime static_export.symbol_name,
- comptime static_export.Decl().data.Fn,
+ comptime switch (DeclData) {
+ .Fn => |Fn| Fn,
+ .Var => |Var| @typeInfo(Var).Fn,
+ else => unreachable,
+ },
comptime fn_meta,
comptime std.mem.zeroes([]const []const u8),
false,
diff --git a/src/javascript/jsc/bindings/headers-cpp.h b/src/javascript/jsc/bindings/headers-cpp.h
index 4ea0be1a6b..470feff87d 100644
--- a/src/javascript/jsc/bindings/headers-cpp.h
+++ b/src/javascript/jsc/bindings/headers-cpp.h
@@ -1,4 +1,4 @@
-//-- AUTOGENERATED FILE -- 1640933554
+//-- AUTOGENERATED FILE -- 1642473926
// clang-format off
#pragma once
@@ -216,6 +216,22 @@ extern "C" const size_t WTF__StringView_object_align_ = alignof(WTF::StringView)
extern "C" const size_t Zig__GlobalObject_object_size_ = sizeof(Zig::GlobalObject);
extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObject);
+#ifndef INCLUDED_BunStream_h
+#define INCLUDED_BunStream_h
+#include BunStream.h
+#endif
+
+extern "C" const size_t Bun__Readable_object_size_ = sizeof(Bun__Readable);
+extern "C" const size_t Bun__Readable_object_align_ = alignof(Bun__Readable);
+
+#ifndef INCLUDED_BunStream_h
+#define INCLUDED_BunStream_h
+#include BunStream.h
+#endif
+
+extern "C" const size_t Bun__Writable_object_size_ = sizeof(Bun__Writable);
+extern "C" const size_t Bun__Writable_object_align_ = alignof(Bun__Writable);
+
#ifndef INCLUDED__ZigConsoleClient_h_
#define INCLUDED__ZigConsoleClient_h_
#include "ZigConsoleClient.h"
@@ -224,8 +240,8 @@ extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObj
extern "C" const size_t Zig__ConsoleClient_object_size_ = sizeof(Zig::ConsoleClient);
extern "C" const size_t Zig__ConsoleClient_object_align_ = alignof(Zig::ConsoleClient);
-const size_t sizes[26] = {sizeof(JSC::JSObject), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject)};
+const size_t sizes[29] = {sizeof(JSC::JSObject), sizeof(SystemError), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject), sizeof(Bun__Readable), sizeof(Bun__Writable)};
-const char* names[26] = {"JSC__JSObject", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject"};
+const char* names[29] = {"JSC__JSObject", "SystemError", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject", "Bun__Readable", "Bun__Writable"};
-const size_t aligns[26] = {alignof(JSC::JSObject), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject)};
+const size_t aligns[29] = {alignof(JSC::JSObject), alignof(SystemError), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject), alignof(Bun__Readable), alignof(Bun__Writable)};
diff --git a/src/javascript/jsc/bindings/headers-handwritten.h b/src/javascript/jsc/bindings/headers-handwritten.h
index e07eca6b68..cf7c87e4f6 100644
--- a/src/javascript/jsc/bindings/headers-handwritten.h
+++ b/src/javascript/jsc/bindings/headers-handwritten.h
@@ -35,6 +35,14 @@ typedef struct ErrorableResolvedSource {
bool success;
} ErrorableResolvedSource;
+typedef struct SystemError {
+ int errno_;
+ ZigString code;
+ ZigString message;
+ ZigString path;
+ ZigString syscall;
+} SystemError;
+
typedef uint8_t ZigStackFrameCode;
const ZigStackFrameCode ZigStackFrameCodeNone = 0;
const ZigStackFrameCode ZigStackFrameCodeEval = 1;
@@ -74,6 +82,10 @@ typedef struct ZigStackTrace {
typedef struct ZigException {
unsigned char code;
uint16_t runtime_type;
+ int errno_;
+ ZigString syscall;
+ ZigString code_;
+ ZigString path;
ZigString name;
ZigString message;
ZigStackTrace stack;
@@ -93,9 +105,83 @@ const JSErrorCode JSErrorCodeOutOfMemoryError = 8;
const JSErrorCode JSErrorCodeStackOverflow = 253;
const JSErrorCode JSErrorCodeUserErrorCode = 254;
+#pragma mark - Stream
+
+typedef uint8_t Encoding;
+const Encoding Encoding__utf8 = 0;
+const Encoding Encoding__ucs2 = 1;
+const Encoding Encoding__utf16le = 2;
+const Encoding Encoding__latin1 = 3;
+const Encoding Encoding__ascii = 4;
+const Encoding Encoding__base64 = 5;
+const Encoding Encoding__base64url = 6;
+const Encoding Encoding__hex = 7;
+const Encoding Encoding__buffer = 8;
+
+typedef uint8_t WritableEvent;
+const WritableEvent WritableEvent__Close = 0;
+const WritableEvent WritableEvent__Drain = 1;
+const WritableEvent WritableEvent__Error = 2;
+const WritableEvent WritableEvent__Finish = 3;
+const WritableEvent WritableEvent__Pipe = 4;
+const WritableEvent WritableEvent__Unpipe = 5;
+const WritableEvent WritableEvent__Open = 6;
+const WritableEvent WritableEventUser = 254;
+
+typedef uint8_t ReadableEvent;
+
+const ReadableEvent ReadableEvent__Close = 0;
+const ReadableEvent ReadableEvent__Data = 1;
+const ReadableEvent ReadableEvent__End = 2;
+const ReadableEvent ReadableEvent__Error = 3;
+const ReadableEvent ReadableEvent__Pause = 4;
+const ReadableEvent ReadableEvent__Readable = 5;
+const ReadableEvent ReadableEvent__Resume = 6;
+const ReadableEvent ReadableEvent__Open = 7;
+const ReadableEvent ReadableEventUser = 254;
+
+typedef struct {
+ uint32_t highwater_mark;
+ Encoding encoding;
+ int32_t start;
+ int32_t end;
+ bool readable;
+ bool aborted;
+ bool did_read;
+ bool ended;
+ uint8_t flowing;
+ bool emit_close;
+ bool emit_end;
+} Bun__Readable;
+
+typedef struct {
+ uint32_t highwater_mark;
+ Encoding encoding;
+ uint32_t start;
+ bool destroyed;
+ bool ended;
+ bool corked;
+ bool finished;
+ bool emit_close;
+} Bun__Writable;
+
#ifdef __cplusplus
+
extern "C" ZigErrorCode Zig_ErrorCodeParserError;
extern "C" void ZigString__free(const unsigned char *ptr, size_t len, void *allocator);
extern "C" void Microtask__run(void *ptr, void *global);
+
+// Used in process.version
+extern "C" const char *Bun__version;
+
+// Used in process.versions
+extern "C" const char *Bun__versions_webkit;
+extern "C" const char *Bun__versions_mimalloc;
+extern "C" const char *Bun__versions_libarchive;
+extern "C" const char *Bun__versions_picohttpparser;
+extern "C" const char *Bun__versions_boringssl;
+extern "C" const char *Bun__versions_zlib;
+extern "C" const char *Bun__versions_zig;
+
#endif
diff --git a/src/javascript/jsc/bindings/headers-replacements.zig b/src/javascript/jsc/bindings/headers-replacements.zig
index e45f0348d0..96c058d562 100644
--- a/src/javascript/jsc/bindings/headers-replacements.zig
+++ b/src/javascript/jsc/bindings/headers-replacements.zig
@@ -53,4 +53,8 @@ pub const ZigStackTrace = bindings.ZigStackTrace;
pub const ReturnableException = bindings.ReturnableException;
pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask;
pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback;
+pub const SystemError = bindings.SystemError;
const JSClassRef = bindings.C.JSClassRef;
+pub const JSC__CatchScope = bindings.CatchScope;
+pub const Bun__Readable = bindings.NodeReadableStream;
+pub const Bun__Writable = bindings.NodeWritableStream;
diff --git a/src/javascript/jsc/bindings/headers.h b/src/javascript/jsc/bindings/headers.h
index 6ae0dae83e..9db733c025 100644
--- a/src/javascript/jsc/bindings/headers.h
+++ b/src/javascript/jsc/bindings/headers.h
@@ -1,5 +1,5 @@
// clang-format: off
-//-- AUTOGENERATED FILE -- 1640933554
+//-- AUTOGENERATED FILE -- 1642473926
#pragma once
#include
@@ -78,55 +78,58 @@ typedef void* JSClassRef;
typedef char* bJSC__Identifier_buf;
#ifndef __cplusplus
- typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype
+ typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope
typedef struct JSC__GeneratorPrototype JSC__GeneratorPrototype; // JSC::GeneratorPrototype
typedef struct JSC__ArrayIteratorPrototype JSC__ArrayIteratorPrototype; // JSC::ArrayIteratorPrototype
- typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype
- typedef bWTF__StringView WTF__StringView; // WTF::StringView
+ typedef ErrorableResolvedSource ErrorableResolvedSource;
typedef struct JSC__JSPromisePrototype JSC__JSPromisePrototype; // JSC::JSPromisePrototype
- typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope
- typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope
+ typedef ErrorableZigString ErrorableZigString;
typedef bJSC__PropertyName JSC__PropertyName; // JSC::PropertyName
typedef bJSC__JSObject JSC__JSObject; // JSC::JSObject
- typedef ErrorableResolvedSource ErrorableResolvedSource;
- typedef ErrorableZigString ErrorableZigString;
typedef bWTF__ExternalStringImpl WTF__ExternalStringImpl; // WTF::ExternalStringImpl
typedef struct JSC__AsyncIteratorPrototype JSC__AsyncIteratorPrototype; // JSC::AsyncIteratorPrototype
- typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl
typedef bJSC__JSLock JSC__JSLock; // JSC::JSLock
typedef bJSC__JSModuleLoader JSC__JSModuleLoader; // JSC::JSModuleLoader
- typedef bJSC__VM JSC__VM; // JSC::VM
- typedef JSClassRef JSClassRef;
typedef struct JSC__AsyncGeneratorPrototype JSC__AsyncGeneratorPrototype; // JSC::AsyncGeneratorPrototype
typedef struct JSC__AsyncGeneratorFunctionPrototype JSC__AsyncGeneratorFunctionPrototype; // JSC::AsyncGeneratorFunctionPrototype
- typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject
- typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction
- typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype
- typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype
typedef bJSC__Identifier JSC__Identifier; // JSC::Identifier
- typedef bJSC__JSPromise JSC__JSPromise; // JSC::JSPromise
- typedef ZigException ZigException;
- typedef struct JSC__SetIteratorPrototype JSC__SetIteratorPrototype; // JSC::SetIteratorPrototype
- typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode
+ typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype
typedef struct Zig__JSMicrotaskCallback Zig__JSMicrotaskCallback; // Zig::JSMicrotaskCallback
+ typedef bJSC__JSPromise JSC__JSPromise; // JSC::JSPromise
+ typedef struct JSC__SetIteratorPrototype JSC__SetIteratorPrototype; // JSC::SetIteratorPrototype
+ typedef SystemError SystemError;
typedef bJSC__JSCell JSC__JSCell; // JSC::JSCell
- typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype
- typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype
typedef bJSC__SourceOrigin JSC__SourceOrigin; // JSC::SourceOrigin
- typedef ZigString ZigString;
typedef bJSC__JSModuleRecord JSC__JSModuleRecord; // JSC::JSModuleRecord
typedef bWTF__String WTF__String; // WTF::String
typedef bWTF__URL WTF__URL; // WTF::URL
- typedef int64_t JSC__JSValue;
typedef struct JSC__IteratorPrototype JSC__IteratorPrototype; // JSC::IteratorPrototype
+ typedef Bun__Readable Bun__Readable;
typedef bJSC__JSInternalPromise JSC__JSInternalPromise; // JSC::JSInternalPromise
+ typedef Bun__Writable Bun__Writable;
+ typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype
+ typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame
+ typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype
+ typedef bWTF__StringView WTF__StringView; // WTF::StringView
+ typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope
+ typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl
+ typedef bJSC__VM JSC__VM; // JSC::VM
+ typedef JSClassRef JSClassRef;
+ typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject
+ typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction
+ typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype
+ typedef ZigException ZigException;
+ typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode
+ typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype
+ typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype
+ typedef ZigString ZigString;
+ typedef int64_t JSC__JSValue;
typedef struct JSC__FunctionPrototype JSC__FunctionPrototype; // JSC::FunctionPrototype
typedef bInspector__ScriptArguments Inspector__ScriptArguments; // Inspector::ScriptArguments
typedef bJSC__Exception JSC__Exception; // JSC::Exception
typedef bJSC__JSString JSC__JSString; // JSC::JSString
typedef struct JSC__ObjectPrototype JSC__ObjectPrototype; // JSC::ObjectPrototype
- typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame
- typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype
+ typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype
#endif
@@ -134,8 +137,8 @@ typedef void* JSClassRef;
namespace JSC {
class JSCell;
class Exception;
- class StringPrototype;
class JSPromisePrototype;
+ class StringPrototype;
class GeneratorFunctionPrototype;
class ArrayPrototype;
class JSString;
@@ -149,9 +152,9 @@ typedef void* JSClassRef;
class CatchScope;
class VM;
class BigIntPrototype;
- class SetIteratorPrototype;
- class ThrowScope;
class SourceOrigin;
+ class ThrowScope;
+ class SetIteratorPrototype;
class AsyncGeneratorPrototype;
class PropertyName;
class MapIteratorPrototype;
@@ -185,14 +188,17 @@ typedef void* JSClassRef;
typedef ErrorableResolvedSource ErrorableResolvedSource;
typedef ErrorableZigString ErrorableZigString;
+ typedef SystemError SystemError;
+ typedef Bun__Readable Bun__Readable;
+ typedef Bun__Writable Bun__Writable;
typedef JSClassRef JSClassRef;
typedef ZigException ZigException;
typedef ZigString ZigString;
typedef int64_t JSC__JSValue;
using JSC__JSCell = JSC::JSCell;
using JSC__Exception = JSC::Exception;
- using JSC__StringPrototype = JSC::StringPrototype;
using JSC__JSPromisePrototype = JSC::JSPromisePrototype;
+ using JSC__StringPrototype = JSC::StringPrototype;
using JSC__GeneratorFunctionPrototype = JSC::GeneratorFunctionPrototype;
using JSC__ArrayPrototype = JSC::ArrayPrototype;
using JSC__JSString = JSC::JSString;
@@ -206,9 +212,9 @@ typedef void* JSClassRef;
using JSC__CatchScope = JSC::CatchScope;
using JSC__VM = JSC::VM;
using JSC__BigIntPrototype = JSC::BigIntPrototype;
- using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype;
- using JSC__ThrowScope = JSC::ThrowScope;
using JSC__SourceOrigin = JSC::SourceOrigin;
+ using JSC__ThrowScope = JSC::ThrowScope;
+ using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype;
using JSC__AsyncGeneratorPrototype = JSC::AsyncGeneratorPrototype;
using JSC__PropertyName = JSC::PropertyName;
using JSC__MapIteratorPrototype = JSC::MapIteratorPrototype;
@@ -242,11 +248,12 @@ CPP_DECL JSC__JSValue JSC__JSObject__create(JSC__JSGlobalObject* arg0, size_t ar
CPP_DECL size_t JSC__JSObject__getArrayLength(JSC__JSObject* arg0);
CPP_DECL JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2);
CPP_DECL JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2);
-CPP_DECL void JSC__JSObject__putDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2, JSC__JSValue JSValue3);
CPP_DECL void JSC__JSObject__putRecord(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4);
+CPP_DECL JSC__JSValue ZigString__to16BitValue(const ZigString* arg0, JSC__JSGlobalObject* arg1);
CPP_DECL JSC__JSValue ZigString__toErrorInstance(const ZigString* arg0, JSC__JSGlobalObject* arg1);
CPP_DECL JSC__JSValue ZigString__toValue(const ZigString* arg0, JSC__JSGlobalObject* arg1);
CPP_DECL JSC__JSValue ZigString__toValueGC(const ZigString* arg0, JSC__JSGlobalObject* arg1);
+CPP_DECL JSC__JSValue SystemError__toErrorInstance(const SystemError* arg0, JSC__JSGlobalObject* arg1);
#pragma mark - JSC::JSCell
@@ -352,6 +359,7 @@ CPP_DECL JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObj
CPP_DECL JSC__JSObject* JSC__JSGlobalObject__datePrototype(JSC__JSGlobalObject* arg0);
CPP_DECL JSC__JSObject* JSC__JSGlobalObject__errorPrototype(JSC__JSGlobalObject* arg0);
CPP_DECL JSC__FunctionPrototype* JSC__JSGlobalObject__functionPrototype(JSC__JSGlobalObject* arg0);
+CPP_DECL JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject* arg0);
CPP_DECL JSC__GeneratorFunctionPrototype* JSC__JSGlobalObject__generatorFunctionPrototype(JSC__JSGlobalObject* arg0);
CPP_DECL JSC__GeneratorPrototype* JSC__JSGlobalObject__generatorPrototype(JSC__JSGlobalObject* arg0);
CPP_DECL JSC__IteratorPrototype* JSC__JSGlobalObject__iteratorPrototype(JSC__JSGlobalObject* arg0);
@@ -422,15 +430,22 @@ CPP_DECL double JSC__JSValue__asNumber(JSC__JSValue JSValue0);
CPP_DECL bJSC__JSObject JSC__JSValue__asObject(JSC__JSValue JSValue0);
CPP_DECL JSC__JSString* JSC__JSValue__asString(JSC__JSValue JSValue0);
CPP_DECL JSC__JSValue JSC__JSValue__createEmptyObject(JSC__JSGlobalObject* arg0, size_t arg1);
-CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2);
+CPP_DECL JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject* arg0, const ZigString* arg1, const ZigString* arg2, JSC__JSValue JSValue3, JSC__JSValue JSValue4);
+CPP_DECL JSC__JSValue JSC__JSValue__createRangeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2);
+CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2, bool arg3);
+CPP_DECL JSC__JSValue JSC__JSValue__createTypeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2);
CPP_DECL bool JSC__JSValue__eqlCell(JSC__JSValue JSValue0, JSC__JSCell* arg1);
CPP_DECL bool JSC__JSValue__eqlValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1);
CPP_DECL void JSC__JSValue__forEach(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, void (* ArgFn2)(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue JSValue2));
+CPP_DECL JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject* arg0, ZigString* arg1, ZigString* arg2, size_t arg3, bool arg4);
CPP_DECL void JSC__JSValue__getClassName(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2);
CPP_DECL JSC__JSValue JSC__JSValue__getErrorsProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1);
+CPP_DECL JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, uint32_t arg3);
CPP_DECL uint32_t JSC__JSValue__getLengthOfArray(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1);
CPP_DECL void JSC__JSValue__getNameProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2);
CPP_DECL JSC__JSValue JSC__JSValue__getPrototype(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1);
+CPP_DECL Bun__Readable* JSC__JSValue__getReadableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1);
+CPP_DECL Bun__Writable* JSC__JSValue__getWritableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1);
CPP_DECL bool JSC__JSValue__isAggregateError(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1);
CPP_DECL bool JSC__JSValue__isAnyInt(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isBigInt(JSC__JSValue JSValue0);
@@ -451,8 +466,10 @@ CPP_DECL bool JSC__JSValue__isNull(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isNumber(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isObject(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isPrimitive(JSC__JSValue JSValue0);
+CPP_DECL bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* arg2);
CPP_DECL bool JSC__JSValue__isString(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isSymbol(JSC__JSValue JSValue0);
+CPP_DECL bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM* arg1);
CPP_DECL bool JSC__JSValue__isUInt32AsAnyInt(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isUndefined(JSC__JSValue JSValue0);
CPP_DECL bool JSC__JSValue__isUndefinedOrNull(JSC__JSValue JSValue0);
@@ -465,7 +482,9 @@ CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt32(int32_t arg0);
CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt64(int64_t arg0);
CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromU16(uint16_t arg0);
CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0);
+CPP_DECL void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2, ZigString* arg3);
CPP_DECL JSC__JSValue JSC__JSValue__jsTDZValue();
+CPP_DECL unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0);
CPP_DECL JSC__JSValue JSC__JSValue__jsUndefined();
CPP_DECL void JSC__JSValue__putRecord(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4);
CPP_DECL bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0);
@@ -496,14 +515,18 @@ CPP_DECL JSC__JSValue JSC__Exception__value(JSC__Exception* arg0);
#pragma mark - JSC::VM
CPP_DECL JSC__JSLock* JSC__VM__apiLock(JSC__VM* arg0);
+CPP_DECL void JSC__VM__clearExecutionTimeLimit(JSC__VM* arg0);
CPP_DECL JSC__VM* JSC__VM__create(unsigned char HeapType0);
CPP_DECL void JSC__VM__deinit(JSC__VM* arg0, JSC__JSGlobalObject* arg1);
CPP_DECL void JSC__VM__deleteAllCode(JSC__VM* arg0, JSC__JSGlobalObject* arg1);
CPP_DECL void JSC__VM__drainMicrotasks(JSC__VM* arg0);
CPP_DECL bool JSC__VM__executionForbidden(JSC__VM* arg0);
+CPP_DECL void JSC__VM__holdAPILock(JSC__VM* arg0, void* arg1, void (* ArgFn2)(void* arg0));
CPP_DECL bool JSC__VM__isEntered(JSC__VM* arg0);
CPP_DECL bool JSC__VM__isJITEnabled();
+CPP_DECL JSC__JSValue JSC__VM__runGC(JSC__VM* arg0, bool arg1);
CPP_DECL void JSC__VM__setExecutionForbidden(JSC__VM* arg0, bool arg1);
+CPP_DECL void JSC__VM__setExecutionTimeLimit(JSC__VM* arg0, double arg1);
CPP_DECL void JSC__VM__shrinkFootprint(JSC__VM* arg0);
CPP_DECL bool JSC__VM__throwError(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__ThrowScope* arg2, const unsigned char* arg3, size_t arg4);
CPP_DECL void JSC__VM__whenIdle(JSC__VM* arg0, void (* ArgFn1)());
@@ -603,6 +626,54 @@ ZIG_DECL void Zig__GlobalObject__resolve(ErrorableZigString* arg0, JSC__JSGlobal
ZIG_DECL bool Zig__ErrorType__isPrivateData(void* arg0);
+#endif
+
+#pragma mark - Bun__Readable
+
+CPP_DECL JSC__JSValue Bun__Readable__create(Bun__Readable* arg0, JSC__JSGlobalObject* arg1);
+
+#ifdef __cplusplus
+
+ZIG_DECL void Bun__Readable__addEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4);
+ZIG_DECL void Bun__Readable__deinit(Bun__Readable* arg0);
+ZIG_DECL JSC__JSValue Bun__Readable__pause(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Readable__pipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL void Bun__Readable__prependEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4);
+ZIG_DECL JSC__JSValue Bun__Readable__read(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL bool Bun__Readable__removeEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3);
+ZIG_DECL JSC__JSValue Bun__Readable__resume(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Readable__unpipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Readable__unshift(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+
+#endif
+
+#pragma mark - Bun__Writable
+
+CPP_DECL JSC__JSValue Bun__Writable__create(Bun__Writable* arg0, JSC__JSGlobalObject* arg1);
+
+#ifdef __cplusplus
+
+ZIG_DECL void Bun__Writable__addEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4);
+ZIG_DECL JSC__JSValue Bun__Writable__close(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Writable__cork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL void Bun__Writable__deinit(Bun__Writable* arg0);
+ZIG_DECL JSC__JSValue Bun__Writable__destroy(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Writable__end(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL void Bun__Writable__prependEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4);
+ZIG_DECL bool Bun__Writable__removeEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3);
+ZIG_DECL JSC__JSValue Bun__Writable__uncork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+ZIG_DECL JSC__JSValue Bun__Writable__write(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3);
+
+#endif
+
+#ifdef __cplusplus
+
+ZIG_DECL JSC__JSValue Bun__Process__getArgv(JSC__JSGlobalObject* arg0);
+ZIG_DECL JSC__JSValue Bun__Process__getCwd(JSC__JSGlobalObject* arg0);
+ZIG_DECL void Bun__Process__getTitle(JSC__JSGlobalObject* arg0, ZigString* arg1);
+ZIG_DECL JSC__JSValue Bun__Process__setCwd(JSC__JSGlobalObject* arg0, ZigString* arg1);
+ZIG_DECL JSC__JSValue Bun__Process__setTitle(JSC__JSGlobalObject* arg0, ZigString* arg1);
+
#endif
CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0);
@@ -613,7 +684,7 @@ CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0);
ZIG_DECL void Zig__ConsoleClient__count(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3);
ZIG_DECL void Zig__ConsoleClient__countReset(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3);
-ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t arg1, uint32_t arg2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5);
+ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t MessageType1, uint32_t MessageLevel2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5);
ZIG_DECL void Zig__ConsoleClient__profile(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3);
ZIG_DECL void Zig__ConsoleClient__profileEnd(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3);
ZIG_DECL void Zig__ConsoleClient__record(void* arg0, JSC__JSGlobalObject* arg1, Inspector__ScriptArguments* arg2);
diff --git a/src/javascript/jsc/bindings/headers.zig b/src/javascript/jsc/bindings/headers.zig
index f5ab2f69a4..061fe3d172 100644
--- a/src/javascript/jsc/bindings/headers.zig
+++ b/src/javascript/jsc/bindings/headers.zig
@@ -53,7 +53,11 @@ pub const ZigStackTrace = bindings.ZigStackTrace;
pub const ReturnableException = bindings.ReturnableException;
pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask;
pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback;
+pub const SystemError = bindings.SystemError;
const JSClassRef = bindings.C.JSClassRef;
+pub const JSC__CatchScope = bindings.CatchScope;
+pub const Bun__Readable = bindings.NodeReadableStream;
+pub const Bun__Writable = bindings.NodeWritableStream;
// GENERATED CODE - DO NOT MODIFY BY HAND
pub const ptrdiff_t = c_long;
@@ -68,49 +72,31 @@ pub const __mbstate_t = extern union {
_mbstateL: c_longlong,
};
-pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype;
-
pub const JSC__GeneratorPrototype = struct_JSC__GeneratorPrototype;
pub const JSC__ArrayIteratorPrototype = struct_JSC__ArrayIteratorPrototype;
-pub const JSC__StringPrototype = struct_JSC__StringPrototype;
-pub const WTF__StringView = bWTF__StringView;
-
pub const JSC__JSPromisePrototype = struct_JSC__JSPromisePrototype;
-pub const JSC__CatchScope = bJSC__CatchScope;
-pub const JSC__ThrowScope = bJSC__ThrowScope;
pub const JSC__PropertyName = bJSC__PropertyName;
pub const JSC__JSObject = bJSC__JSObject;
pub const WTF__ExternalStringImpl = bWTF__ExternalStringImpl;
pub const JSC__AsyncIteratorPrototype = struct_JSC__AsyncIteratorPrototype;
-pub const WTF__StringImpl = bWTF__StringImpl;
pub const JSC__JSLock = bJSC__JSLock;
pub const JSC__JSModuleLoader = bJSC__JSModuleLoader;
-pub const JSC__VM = bJSC__VM;
pub const JSC__AsyncGeneratorPrototype = struct_JSC__AsyncGeneratorPrototype;
pub const JSC__AsyncGeneratorFunctionPrototype = struct_JSC__AsyncGeneratorFunctionPrototype;
-pub const JSC__JSGlobalObject = bJSC__JSGlobalObject;
-pub const JSC__JSFunction = bJSC__JSFunction;
+pub const JSC__Identifier = bJSC__Identifier;
pub const JSC__ArrayPrototype = struct_JSC__ArrayPrototype;
-pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype;
-pub const JSC__Identifier = bJSC__Identifier;
+pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback;
pub const JSC__JSPromise = bJSC__JSPromise;
pub const JSC__SetIteratorPrototype = struct_JSC__SetIteratorPrototype;
-pub const JSC__SourceCode = bJSC__SourceCode;
-
-pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback;
pub const JSC__JSCell = bJSC__JSCell;
-
-pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype;
-
-pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype;
pub const JSC__SourceOrigin = bJSC__SourceOrigin;
pub const JSC__JSModuleRecord = bJSC__JSModuleRecord;
pub const WTF__String = bWTF__String;
@@ -119,24 +105,42 @@ pub const WTF__URL = bWTF__URL;
pub const JSC__IteratorPrototype = struct_JSC__IteratorPrototype;
pub const JSC__JSInternalPromise = bJSC__JSInternalPromise;
+pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype;
+pub const JSC__CallFrame = bJSC__CallFrame;
+
+pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype;
+pub const WTF__StringView = bWTF__StringView;
+pub const JSC__ThrowScope = bJSC__ThrowScope;
+pub const WTF__StringImpl = bWTF__StringImpl;
+pub const JSC__VM = bJSC__VM;
+pub const JSC__JSGlobalObject = bJSC__JSGlobalObject;
+pub const JSC__JSFunction = bJSC__JSFunction;
+
+pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype;
+pub const JSC__SourceCode = bJSC__SourceCode;
+
+pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype;
+
+pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype;
+
pub const JSC__FunctionPrototype = struct_JSC__FunctionPrototype;
pub const Inspector__ScriptArguments = bInspector__ScriptArguments;
pub const JSC__Exception = bJSC__Exception;
pub const JSC__JSString = bJSC__JSString;
pub const JSC__ObjectPrototype = struct_JSC__ObjectPrototype;
-pub const JSC__CallFrame = bJSC__CallFrame;
-pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype;
+pub const JSC__StringPrototype = struct_JSC__StringPrototype;
pub extern fn JSC__JSObject__create(arg0: [*c]JSC__JSGlobalObject, arg1: usize, arg2: ?*anyopaque, ArgFn3: ?fn (?*anyopaque, [*c]JSC__JSObject, [*c]JSC__JSGlobalObject) callconv(.C) void) JSC__JSValue;
pub extern fn JSC__JSObject__getArrayLength(arg0: [*c]JSC__JSObject) usize;
pub extern fn JSC__JSObject__getDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString) JSC__JSValue;
pub extern fn JSC__JSObject__getIndex(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32) JSC__JSValue;
-pub extern fn JSC__JSObject__putDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString, JSValue3: JSC__JSValue) void;
pub extern fn JSC__JSObject__putRecord(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void;
+pub extern fn ZigString__to16BitValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn ZigString__toErrorInstance(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn ZigString__toValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn ZigString__toValueGC(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
+pub extern fn SystemError__toErrorInstance(arg0: [*c]const SystemError, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn JSC__JSCell__getObject(arg0: [*c]JSC__JSCell) [*c]JSC__JSObject;
pub extern fn JSC__JSCell__getString(arg0: [*c]JSC__JSCell, arg1: [*c]JSC__JSGlobalObject) bWTF__String;
pub extern fn JSC__JSCell__getType(arg0: [*c]JSC__JSCell) u8;
@@ -209,6 +213,7 @@ pub extern fn JSC__JSGlobalObject__createAggregateError(arg0: [*c]JSC__JSGlobalO
pub extern fn JSC__JSGlobalObject__datePrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject;
pub extern fn JSC__JSGlobalObject__errorPrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject;
pub extern fn JSC__JSGlobalObject__functionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__FunctionPrototype;
+pub extern fn JSC__JSGlobalObject__generateHeapSnapshot(arg0: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn JSC__JSGlobalObject__generatorFunctionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorFunctionPrototype;
pub extern fn JSC__JSGlobalObject__generatorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorPrototype;
pub extern fn JSC__JSGlobalObject__iteratorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__IteratorPrototype;
@@ -270,15 +275,22 @@ pub extern fn JSC__JSValue__asNumber(JSValue0: JSC__JSValue) f64;
pub extern fn JSC__JSValue__asObject(JSValue0: JSC__JSValue) bJSC__JSObject;
pub extern fn JSC__JSValue__asString(JSValue0: JSC__JSValue) [*c]JSC__JSString;
pub extern fn JSC__JSValue__createEmptyObject(arg0: [*c]JSC__JSGlobalObject, arg1: usize) JSC__JSValue;
-pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize) JSC__JSValue;
+pub extern fn JSC__JSValue__createObject2(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]const ZigString, arg2: [*c]const ZigString, JSValue3: JSC__JSValue, JSValue4: JSC__JSValue) JSC__JSValue;
+pub extern fn JSC__JSValue__createRangeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue;
+pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize, arg3: bool) JSC__JSValue;
+pub extern fn JSC__JSValue__createTypeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn JSC__JSValue__eqlCell(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSCell) bool;
pub extern fn JSC__JSValue__eqlValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue) bool;
pub extern fn JSC__JSValue__forEach(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, ArgFn2: ?fn ([*c]JSC__VM, [*c]JSC__JSGlobalObject, JSC__JSValue) callconv(.C) void) void;
+pub extern fn JSC__JSValue__fromEntries(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: [*c]ZigString, arg3: usize, arg4: bool) JSC__JSValue;
pub extern fn JSC__JSValue__getClassName(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void;
pub extern fn JSC__JSValue__getErrorsProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
+pub extern fn JSC__JSValue__getIfPropertyExistsImpl(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const u8, arg3: u32) JSC__JSValue;
pub extern fn JSC__JSValue__getLengthOfArray(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) u32;
pub extern fn JSC__JSValue__getNameProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void;
pub extern fn JSC__JSValue__getPrototype(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
+pub extern fn JSC__JSValue__getReadableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Readable;
+pub extern fn JSC__JSValue__getWritableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Writable;
pub extern fn JSC__JSValue__isAggregateError(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) bool;
pub extern fn JSC__JSValue__isAnyInt(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isBigInt(JSValue0: JSC__JSValue) bool;
@@ -299,8 +311,10 @@ pub extern fn JSC__JSValue__isNull(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isNumber(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isObject(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isPrimitive(JSValue0: JSC__JSValue) bool;
+pub extern fn JSC__JSValue__isSameValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue, arg2: [*c]JSC__JSGlobalObject) bool;
pub extern fn JSC__JSValue__isString(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isSymbol(JSValue0: JSC__JSValue) bool;
+pub extern fn JSC__JSValue__isTerminationException(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) bool;
pub extern fn JSC__JSValue__isUInt32AsAnyInt(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isUndefined(JSValue0: JSC__JSValue) bool;
pub extern fn JSC__JSValue__isUndefinedOrNull(JSValue0: JSC__JSValue) bool;
@@ -313,7 +327,9 @@ pub extern fn JSC__JSValue__jsNumberFromInt32(arg0: i32) JSC__JSValue;
pub extern fn JSC__JSValue__jsNumberFromInt64(arg0: i64) JSC__JSValue;
pub extern fn JSC__JSValue__jsNumberFromU16(arg0: u16) JSC__JSValue;
pub extern fn JSC__JSValue__jsNumberFromUint64(arg0: u64) JSC__JSValue;
+pub extern fn JSC__JSValue__jsonStringify(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32, arg3: [*c]ZigString) void;
pub extern fn JSC__JSValue__jsTDZValue(...) JSC__JSValue;
+pub extern fn JSC__JSValue__jsType(JSValue0: JSC__JSValue) u8;
pub extern fn JSC__JSValue__jsUndefined(...) JSC__JSValue;
pub extern fn JSC__JSValue__putRecord(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void;
pub extern fn JSC__JSValue__toBoolean(JSValue0: JSC__JSValue) bool;
@@ -334,14 +350,18 @@ pub extern fn JSC__Exception__create(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]JS
pub extern fn JSC__Exception__getStackTrace(arg0: [*c]JSC__Exception, arg1: [*c]ZigStackTrace) void;
pub extern fn JSC__Exception__value(arg0: [*c]JSC__Exception) JSC__JSValue;
pub extern fn JSC__VM__apiLock(arg0: [*c]JSC__VM) [*c]JSC__JSLock;
+pub extern fn JSC__VM__clearExecutionTimeLimit(arg0: [*c]JSC__VM) void;
pub extern fn JSC__VM__create(HeapType0: u8) [*c]JSC__VM;
pub extern fn JSC__VM__deinit(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void;
pub extern fn JSC__VM__deleteAllCode(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void;
pub extern fn JSC__VM__drainMicrotasks(arg0: [*c]JSC__VM) void;
pub extern fn JSC__VM__executionForbidden(arg0: [*c]JSC__VM) bool;
+pub extern fn JSC__VM__holdAPILock(arg0: [*c]JSC__VM, arg1: ?*anyopaque, ArgFn2: ?fn (?*anyopaque) callconv(.C) void) void;
pub extern fn JSC__VM__isEntered(arg0: [*c]JSC__VM) bool;
pub extern fn JSC__VM__isJITEnabled(...) bool;
+pub extern fn JSC__VM__runGC(arg0: [*c]JSC__VM, arg1: bool) JSC__JSValue;
pub extern fn JSC__VM__setExecutionForbidden(arg0: [*c]JSC__VM, arg1: bool) void;
+pub extern fn JSC__VM__setExecutionTimeLimit(arg0: [*c]JSC__VM, arg1: f64) void;
pub extern fn JSC__VM__shrinkFootprint(arg0: [*c]JSC__VM) void;
pub extern fn JSC__VM__throwError(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]JSC__ThrowScope, arg3: [*c]const u8, arg4: usize) bool;
pub extern fn JSC__VM__whenIdle(arg0: [*c]JSC__VM, ArgFn1: ?fn (...) callconv(.C) void) void;
@@ -399,4 +419,6 @@ pub extern fn WTF__StringView__length(arg0: [*c]const WTF__StringView) usize;
pub extern fn Zig__GlobalObject__create(arg0: [*c]JSClassRef, arg1: i32, arg2: ?*anyopaque) [*c]JSC__JSGlobalObject;
pub extern fn Zig__GlobalObject__getModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject) ?*anyopaque;
pub extern fn Zig__GlobalObject__resetModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject, arg1: ?*anyopaque) bool;
+pub extern fn Bun__Readable__create(arg0: [*c]Bun__Readable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
+pub extern fn Bun__Writable__create(arg0: [*c]Bun__Writable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue;
pub extern fn ZigException__fromException(arg0: [*c]JSC__Exception) ZigException;
diff --git a/src/javascript/jsc/bindings/helpers.h b/src/javascript/jsc/bindings/helpers.h
index 73582d1dc1..1c12379694 100644
--- a/src/javascript/jsc/bindings/helpers.h
+++ b/src/javascript/jsc/bindings/helpers.h
@@ -1,3 +1,5 @@
+#pragma once
+
#include "headers.h"
#include "root.h"
@@ -10,8 +12,6 @@
#include
#include
-#pragma once
-
template class Wrap {
public:
Wrap(){};
@@ -72,46 +72,90 @@ static const JSC::Identifier toIdentifier(ZigString str, JSC::JSGlobalObject *gl
return JSC::Identifier::fromString(global->vm(), str.ptr, str.len);
}
+static bool isTaggedUTF16Ptr(const unsigned char *ptr) {
+ return (reinterpret_cast(ptr) & (static_cast(1) << 63)) != 0;
+}
+
+static bool isTaggedExternalPtr(const unsigned char *ptr) {
+ return (reinterpret_cast(ptr) & (static_cast(1) << 62)) != 0;
+}
+
static const WTF::String toString(ZigString str) {
if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); }
- return WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len));
+ return !isTaggedUTF16Ptr(str.ptr)
+ ? WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len))
+ : WTF::String(WTF::StringImpl::createWithoutCopying(
+ reinterpret_cast