mirror of
https://github.com/oven-sh/bun
synced 2026-03-01 13:01:06 +01:00
Compare commits
88 Commits
ali-extens
...
don/test/m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33fdc12fbe | ||
|
|
0bc57eebcb | ||
|
|
455de2a449 | ||
|
|
81bc01d477 | ||
|
|
d21444a681 | ||
|
|
2d5ea4993f | ||
|
|
b39632c921 | ||
|
|
38325aa41c | ||
|
|
969bab3848 | ||
|
|
5bd4972d5b | ||
|
|
68780faee2 | ||
|
|
0bbc18fd19 | ||
|
|
53318c8b13 | ||
|
|
abe69901b2 | ||
|
|
c0cf0414a0 | ||
|
|
3dc3527171 | ||
|
|
af4f1c7d39 | ||
|
|
2c1dea818c | ||
|
|
cc125b475f | ||
|
|
cbbf88f3a6 | ||
|
|
8064a55a48 | ||
|
|
0531d6756c | ||
|
|
6135b3dec9 | ||
|
|
b08dd8795e | ||
|
|
c1eba5886f | ||
|
|
fcca2cc398 | ||
|
|
dd32e6b416 | ||
|
|
b453360dff | ||
|
|
1476e4c958 | ||
|
|
eacf89e5bf | ||
|
|
fa6ac405a4 | ||
|
|
4c8cbecb08 | ||
|
|
00b7d6479b | ||
|
|
bcf023c829 | ||
|
|
b7b1ca8ebe | ||
|
|
784bc4e012 | ||
|
|
dd5c40dab7 | ||
|
|
3a4a9ae4e9 | ||
|
|
9d1a35b658 | ||
|
|
61cc9c3947 | ||
|
|
e904a181d8 | ||
|
|
55a0bdc68d | ||
|
|
55454f7910 | ||
|
|
e4aeb761e4 | ||
|
|
f9efe94b85 | ||
|
|
7eb8a3feae | ||
|
|
d7ed9c673e | ||
|
|
b4dce96c40 | ||
|
|
52ef8b1778 | ||
|
|
baff3c900e | ||
|
|
23299dadf6 | ||
|
|
0d5e4e162b | ||
|
|
d27594ecf4 | ||
|
|
a2e2d114e9 | ||
|
|
da3d64b1ef | ||
|
|
ce64e04b16 | ||
|
|
55473cb64a | ||
|
|
752441d911 | ||
|
|
da5d4d791c | ||
|
|
6d453be7d9 | ||
|
|
2d441d868b | ||
|
|
56ad4cc4a6 | ||
|
|
d2acb2eac0 | ||
|
|
de7eafbdd1 | ||
|
|
4114986c3e | ||
|
|
8aa451c2dc | ||
|
|
497cef9759 | ||
|
|
dd57b95546 | ||
|
|
ea7c4986d7 | ||
|
|
6c7edf2dbe | ||
|
|
bf2f153f5c | ||
|
|
f64a4c4ace | ||
|
|
0216431c98 | ||
|
|
ae289c4858 | ||
|
|
5d1609fe5c | ||
|
|
471fe7b886 | ||
|
|
08222eda71 | ||
|
|
6f8c5959d0 | ||
|
|
40d5e745c9 | ||
|
|
225bfd54fa | ||
|
|
a6ca8c40d4 | ||
|
|
b52ad226a5 | ||
|
|
5f8f805db9 | ||
|
|
37c98bebd6 | ||
|
|
bd01df19c1 | ||
|
|
7fd16ebffa | ||
|
|
1bb211df56 | ||
|
|
bdd0b89f16 |
1742
.buildkite/ci.mjs
1742
.buildkite/ci.mjs
File diff suppressed because it is too large
Load Diff
@@ -8,4 +8,4 @@ function run_command() {
|
||||
{ set +x; } 2>/dev/null
|
||||
}
|
||||
|
||||
run_command node ".buildkite/ci.mjs"
|
||||
run_command node ".buildkite/ci.mjs" "$@"
|
||||
|
||||
79
.github/workflows/update-cares.yml
vendored
79
.github/workflows/update-cares.yml
vendored
@@ -2,7 +2,7 @@ name: Update c-ares
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
- cron: "0 4 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -18,44 +18,75 @@ jobs:
|
||||
- name: Check c-ares version
|
||||
id: check-version
|
||||
run: |
|
||||
CURRENT_VERSION=$(grep -oP 'CARES_VERSION\s+\K\S+' cmake/targets/BuildCares.cmake)
|
||||
set -euo pipefail
|
||||
|
||||
# Extract the commit hash from the line after COMMIT
|
||||
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildCares.cmake)
|
||||
|
||||
if [ -z "$CURRENT_VERSION" ]; then
|
||||
echo "Error: Could not find current version in BuildCares.cmake"
|
||||
echo "Error: Could not find COMMIT line in BuildCares.cmake"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate that it looks like a git hash
|
||||
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid git hash format in BuildCares.cmake"
|
||||
echo "Found: $CURRENT_VERSION"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/c-ares/c-ares/releases/latest)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "Error: Failed to fetch latest release from GitHub API"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
|
||||
echo "Error: Could not extract tag name from GitHub API response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_SHA=$(curl -sL "https://api.github.com/repos/c-ares/c-ares/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
|
||||
if [ -z "$LATEST_SHA" ]; then
|
||||
echo "Error: Could not fetch latest version from GitHub API"
|
||||
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
|
||||
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#LATEST_SHA} -ne 40 ]; then
|
||||
echo "Error: Invalid SHA length"
|
||||
|
||||
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid SHA format received from GitHub"
|
||||
echo "Found: $LATEST_SHA"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
|
||||
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create PR if update needed
|
||||
- name: Update version if needed
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BRANCH="update-cares-${GITHUB_SHA::8}"
|
||||
git checkout -b "$BRANCH"
|
||||
set -euo pipefail
|
||||
# Handle multi-line format where COMMIT and its value are on separate lines
|
||||
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildCares.cmake
|
||||
|
||||
sed -i "s/CARES_VERSION\s\+[0-9a-f]\+/CARES_VERSION ${{ steps.check-version.outputs.latest }}/" cmake/targets/BuildCares.cmake
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add cmake/targets/BuildCares.cmake
|
||||
git commit -m "deps: update c-ares to ${{ steps.check-version.outputs.latest }}"
|
||||
git push origin "$BRANCH"
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
cmake/targets/BuildCares.cmake
|
||||
commit-message: "deps: update c-ares to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
|
||||
title: "deps: update c-ares to ${{ steps.check-version.outputs.tag }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-cares-${{ github.run_number }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
gh pr create \
|
||||
--title "deps: update c-ares to ${LATEST_SHA::8}" \
|
||||
--body "Updates c-ares from ${CURRENT_VERSION::8} to ${LATEST_SHA::8}" \
|
||||
--base main \
|
||||
--head "$BRANCH"
|
||||
Updates c-ares to version ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-cares.yml)
|
||||
|
||||
79
.github/workflows/update-libarchive.yml
vendored
79
.github/workflows/update-libarchive.yml
vendored
@@ -2,7 +2,7 @@ name: Update libarchive
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
- cron: "0 3 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -18,44 +18,75 @@ jobs:
|
||||
- name: Check libarchive version
|
||||
id: check-version
|
||||
run: |
|
||||
CURRENT_VERSION=$(grep -oP 'LIBARCHIVE_VERSION\s+\K\S+' cmake/targets/BuildLibArchive.cmake)
|
||||
set -euo pipefail
|
||||
|
||||
# Extract the commit hash from the line after COMMIT
|
||||
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLibArchive.cmake)
|
||||
|
||||
if [ -z "$CURRENT_VERSION" ]; then
|
||||
echo "Error: Could not find current version in BuildLibArchive.cmake"
|
||||
echo "Error: Could not find COMMIT line in BuildLibArchive.cmake"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate that it looks like a git hash
|
||||
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid git hash format in BuildLibArchive.cmake"
|
||||
echo "Found: $CURRENT_VERSION"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/libarchive/libarchive/releases/latest)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "Error: Failed to fetch latest release from GitHub API"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
|
||||
echo "Error: Could not extract tag name from GitHub API response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_SHA=$(curl -sL "https://api.github.com/repos/libarchive/libarchive/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
|
||||
if [ -z "$LATEST_SHA" ]; then
|
||||
echo "Error: Could not fetch latest version from GitHub API"
|
||||
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
|
||||
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#LATEST_SHA} -ne 40 ]; then
|
||||
echo "Error: Invalid SHA length"
|
||||
|
||||
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid SHA format received from GitHub"
|
||||
echo "Found: $LATEST_SHA"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
|
||||
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create PR if update needed
|
||||
- name: Update version if needed
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BRANCH="update-libarchive-${GITHUB_SHA::8}"
|
||||
git checkout -b "$BRANCH"
|
||||
set -euo pipefail
|
||||
# Handle multi-line format where COMMIT and its value are on separate lines
|
||||
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLibArchive.cmake
|
||||
|
||||
sed -i "s/LIBARCHIVE_VERSION\s\+[0-9a-f]\+/LIBARCHIVE_VERSION ${{ steps.check-version.outputs.latest }}/" cmake/targets/BuildLibArchive.cmake
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add cmake/targets/BuildLibArchive.cmake
|
||||
git commit -m "deps: update libarchive to ${{ steps.check-version.outputs.latest }}"
|
||||
git push origin "$BRANCH"
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
cmake/targets/BuildLibArchive.cmake
|
||||
commit-message: "deps: update libarchive to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
|
||||
title: "deps: update libarchive to ${{ steps.check-version.outputs.tag }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-libarchive-${{ github.run_number }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
gh pr create \
|
||||
--title "deps: update libarchive to ${LATEST_SHA::8}" \
|
||||
--body "Updates libarchive from ${CURRENT_VERSION::8} to ${LATEST_SHA::8}" \
|
||||
--base main \
|
||||
--head "$BRANCH"
|
||||
Updates libarchive to version ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-libarchive.yml)
|
||||
|
||||
79
.github/workflows/update-libdeflate.yml
vendored
79
.github/workflows/update-libdeflate.yml
vendored
@@ -2,7 +2,7 @@ name: Update libdeflate
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
- cron: "0 2 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -18,44 +18,75 @@ jobs:
|
||||
- name: Check libdeflate version
|
||||
id: check-version
|
||||
run: |
|
||||
CURRENT_VERSION=$(grep -oP 'LIBDEFLATE_VERSION\s+\K\S+' cmake/targets/BuildLibDeflate.cmake)
|
||||
set -euo pipefail
|
||||
|
||||
# Extract the commit hash from the line after COMMIT
|
||||
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLibDeflate.cmake)
|
||||
|
||||
if [ -z "$CURRENT_VERSION" ]; then
|
||||
echo "Error: Could not find current version in BuildLibDeflate.cmake"
|
||||
echo "Error: Could not find COMMIT line in BuildLibDeflate.cmake"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate that it looks like a git hash
|
||||
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid git hash format in BuildLibDeflate.cmake"
|
||||
echo "Found: $CURRENT_VERSION"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/ebiggers/libdeflate/releases/latest)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "Error: Failed to fetch latest release from GitHub API"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
|
||||
echo "Error: Could not extract tag name from GitHub API response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_SHA=$(curl -sL "https://api.github.com/repos/ebiggers/libdeflate/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
|
||||
if [ -z "$LATEST_SHA" ]; then
|
||||
echo "Error: Could not fetch latest version from GitHub API"
|
||||
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
|
||||
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#LATEST_SHA} -ne 40 ]; then
|
||||
echo "Error: Invalid SHA length"
|
||||
|
||||
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid SHA format received from GitHub"
|
||||
echo "Found: $LATEST_SHA"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
|
||||
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create PR if update needed
|
||||
- name: Update version if needed
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BRANCH="update-libdeflate-${GITHUB_SHA::8}"
|
||||
git checkout -b "$BRANCH"
|
||||
set -euo pipefail
|
||||
# Handle multi-line format where COMMIT and its value are on separate lines
|
||||
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLibDeflate.cmake
|
||||
|
||||
sed -i "s/LIBDEFLATE_VERSION\s\+[0-9a-f]\+/LIBDEFLATE_VERSION ${{ steps.check-version.outputs.latest }}/" cmake/targets/BuildLibDeflate.cmake
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add cmake/targets/BuildLibDeflate.cmake
|
||||
git commit -m "deps: update libdeflate to ${{ steps.check-version.outputs.latest }}"
|
||||
git push origin "$BRANCH"
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
cmake/targets/BuildLibDeflate.cmake
|
||||
commit-message: "deps: update libdeflate to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
|
||||
title: "deps: update libdeflate to ${{ steps.check-version.outputs.tag }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-libdeflate-${{ github.run_number }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
gh pr create \
|
||||
--title "deps: update libdeflate to ${LATEST_SHA::8}" \
|
||||
--body "Updates libdeflate from ${CURRENT_VERSION::8} to ${LATEST_SHA::8}" \
|
||||
--base main \
|
||||
--head "$BRANCH"
|
||||
Updates libdeflate to version ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-libdeflate.yml)
|
||||
|
||||
79
.github/workflows/update-lolhtml.yml
vendored
79
.github/workflows/update-lolhtml.yml
vendored
@@ -2,7 +2,7 @@ name: Update lolhtml
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
- cron: "0 1 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -18,44 +18,75 @@ jobs:
|
||||
- name: Check lolhtml version
|
||||
id: check-version
|
||||
run: |
|
||||
CURRENT_VERSION=$(grep -oP 'LOLHTML_VERSION\s+\K\S+' cmake/targets/BuildLolHtml.cmake)
|
||||
set -euo pipefail
|
||||
|
||||
# Extract the commit hash from the line after COMMIT
|
||||
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLolHtml.cmake)
|
||||
|
||||
if [ -z "$CURRENT_VERSION" ]; then
|
||||
echo "Error: Could not find current version in BuildLolHtml.cmake"
|
||||
echo "Error: Could not find COMMIT line in BuildLolHtml.cmake"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate that it looks like a git hash
|
||||
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid git hash format in BuildLolHtml.cmake"
|
||||
echo "Found: $CURRENT_VERSION"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/cloudflare/lol-html/releases/latest)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "Error: Failed to fetch latest release from GitHub API"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
|
||||
echo "Error: Could not extract tag name from GitHub API response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_SHA=$(curl -sL "https://api.github.com/repos/cloudflare/lol-html/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
|
||||
if [ -z "$LATEST_SHA" ]; then
|
||||
echo "Error: Could not fetch latest version from GitHub API"
|
||||
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
|
||||
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#LATEST_SHA} -ne 40 ]; then
|
||||
echo "Error: Invalid SHA length"
|
||||
|
||||
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid SHA format received from GitHub"
|
||||
echo "Found: $LATEST_SHA"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
|
||||
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create PR if update needed
|
||||
- name: Update version if needed
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BRANCH="update-lolhtml-${GITHUB_SHA::8}"
|
||||
git checkout -b "$BRANCH"
|
||||
set -euo pipefail
|
||||
# Handle multi-line format where COMMIT and its value are on separate lines
|
||||
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLolHtml.cmake
|
||||
|
||||
sed -i "s/LOLHTML_VERSION\s\+[0-9a-f]\+/LOLHTML_VERSION ${{ steps.check-version.outputs.latest }}/" cmake/targets/BuildLolHtml.cmake
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add cmake/targets/BuildLolHtml.cmake
|
||||
git commit -m "deps: update lolhtml to ${{ steps.check-version.outputs.latest }}"
|
||||
git push origin "$BRANCH"
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
cmake/targets/BuildLolHtml.cmake
|
||||
commit-message: "deps: update lolhtml to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
|
||||
title: "deps: update lolhtml to ${{ steps.check-version.outputs.tag }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-lolhtml-${{ github.run_number }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
gh pr create \
|
||||
--title "deps: update lolhtml to ${LATEST_SHA::8}" \
|
||||
--body "Updates lolhtml from ${CURRENT_VERSION::8} to ${LATEST_SHA::8}" \
|
||||
--base main \
|
||||
--head "$BRANCH"
|
||||
Updates lolhtml to version ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-lolhtml.yml)
|
||||
|
||||
79
.github/workflows/update-lshpack.yml
vendored
79
.github/workflows/update-lshpack.yml
vendored
@@ -2,7 +2,7 @@ name: Update lshpack
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * 0"
|
||||
- cron: "0 5 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -18,44 +18,75 @@ jobs:
|
||||
- name: Check lshpack version
|
||||
id: check-version
|
||||
run: |
|
||||
CURRENT_VERSION=$(grep -oP 'LSHPACK_VERSION\s+\K\S+' cmake/targets/BuildLshpack.cmake)
|
||||
set -euo pipefail
|
||||
|
||||
# Extract the commit hash from the line after COMMIT
|
||||
CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLshpack.cmake)
|
||||
|
||||
if [ -z "$CURRENT_VERSION" ]; then
|
||||
echo "Error: Could not find current version in BuildLshpack.cmake"
|
||||
echo "Error: Could not find COMMIT line in BuildLshpack.cmake"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Validate that it looks like a git hash
|
||||
if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid git hash format in BuildLshpack.cmake"
|
||||
echo "Found: $CURRENT_VERSION"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
LATEST_RELEASE=$(curl -sL https://api.github.com/repos/litespeedtech/ls-hpack/releases/latest)
|
||||
if [ -z "$LATEST_RELEASE" ]; then
|
||||
echo "Error: Failed to fetch latest release from GitHub API"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||
if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
|
||||
echo "Error: Could not extract tag name from GitHub API response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LATEST_SHA=$(curl -sL "https://api.github.com/repos/litespeedtech/ls-hpack/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
|
||||
if [ -z "$LATEST_SHA" ]; then
|
||||
echo "Error: Could not fetch latest version from GitHub API"
|
||||
if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
|
||||
echo "Error: Could not fetch SHA for tag $LATEST_TAG"
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#LATEST_SHA} -ne 40 ]; then
|
||||
echo "Error: Invalid SHA length"
|
||||
|
||||
if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
|
||||
echo "Error: Invalid SHA format received from GitHub"
|
||||
echo "Found: $LATEST_SHA"
|
||||
echo "Expected: 40 character hexadecimal string"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
|
||||
echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create PR if update needed
|
||||
- name: Update version if needed
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BRANCH="update-lshpack-${GITHUB_SHA::8}"
|
||||
git checkout -b "$BRANCH"
|
||||
set -euo pipefail
|
||||
# Handle multi-line format where COMMIT and its value are on separate lines
|
||||
sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLshpack.cmake
|
||||
|
||||
sed -i "s/LSHPACK_VERSION\s\+[0-9a-f]\+/LSHPACK_VERSION ${{ steps.check-version.outputs.latest }}/" cmake/targets/BuildLshpack.cmake
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add cmake/targets/BuildLshpack.cmake
|
||||
git commit -m "deps: update lshpack to ${{ steps.check-version.outputs.latest }}"
|
||||
git push origin "$BRANCH"
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
cmake/targets/BuildLshpack.cmake
|
||||
commit-message: "deps: update lshpack to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
|
||||
title: "deps: update lshpack to ${{ steps.check-version.outputs.tag }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-lshpack-${{ github.run_number }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
gh pr create \
|
||||
--title "deps: update lshpack to ${LATEST_SHA::8}" \
|
||||
--body "Updates lshpack from ${CURRENT_VERSION::8} to ${LATEST_SHA::8}" \
|
||||
--base main \
|
||||
--head "$BRANCH"
|
||||
Updates lshpack to version ${{ steps.check-version.outputs.tag }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-lshpack.yml)
|
||||
|
||||
109
.github/workflows/update-sqlite3.yml
vendored
Normal file
109
.github/workflows/update-sqlite3.yml
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
name: Update SQLite3
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 6 * * 0" # Run weekly
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
check-update:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Check SQLite version
|
||||
id: check-version
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Get current version from the header file using SQLITE_VERSION_NUMBER
|
||||
CURRENT_VERSION_NUM=$(grep -o '#define SQLITE_VERSION_NUMBER [0-9]\+' src/bun.js/bindings/sqlite/sqlite3_local.h | awk '{print $3}' | tr -d '\n\r')
|
||||
if [ -z "$CURRENT_VERSION_NUM" ]; then
|
||||
echo "Error: Could not find SQLITE_VERSION_NUMBER in sqlite3_local.h"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Convert numeric version to semantic version for display
|
||||
CURRENT_MAJOR=$((CURRENT_VERSION_NUM / 1000000))
|
||||
CURRENT_MINOR=$((($CURRENT_VERSION_NUM / 1000) % 1000))
|
||||
CURRENT_PATCH=$((CURRENT_VERSION_NUM % 1000))
|
||||
CURRENT_VERSION="$CURRENT_MAJOR.$CURRENT_MINOR.$CURRENT_PATCH"
|
||||
|
||||
echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "current_num=$CURRENT_VERSION_NUM" >> $GITHUB_OUTPUT
|
||||
|
||||
# Fetch SQLite download page
|
||||
DOWNLOAD_PAGE=$(curl -sL https://sqlite.org/download.html)
|
||||
if [ -z "$DOWNLOAD_PAGE" ]; then
|
||||
echo "Error: Failed to fetch SQLite download page"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract latest version and year from the amalgamation link
|
||||
LATEST_INFO=$(echo "$DOWNLOAD_PAGE" | grep -o 'sqlite-amalgamation-[0-9]\{7\}.zip' | head -n1)
|
||||
LATEST_YEAR=$(echo "$DOWNLOAD_PAGE" | grep -o '[0-9]\{4\}/sqlite-amalgamation-[0-9]\{7\}.zip' | head -n1 | cut -d'/' -f1 | tr -d '\n\r')
|
||||
LATEST_VERSION_NUM=$(echo "$LATEST_INFO" | grep -o '[0-9]\{7\}' | tr -d '\n\r')
|
||||
|
||||
if [ -z "$LATEST_VERSION_NUM" ] || [ -z "$LATEST_YEAR" ]; then
|
||||
echo "Error: Could not extract latest version info"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Convert numeric version to semantic version for display
|
||||
LATEST_MAJOR=$((10#$LATEST_VERSION_NUM / 1000000))
|
||||
LATEST_MINOR=$((($LATEST_VERSION_NUM / 1000) % 1000))
|
||||
LATEST_PATCH=$((10#$LATEST_VERSION_NUM % 1000))
|
||||
LATEST_VERSION="$LATEST_MAJOR.$LATEST_MINOR.$LATEST_PATCH"
|
||||
|
||||
echo "latest=$LATEST_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "latest_year=$LATEST_YEAR" >> $GITHUB_OUTPUT
|
||||
echo "latest_num=$LATEST_VERSION_NUM" >> $GITHUB_OUTPUT
|
||||
|
||||
# Debug output
|
||||
echo "Current version: $CURRENT_VERSION ($CURRENT_VERSION_NUM)"
|
||||
echo "Latest version: $LATEST_VERSION ($LATEST_VERSION_NUM)"
|
||||
|
||||
- name: Update SQLite if needed
|
||||
if: success() && steps.check-version.outputs.current_num < steps.check-version.outputs.latest_num
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
cd $TEMP_DIR
|
||||
|
||||
echo "Downloading from: https://sqlite.org/${{ steps.check-version.outputs.latest_year }}/sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
|
||||
|
||||
# Download and extract latest version
|
||||
wget "https://sqlite.org/${{ steps.check-version.outputs.latest_year }}/sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
|
||||
unzip "sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
|
||||
cd "sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}"
|
||||
|
||||
# Add header comment and copy files
|
||||
echo "// clang-format off" > $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3.c
|
||||
cat sqlite3.c >> $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3.c
|
||||
|
||||
echo "// clang-format off" > $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3_local.h
|
||||
cat sqlite3.h >> $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3_local.h
|
||||
|
||||
- name: Create Pull Request
|
||||
if: success() && steps.check-version.outputs.current_num < steps.check-version.outputs.latest_num
|
||||
uses: peter-evans/create-pull-request@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
add-paths: |
|
||||
src/bun.js/bindings/sqlite/sqlite3.c
|
||||
src/bun.js/bindings/sqlite/sqlite3_local.h
|
||||
commit-message: "deps: update sqlite to ${{ steps.check-version.outputs.latest }}"
|
||||
title: "deps: update sqlite to ${{ steps.check-version.outputs.latest }}"
|
||||
delete-branch: true
|
||||
branch: deps/update-sqlite-${{ steps.check-version.outputs.latest }}
|
||||
body: |
|
||||
## What does this PR do?
|
||||
|
||||
Updates SQLite to version ${{ steps.check-version.outputs.latest }}
|
||||
|
||||
Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-sqlite3.yml)
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -116,8 +116,10 @@ scripts/env.local
|
||||
sign.*.json
|
||||
sign.json
|
||||
src/bake/generated.ts
|
||||
src/generated_enum_extractor.zig
|
||||
src/bun.js/bindings-obj
|
||||
src/bun.js/bindings/GeneratedJS2Native.zig
|
||||
src/bun.js/bindings/GeneratedBindings.zig
|
||||
src/bun.js/debug-bindings-obj
|
||||
src/deps/zig-clap/.gitattributes
|
||||
src/deps/zig-clap/.github
|
||||
|
||||
@@ -5,6 +5,5 @@ test/js/deno
|
||||
test/node.js
|
||||
src/react-refresh.js
|
||||
*.min.js
|
||||
test/js/node/test/fixtures
|
||||
test/js/node/test/common
|
||||
test/snippets
|
||||
test/js/node/test
|
||||
|
||||
117
.vscode/launch.json
generated
vendored
117
.vscode/launch.json
generated
vendored
@@ -16,7 +16,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "1",
|
||||
@@ -33,7 +32,6 @@
|
||||
"args": ["test", "--only", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
@@ -56,7 +54,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "0",
|
||||
@@ -73,7 +70,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "0",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -90,7 +86,6 @@
|
||||
"args": ["test", "--watch", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -107,7 +102,6 @@
|
||||
"args": ["test", "--hot", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -124,7 +118,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -147,7 +140,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -187,7 +179,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "0",
|
||||
"BUN_DEBUG_IncrementalGraph": "1",
|
||||
@@ -207,7 +198,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "0",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -223,7 +213,6 @@
|
||||
"args": ["run", "--watch", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
// "BUN_DEBUG_DEBUGGER": "1",
|
||||
// "BUN_DEBUG_INTERNAL_DEBUGGER": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
@@ -242,7 +231,6 @@
|
||||
"args": ["run", "--hot", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -303,7 +291,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -320,7 +307,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "0",
|
||||
@@ -337,7 +323,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -354,7 +339,6 @@
|
||||
"args": ["test", "--watch", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -371,7 +355,6 @@
|
||||
"args": ["test", "--hot", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -388,7 +371,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -411,7 +393,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_DEBUG_jest": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
@@ -435,7 +416,6 @@
|
||||
"args": ["exec", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -452,7 +432,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -468,7 +447,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "0",
|
||||
},
|
||||
@@ -484,7 +462,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
"BUN_INSPECT": "ws://localhost:0/",
|
||||
@@ -506,7 +483,6 @@
|
||||
"args": ["install"],
|
||||
"cwd": "${fileDirname}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -522,7 +498,6 @@
|
||||
"args": ["test/runner.node.mjs"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"env": {
|
||||
"FORCE_COLOR": "1",
|
||||
"BUN_DEBUG_QUIET_LOGS": "1",
|
||||
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
|
||||
},
|
||||
@@ -542,10 +517,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -571,10 +542,6 @@
|
||||
"args": ["test", "--only", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -600,10 +567,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -629,10 +592,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "0",
|
||||
@@ -658,10 +617,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -696,10 +651,6 @@
|
||||
"args": ["test", "${file}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -735,10 +686,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -764,10 +711,6 @@
|
||||
"args": ["install"],
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -789,10 +732,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -814,10 +753,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -848,10 +783,6 @@
|
||||
"args": ["run", "${fileBasename}"],
|
||||
"cwd": "${fileDirname}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -883,10 +814,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -912,10 +839,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -941,10 +864,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "0",
|
||||
@@ -970,10 +889,6 @@
|
||||
"args": ["test", "--watch", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -999,10 +914,6 @@
|
||||
"args": ["test", "--hot", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1028,10 +939,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1066,10 +973,6 @@
|
||||
"args": ["test", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1105,10 +1008,6 @@
|
||||
"args": ["exec", "${input:testName}"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1131,10 +1030,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1156,10 +1051,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1185,10 +1076,6 @@
|
||||
"args": ["test"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
@@ -1223,10 +1110,6 @@
|
||||
"args": ["test/runner.node.mjs"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [
|
||||
{
|
||||
"name": "FORCE_COLOR",
|
||||
"value": "1",
|
||||
},
|
||||
{
|
||||
"name": "BUN_DEBUG_QUIET_LOGS",
|
||||
"value": "1",
|
||||
|
||||
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -63,7 +63,7 @@
|
||||
"editor.tabSize": 4,
|
||||
"editor.defaultFormatter": "xaver.clang-format",
|
||||
},
|
||||
"clangd.arguments": ["-header-insertion=never"],
|
||||
"clangd.arguments": ["-header-insertion=never", "-no-unused-includes"],
|
||||
|
||||
// JavaScript
|
||||
"prettier.enable": true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Configuring a development environment for Bun can take 10-30 minutes depending on your internet connection and computer speed. You will need ~10GB of free disk space for the repository and build artifacts.
|
||||
|
||||
If you are using Windows, please refer to [this guide](/docs/project/building-windows)
|
||||
If you are using Windows, please refer to [this guide](/docs/project/building-windows.md)
|
||||
|
||||
{% details summary="For Ubuntu users" %}
|
||||
TL;DR: Ubuntu 22.04 is suggested.
|
||||
|
||||
22
build.zig
22
build.zig
@@ -327,6 +327,19 @@ pub fn build(b: *Build) !void {
|
||||
.{ .os = .windows, .arch = .x86_64 },
|
||||
});
|
||||
}
|
||||
|
||||
// zig build enum-extractor
|
||||
{
|
||||
// const step = b.step("enum-extractor", "Extract enum definitions (invoked by a code generator)");
|
||||
// const exe = b.addExecutable(.{
|
||||
// .name = "enum_extractor",
|
||||
// .root_source_file = b.path("./src/generated_enum_extractor.zig"),
|
||||
// .target = b.graph.host,
|
||||
// .optimize = .Debug,
|
||||
// });
|
||||
// const run = b.addRunArtifact(exe);
|
||||
// step.dependOn(&run.step);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn addMultiCheck(
|
||||
@@ -414,6 +427,15 @@ pub fn addBunObject(b: *Build, opts: *BunBuildOptions) *Compile {
|
||||
}
|
||||
addInternalPackages(b, obj, opts);
|
||||
obj.root_module.addImport("build_options", opts.buildOptionsModule(b));
|
||||
|
||||
const translate_plugin_api = b.addTranslateC(.{
|
||||
.root_source_file = b.path("./packages/bun-native-bundler-plugin-api/bundler_plugin.h"),
|
||||
.target = opts.target,
|
||||
.optimize = opts.optimize,
|
||||
.link_libc = true,
|
||||
});
|
||||
obj.root_module.addImport("bun-native-bundler-plugin-api", translate_plugin_api.createModule());
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ else()
|
||||
setx(RELEASE OFF)
|
||||
endif()
|
||||
|
||||
if(CMAKE_BUILD_TYPE MATCHES "Debug|RelWithDebInfo")
|
||||
if(CMAKE_BUILD_TYPE MATCHES "Debug")
|
||||
setx(DEBUG ON)
|
||||
else()
|
||||
setx(DEBUG OFF)
|
||||
|
||||
@@ -4,7 +4,7 @@ register_repository(
|
||||
REPOSITORY
|
||||
oven-sh/boringssl
|
||||
COMMIT
|
||||
29a2cd359458c9384694b75456026e4b57e3e567
|
||||
914b005ef3ece44159dca0ffad74eb42a9f6679f
|
||||
)
|
||||
|
||||
register_cmake_command(
|
||||
|
||||
@@ -318,13 +318,13 @@ register_command(
|
||||
TARGET
|
||||
bun-bake-codegen
|
||||
COMMENT
|
||||
"Bundling Kit Runtime"
|
||||
"Bundling Bake Runtime"
|
||||
COMMAND
|
||||
${BUN_EXECUTABLE}
|
||||
run
|
||||
${BUN_BAKE_RUNTIME_CODEGEN_SCRIPT}
|
||||
--debug=${DEBUG}
|
||||
--codegen_root=${CODEGEN_PATH}
|
||||
--codegen-root=${CODEGEN_PATH}
|
||||
SOURCES
|
||||
${BUN_BAKE_RUNTIME_SOURCES}
|
||||
${BUN_BAKE_RUNTIME_CODEGEN_SOURCES}
|
||||
@@ -334,6 +334,39 @@ register_command(
|
||||
${BUN_BAKE_RUNTIME_OUTPUTS}
|
||||
)
|
||||
|
||||
set(BUN_BINDGEN_SCRIPT ${CWD}/src/codegen/bindgen.ts)
|
||||
|
||||
file(GLOB_RECURSE BUN_BINDGEN_SOURCES ${CONFIGURE_DEPENDS}
|
||||
${CWD}/src/**/*.bind.ts
|
||||
)
|
||||
|
||||
set(BUN_BINDGEN_CPP_OUTPUTS
|
||||
${CODEGEN_PATH}/GeneratedBindings.cpp
|
||||
)
|
||||
|
||||
set(BUN_BINDGEN_ZIG_OUTPUTS
|
||||
${CWD}/src/bun.js/bindings/GeneratedBindings.zig
|
||||
)
|
||||
|
||||
register_command(
|
||||
TARGET
|
||||
bun-binding-generator
|
||||
COMMENT
|
||||
"Processing \".bind.ts\" files"
|
||||
COMMAND
|
||||
${BUN_EXECUTABLE}
|
||||
run
|
||||
${BUN_BINDGEN_SCRIPT}
|
||||
--debug=${DEBUG}
|
||||
--codegen-root=${CODEGEN_PATH}
|
||||
SOURCES
|
||||
${BUN_BINDGEN_SOURCES}
|
||||
${BUN_BINDGEN_SCRIPT}
|
||||
OUTPUTS
|
||||
${BUN_BINDGEN_CPP_OUTPUTS}
|
||||
${BUN_BINDGEN_ZIG_OUTPUTS}
|
||||
)
|
||||
|
||||
set(BUN_JS_SINK_SCRIPT ${CWD}/src/codegen/generate-jssink.ts)
|
||||
|
||||
set(BUN_JS_SINK_SOURCES
|
||||
@@ -385,7 +418,6 @@ set(BUN_OBJECT_LUT_OUTPUTS
|
||||
${CODEGEN_PATH}/NodeModuleModule.lut.h
|
||||
)
|
||||
|
||||
|
||||
macro(WEBKIT_ADD_SOURCE_DEPENDENCIES _source _deps)
|
||||
set(_tmp)
|
||||
get_source_file_property(_tmp ${_source} OBJECT_DEPENDS)
|
||||
@@ -461,6 +493,7 @@ list(APPEND BUN_ZIG_SOURCES
|
||||
${CWD}/build.zig
|
||||
${CWD}/root.zig
|
||||
${CWD}/root_wasm.zig
|
||||
${BUN_BINDGEN_ZIG_OUTPUTS}
|
||||
)
|
||||
|
||||
set(BUN_ZIG_GENERATED_SOURCES
|
||||
@@ -482,7 +515,6 @@ endif()
|
||||
|
||||
set(BUN_ZIG_OUTPUT ${BUILD_PATH}/bun-zig.o)
|
||||
|
||||
|
||||
if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm|ARM|arm64|ARM64|aarch64|AARCH64")
|
||||
if(APPLE)
|
||||
set(ZIG_CPU "apple_m1")
|
||||
@@ -606,6 +638,7 @@ list(APPEND BUN_CPP_SOURCES
|
||||
${BUN_JS_SINK_OUTPUTS}
|
||||
${BUN_JAVASCRIPT_OUTPUTS}
|
||||
${BUN_OBJECT_LUT_OUTPUTS}
|
||||
${BUN_BINDGEN_CPP_OUTPUTS}
|
||||
)
|
||||
|
||||
if(WIN32)
|
||||
|
||||
@@ -4,7 +4,7 @@ register_repository(
|
||||
REPOSITORY
|
||||
c-ares/c-ares
|
||||
COMMIT
|
||||
c29e75d54c3743783d51a609980495cf553b4bca
|
||||
41ee334af3e3d0027dca5e477855d0244936bd49
|
||||
)
|
||||
|
||||
register_cmake_command(
|
||||
|
||||
@@ -4,7 +4,7 @@ register_repository(
|
||||
REPOSITORY
|
||||
ebiggers/libdeflate
|
||||
COMMIT
|
||||
dc76454a39e7e83b68c3704b6e3784654f8d5ac5
|
||||
9d624d1d8ba82c690d6d6be1d0a961fc5a983ea4
|
||||
)
|
||||
|
||||
register_cmake_command(
|
||||
|
||||
@@ -4,7 +4,7 @@ register_repository(
|
||||
REPOSITORY
|
||||
cloudflare/lol-html
|
||||
COMMIT
|
||||
8d4c273ded322193d017042d1f48df2766b0f88b
|
||||
4f8becea13a0021c8b71abd2dcc5899384973b66
|
||||
)
|
||||
|
||||
set(LOLHTML_CWD ${VENDOR_PATH}/lolhtml/c-api)
|
||||
@@ -49,6 +49,8 @@ register_command(
|
||||
CARGO_TERM_VERBOSE=true
|
||||
CARGO_TERM_DIAGNOSTIC=true
|
||||
CARGO_ENCODED_RUSTFLAGS=${RUSTFLAGS}
|
||||
CARGO_HOME=${CARGO_HOME}
|
||||
RUSTUP_HOME=${RUSTUP_HOME}
|
||||
)
|
||||
|
||||
target_link_libraries(${bun} PRIVATE ${LOLHTML_LIBRARY})
|
||||
|
||||
@@ -4,7 +4,7 @@ register_repository(
|
||||
REPOSITORY
|
||||
litespeedtech/ls-hpack
|
||||
COMMIT
|
||||
3d0f1fc1d6e66a642e7a98c55deb38aa986eb4b0
|
||||
32e96f10593c7cb8553cd8c9c12721100ae9e924
|
||||
)
|
||||
|
||||
if(WIN32)
|
||||
|
||||
@@ -1,15 +1,42 @@
|
||||
if(DEFINED ENV{CARGO_HOME})
|
||||
set(CARGO_HOME $ENV{CARGO_HOME})
|
||||
elseif(CMAKE_HOST_WIN32)
|
||||
set(CARGO_HOME $ENV{USERPROFILE}/.cargo)
|
||||
if(NOT EXISTS ${CARGO_HOME})
|
||||
set(CARGO_HOME $ENV{PROGRAMFILES}/Rust/cargo)
|
||||
endif()
|
||||
else()
|
||||
set(CARGO_HOME $ENV{HOME}/.cargo)
|
||||
endif()
|
||||
|
||||
if(DEFINED ENV{RUSTUP_HOME})
|
||||
set(RUSTUP_HOME $ENV{RUSTUP_HOME})
|
||||
elseif(CMAKE_HOST_WIN32)
|
||||
set(RUSTUP_HOME $ENV{USERPROFILE}/.rustup)
|
||||
if(NOT EXISTS ${RUSTUP_HOME})
|
||||
set(RUSTUP_HOME $ENV{PROGRAMFILES}/Rust/rustup)
|
||||
endif()
|
||||
else()
|
||||
set(RUSTUP_HOME $ENV{HOME}/.rustup)
|
||||
endif()
|
||||
|
||||
find_command(
|
||||
VARIABLE
|
||||
CARGO_EXECUTABLE
|
||||
COMMAND
|
||||
cargo
|
||||
PATHS
|
||||
$ENV{HOME}/.cargo/bin
|
||||
${CARGO_HOME}/bin
|
||||
REQUIRED
|
||||
OFF
|
||||
)
|
||||
|
||||
if(EXISTS ${CARGO_EXECUTABLE})
|
||||
if(CARGO_EXECUTABLE MATCHES "^${CARGO_HOME}")
|
||||
setx(CARGO_HOME ${CARGO_HOME})
|
||||
setx(RUSTUP_HOME ${RUSTUP_HOME})
|
||||
endif()
|
||||
|
||||
return()
|
||||
endif()
|
||||
|
||||
|
||||
@@ -671,7 +671,7 @@ _bun() {
|
||||
cmd)
|
||||
local -a scripts_list
|
||||
IFS=$'\n' scripts_list=($(SHELL=zsh bun getcompletes i))
|
||||
scripts="scripts:scripts:(($scripts_list))"
|
||||
scripts="scripts:scripts:((${scripts_list//:/\\\\:}))"
|
||||
IFS=$'\n' files_list=($(SHELL=zsh bun getcompletes j))
|
||||
|
||||
main_commands=(
|
||||
@@ -871,8 +871,8 @@ _bun_run_param_script_completion() {
|
||||
IFS=$'\n' scripts_list=($(SHELL=zsh bun getcompletes s))
|
||||
IFS=$'\n' bins=($(SHELL=zsh bun getcompletes b))
|
||||
|
||||
_alternative "scripts:scripts:(($scripts_list))"
|
||||
_alternative "bin:bin:(($bins))"
|
||||
_alternative "scripts:scripts:((${scripts_list//:/\\\\:}))"
|
||||
_alternative "bin:bin:((${bins//:/\\\\:}))"
|
||||
_alternative "files:file:_files -g '*.(js|ts|jsx|tsx|wasm)'"
|
||||
}
|
||||
|
||||
|
||||
@@ -546,6 +546,113 @@ export type ImportKind =
|
||||
|
||||
By design, the manifest is a simple JSON object that can easily be serialized or written to disk. It is also compatible with esbuild's [`metafile`](https://esbuild.github.io/api/#metafile) format. -->
|
||||
|
||||
### `env`
|
||||
|
||||
Controls how environment variables are handled during bundling. Internally, this uses `define` to inject environment variables into the bundle, but makes it easier to specify the environment variables to inject.
|
||||
|
||||
#### `env: "inline"`
|
||||
|
||||
Injects environment variables into the bundled output by converting `process.env.FOO` references to string literals containing the actual environment variable values.
|
||||
|
||||
{% codetabs group="a" %}
|
||||
|
||||
```ts#JavaScript
|
||||
await Bun.build({
|
||||
entrypoints: ['./index.tsx'],
|
||||
outdir: './out',
|
||||
env: "inline",
|
||||
})
|
||||
```
|
||||
|
||||
```bash#CLI
|
||||
$ FOO=bar BAZ=123 bun build ./index.tsx --outdir ./out --env inline
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
For the input below:
|
||||
|
||||
```js#input.js
|
||||
console.log(process.env.FOO);
|
||||
console.log(process.env.BAZ);
|
||||
```
|
||||
|
||||
The generated bundle will contain the following code:
|
||||
|
||||
```js#output.js
|
||||
console.log("bar");
|
||||
console.log("123");
|
||||
```
|
||||
|
||||
#### `env: "PUBLIC_*"` (prefix)
|
||||
|
||||
Inlines environment variables matching the given prefix (the part before the `*` character), replacing `process.env.FOO` with the actual environment variable value. This is useful for selectively inlining environment variables for things like public-facing URLs or client-side tokens, without worrying about injecting private credentials into output bundles.
|
||||
|
||||
{% codetabs group="a" %}
|
||||
|
||||
```ts#JavaScript
|
||||
await Bun.build({
|
||||
entrypoints: ['./index.tsx'],
|
||||
outdir: './out',
|
||||
|
||||
// Inline all env vars that start with "ACME_PUBLIC_"
|
||||
env: "ACME_PUBLIC_*",
|
||||
})
|
||||
```
|
||||
|
||||
```bash#CLI
|
||||
$ FOO=bar BAZ=123 ACME_PUBLIC_URL=https://acme.com bun build ./index.tsx --outdir ./out --env 'ACME_PUBLIC_*'
|
||||
```
|
||||
|
||||
{% /codetabs %}
|
||||
|
||||
For example, given the following environment variables:
|
||||
|
||||
```bash
|
||||
$ FOO=bar BAZ=123 ACME_PUBLIC_URL=https://acme.com
|
||||
```
|
||||
|
||||
And source code:
|
||||
|
||||
```ts#index.tsx
|
||||
console.log(process.env.FOO);
|
||||
console.log(process.env.ACME_PUBLIC_URL);
|
||||
console.log(process.env.BAZ);
|
||||
```
|
||||
|
||||
The generated bundle will contain the following code:
|
||||
|
||||
```js
|
||||
console.log(process.env.FOO);
|
||||
console.log("https://acme.com");
|
||||
console.log(process.env.BAZ);
|
||||
```
|
||||
|
||||
#### `env: "disable"`
|
||||
|
||||
Disables environment variable injection entirely.
|
||||
|
||||
For example, given the following environment variables:
|
||||
|
||||
```bash
|
||||
$ FOO=bar BAZ=123 ACME_PUBLIC_URL=https://acme.com
|
||||
```
|
||||
|
||||
And source code:
|
||||
|
||||
```ts#index.tsx
|
||||
console.log(process.env.FOO);
|
||||
console.log(process.env.ACME_PUBLIC_URL);
|
||||
console.log(process.env.BAZ);
|
||||
```
|
||||
|
||||
The generated bundle will contain the following code:
|
||||
|
||||
```js
|
||||
console.log(process.env.FOO);
|
||||
console.log(process.env.BAZ);
|
||||
```
|
||||
|
||||
### `sourcemap`
|
||||
|
||||
Specifies the type of sourcemap to generate.
|
||||
|
||||
@@ -16,7 +16,7 @@ Set these variables in a `.env` file.
|
||||
Bun reads the following files automatically (listed in order of increasing precedence).
|
||||
|
||||
- `.env`
|
||||
- `.env.production` or `.env.development` (depending on value of `NODE_ENV`)
|
||||
- `.env.production`, `.env.development`, `.env.test` (depending on value of `NODE_ENV`)
|
||||
- `.env.local`
|
||||
|
||||
```txt#.env
|
||||
|
||||
@@ -30,7 +30,6 @@ Bun implements the vast majority of Jest's matchers, but compatibility isn't 100
|
||||
|
||||
Some notable missing features:
|
||||
|
||||
- `expect().toMatchInlineSnapshot()`
|
||||
- `expect().toHaveReturned()`
|
||||
|
||||
---
|
||||
|
||||
@@ -4,10 +4,6 @@ name: Use snapshot testing in `bun test`
|
||||
|
||||
Bun's test runner supports Jest-style snapshot testing via `.toMatchSnapshot()`.
|
||||
|
||||
{% callout %}
|
||||
The `.toMatchInlineSnapshot()` method is not yet supported.
|
||||
{% /callout %}
|
||||
|
||||
```ts#snap.test.ts
|
||||
import { test, expect } from "bun:test";
|
||||
|
||||
@@ -96,4 +92,4 @@ Ran 1 tests across 1 files. [102.00ms]
|
||||
|
||||
---
|
||||
|
||||
See [Docs > Test Runner > Snapshots](https://bun.sh/docs/test/mocks) for complete documentation on mocking with the Bun test runner.
|
||||
See [Docs > Test Runner > Snapshots](https://bun.sh/docs/test/snapshots) for complete documentation on snapshots with the Bun test runner.
|
||||
|
||||
@@ -49,7 +49,7 @@ Next, add these preload scripts to your `bunfig.toml` (you can also have everyth
|
||||
|
||||
```toml#bunfig.toml
|
||||
[test]
|
||||
preload = ["happydom.ts", "testing-library.ts"]
|
||||
preload = ["./happydom.ts", "./testing-library.ts"]
|
||||
```
|
||||
---
|
||||
|
||||
@@ -84,4 +84,4 @@ test('Can use Testing Library', () => {
|
||||
|
||||
---
|
||||
|
||||
Refer to the [Testing Library docs](https://testing-library.com/), [Happy DOM repo](https://github.com/capricorn86/happy-dom) and [Docs > Test runner > DOM](https://bun.sh/docs/test/dom) for complete documentation on writing browser tests with Bun.
|
||||
Refer to the [Testing Library docs](https://testing-library.com/), [Happy DOM repo](https://github.com/capricorn86/happy-dom) and [Docs > Test runner > DOM](https://bun.sh/docs/test/dom) for complete documentation on writing browser tests with Bun.
|
||||
|
||||
@@ -4,10 +4,6 @@ name: Update snapshots in `bun test`
|
||||
|
||||
Bun's test runner supports Jest-style snapshot testing via `.toMatchSnapshot()`.
|
||||
|
||||
{% callout %}
|
||||
The `.toMatchInlineSnapshot()` method is not yet supported.
|
||||
{% /callout %}
|
||||
|
||||
```ts#snap.test.ts
|
||||
import { test, expect } from "bun:test";
|
||||
|
||||
@@ -47,4 +43,4 @@ Ran 1 tests across 1 files. [102.00ms]
|
||||
|
||||
---
|
||||
|
||||
See [Docs > Test Runner > Snapshots](https://bun.sh/docs/test/mocks) for complete documentation on mocking with the Bun test runner.
|
||||
See [Docs > Test Runner > Snapshots](https://bun.sh/docs/test/snapshots) for complete documentation on snapshots with the Bun test runner.
|
||||
|
||||
@@ -189,14 +189,19 @@ For convenience, here are download links for the latest version:
|
||||
|
||||
- [`bun-linux-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64.zip)
|
||||
- [`bun-linux-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-baseline.zip)
|
||||
- [`bun-linux-x64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl.zip)
|
||||
- [`bun-linux-x64-musl-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl-baseline.zip)
|
||||
- [`bun-windows-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64.zip)
|
||||
- [`bun-windows-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64-baseline.zip)
|
||||
- [`bun-darwin-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-aarch64.zip)
|
||||
- [`bun-linux-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64.zip)
|
||||
- [`bun-linux-aarch64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64-musl.zip)
|
||||
- [`bun-darwin-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-x64.zip)
|
||||
- [`bun-darwin-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-x64-baseline.zip)
|
||||
|
||||
The `baseline` binaries are built for older CPUs which may not support AVX2 instructions. If you run into an "Illegal Instruction" error when running Bun, try using the `baseline` binaries instead. Bun's install scripts automatically choose the correct binary for your system which helps avoid this issue. Baseline builds are slower than regular builds, so use them only if necessary.
|
||||
The `musl` binaries are built for distributions that do not ship with the glibc libraries by default, instead relying on musl. The two most popular distros are Void Linux and Alpine Linux, with the latter is used heavily in Docker containers. If you encounter an error like the following: `bun: /lib/x86_64-linux-gnu/libm.so.6: version GLIBC_2.29' not found (required by bun)`, try using the musl binary. Bun's install script automatically chooses the correct binary for your system.
|
||||
|
||||
The `baseline` binaries are built for older CPUs which may not support AVX2 instructions. If you run into an "Illegal Instruction" error when running Bun, try using the `baseline` binaries instead. Bun's install scripts automatically chooses the correct binary for your system which helps avoid this issue. Baseline builds are slower than regular builds, so use them only if necessary.
|
||||
|
||||
<!--
|
||||
## Native
|
||||
|
||||
@@ -402,6 +402,9 @@ export default {
|
||||
page("project/building-windows", "Building Windows", {
|
||||
description: "Learn how to setup a development environment for contributing to the Windows build of Bun.",
|
||||
}),
|
||||
page("project/bindgen", "Bindgen", {
|
||||
description: "About the bindgen code generator",
|
||||
}),
|
||||
page("project/licensing", "License", {
|
||||
description: `Bun is a MIT-licensed project with a large number of statically-linked dependencies with various licenses.`,
|
||||
}),
|
||||
|
||||
199
docs/project/bindgen.md
Normal file
199
docs/project/bindgen.md
Normal file
@@ -0,0 +1,199 @@
|
||||
{% callout %}
|
||||
|
||||
This document is for maintainers and contributors to Bun, and describes internal implementation details.
|
||||
|
||||
{% /callout %}
|
||||
|
||||
The new bindings generator, introduced to the codebase in Dec 2024, scans for
|
||||
`*.bind.ts` to find function and class definition, and generates glue code to
|
||||
interop between JavaScript and native code.
|
||||
|
||||
There are currently other code generators and systems that achieve similar
|
||||
purposes. The following will all eventually be completely phased out in favor of
|
||||
this one:
|
||||
|
||||
- "Classes generator", converting `*.classes.ts` for custom classes.
|
||||
- "JS2Native", allowing ad-hoc calls from `src/js` to native code.
|
||||
|
||||
## Creating JS Functions in Zig
|
||||
|
||||
Given a file implementing a simple function, such as `add`
|
||||
|
||||
```zig#src/bun.js/math.zig
|
||||
pub fn add(global: *JSC.JSGlobalObject, a: i32, b: i32) !i32 {
|
||||
return std.math.add(i32, a, b) catch {
|
||||
// Binding functions can return `error.OutOfMemory` and `error.JSError`.
|
||||
// Others like `error.Overflow` from `std.math.add` must be converted.
|
||||
// Remember to be descriptive.
|
||||
return global.throwPretty("Integer overflow while adding", .{});
|
||||
};
|
||||
}
|
||||
|
||||
const gen = bun.gen.math; // "math" being this file's basename
|
||||
|
||||
const std = @import("std");
|
||||
const bun = @import("root").bun;
|
||||
const JSC = bun.JSC;
|
||||
```
|
||||
|
||||
Then describe the API schema using a `.bind.ts` function. The binding file goes next to the Zig file.
|
||||
|
||||
```ts#src/bun.js/math.bind.ts
|
||||
import { t, fn } from 'bindgen';
|
||||
|
||||
export const add = fn({
|
||||
args: {
|
||||
global: t.globalObject,
|
||||
a: t.i32,
|
||||
b: t.i32.default(1),
|
||||
},
|
||||
ret: t.i32,
|
||||
});
|
||||
```
|
||||
|
||||
This function declaration is equivalent to:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* Throws if zero arguments are provided.
|
||||
* Wraps out of range numbers using modulo.
|
||||
*/
|
||||
declare function add(a: number, b: number = 1): number;
|
||||
```
|
||||
|
||||
The code generator will provide `bun.gen.math.jsAdd`, which is the native function implementation. To pass to JavaScript, use `bun.gen.math.createAddCallback(global)`
|
||||
|
||||
## Strings
|
||||
|
||||
The type for receiving strings is one of [`t.DOMString`](https://webidl.spec.whatwg.org/#idl-DOMString), [`t.ByteString`](https://webidl.spec.whatwg.org/#idl-ByteString), and [`t.USVString`](https://webidl.spec.whatwg.org/#idl-USVString). These map directly to their WebIDL counterparts, and have slightly different conversion logic. Bindgen will pass BunString to native code in all cases.
|
||||
|
||||
When in doubt, use DOMString.
|
||||
|
||||
`t.UTF8String` can be used in place of `t.DOMString`, but will call `bun.String.toUTF8`. The native callback gets `[]const u8` (WTF-8 data) passed to native code, freeing it after the function returns.
|
||||
|
||||
TLDRs from WebIDL spec:
|
||||
|
||||
- ByteString can only contain valid latin1 characters. It is not safe to assume bun.String is already in 8-bit format, but it is extremely likely.
|
||||
- USVString will not contain invalid surrogate pairs, aka text that can be represented correctly in UTF-8.
|
||||
- DOMString is the loosest but also most recommended strategy.
|
||||
|
||||
## Function Variants
|
||||
|
||||
A `variants` can specify multiple variants (also known as overloads).
|
||||
|
||||
```ts#src/bun.js/math.bind.ts
|
||||
import { t, fn } from 'bindgen';
|
||||
|
||||
export const action = fn({
|
||||
variants: [
|
||||
{
|
||||
args: {
|
||||
a: t.i32,
|
||||
},
|
||||
ret: t.i32,
|
||||
},
|
||||
{
|
||||
args: {
|
||||
a: t.DOMString,
|
||||
},
|
||||
ret: t.DOMString,
|
||||
},
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
In Zig, each variant gets a number, based on the order the schema defines.
|
||||
|
||||
```
|
||||
fn action1(a: i32) i32 {
|
||||
return a;
|
||||
}
|
||||
|
||||
fn action2(a: bun.String) bun.String {
|
||||
return a;
|
||||
}
|
||||
```
|
||||
|
||||
## `t.dictionary`
|
||||
|
||||
A `dictionary` is a definition for a JavaScript object, typically as a function inputs. For function outputs, it is usually a smarter idea to declare a class type to add functions and destructuring.
|
||||
|
||||
## Enumerations
|
||||
|
||||
To use [WebIDL's enumeration](https://webidl.spec.whatwg.org/#idl-enums) type, use either:
|
||||
|
||||
- `t.stringEnum`: Create and codegen a new enum type.
|
||||
- `t.zigEnum`: Derive a bindgen type off of an existing enum in the codebase.
|
||||
|
||||
An example of `stringEnum` as used in `fmt.zig` / `bun:internal-for-testing`
|
||||
|
||||
```ts
|
||||
export const Formatter = t.stringEnum(
|
||||
"highlight-javascript",
|
||||
"escape-powershell",
|
||||
);
|
||||
|
||||
export const fmtString = fn({
|
||||
args: {
|
||||
global: t.globalObject,
|
||||
code: t.UTF8String,
|
||||
formatter: Formatter,
|
||||
},
|
||||
ret: t.DOMString,
|
||||
});
|
||||
```
|
||||
|
||||
WebIDL strongly encourages using kebab case for enumeration values, to be consistent with existing Web APIs.
|
||||
|
||||
### Deriving enums from Zig code
|
||||
|
||||
TODO: zigEnum
|
||||
|
||||
## `t.oneOf`
|
||||
|
||||
A `oneOf` is a union between two or more types. It is represented by `union(enum)` in Zig.
|
||||
|
||||
TODO:
|
||||
|
||||
## Attributes
|
||||
|
||||
There are set of attributes that can be chained onto `t.*` types. On all types there are:
|
||||
|
||||
- `.required`, in dictionary parameters only
|
||||
- `.optional`, in function arguments only
|
||||
- `.default(T)`
|
||||
|
||||
When a value is optional, it is lowered to a Zig optional.
|
||||
|
||||
Depending on the type, there are more attributes available. See the type definitions in auto-complete for more details. Note that one of the above three can only be applied, and they must be applied at the end.
|
||||
|
||||
### Integer Attributes
|
||||
|
||||
Integer types allow customizing the overflow behavior with `clamp` or `enforceRange`
|
||||
|
||||
```ts
|
||||
import { t, fn } from "bindgen";
|
||||
|
||||
export const add = fn({
|
||||
args: {
|
||||
global: t.globalObject,
|
||||
// enforce in i32 range
|
||||
a: t.i32.enforceRange(),
|
||||
// clamp to u16 range
|
||||
c: t.u16,
|
||||
// enforce in arbitrary range, with a default if not provided
|
||||
b: t.i32.enforceRange(0, 1000).default(5),
|
||||
// clamp to arbitrary range, or null
|
||||
d: t.u16.clamp(0, 10).optional,
|
||||
},
|
||||
ret: t.i32,
|
||||
});
|
||||
```
|
||||
|
||||
## Callbacks
|
||||
|
||||
TODO
|
||||
|
||||
## Classes
|
||||
|
||||
TODO
|
||||
@@ -355,7 +355,7 @@ Bun.build({
|
||||
|
||||
{% /callout %}
|
||||
|
||||
## Lifecycle callbacks
|
||||
## Lifecycle hooks
|
||||
|
||||
Plugins can register callbacks to be run at various points in the lifecycle of a bundle:
|
||||
|
||||
@@ -363,6 +363,8 @@ Plugins can register callbacks to be run at various points in the lifecycle of a
|
||||
- [`onResolve()`](#onresolve): Run before a module is resolved
|
||||
- [`onLoad()`](#onload): Run before a module is loaded.
|
||||
|
||||
### Reference
|
||||
|
||||
A rough overview of the types (please refer to Bun's `bun.d.ts` for the full type definitions):
|
||||
|
||||
```ts
|
||||
@@ -603,3 +605,98 @@ plugin({
|
||||
```
|
||||
|
||||
Note that the `.defer()` function currently has the limitation that it can only be called once per `onLoad` callback.
|
||||
|
||||
## Native plugins
|
||||
|
||||
{% callout %}
|
||||
**NOTE** — This is an advanced and experiemental API recommended for plugin developers who are familiar with systems programming and the C ABI. Use with caution.
|
||||
{% /callout %}
|
||||
|
||||
One of the reasons why Bun's bundler is so fast is that it is written in native code and leverages multi-threading to load and parse modules in parallel.
|
||||
|
||||
However, one limitation of plugins written in JavaScript is that JavaScript itself is single-threaded.
|
||||
|
||||
Native plugins are written as [NAPI](/docs/node-api) modules and can be run on multiple threads. This allows native plugins to run much faster than JavaScript plugins.
|
||||
|
||||
In addition, native plugins can skip unnecessary work such as the UTF-8 -> UTF-16 conversion needed to pass strings to JavaScript.
|
||||
|
||||
These are the following lifecycle hooks which are available to native plugins:
|
||||
|
||||
- [`onBeforeParse()`](#onbeforeparse): Called on any thread before a file is parsed by Bun's bundler.
|
||||
|
||||
### Creating a native plugin
|
||||
|
||||
Native plugins are NAPI modules which expose lifecycle hooks as C ABI functions.
|
||||
|
||||
To create a native plugin, you must export a C ABI function which matches the signature of the native lifecycle hook you want to implement.
|
||||
|
||||
#### Example: Rust with napi-rs
|
||||
|
||||
First initialize a napi project (see [here](https://napi.rs/docs/introduction/getting-started) for a more comprehensive guide).
|
||||
|
||||
Then install Bun's official safe plugin wrapper crate:
|
||||
|
||||
```bash
|
||||
cargo add bun-native-plugin
|
||||
```
|
||||
|
||||
Now you can export an `extern "C" fn` which is the implementation of your plugin:
|
||||
|
||||
```rust
|
||||
#[no_mangle]
|
||||
extern "C" fn on_before_parse_impl(
|
||||
args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
) {
|
||||
let args = unsafe { &*args };
|
||||
let result = unsafe { &mut *result };
|
||||
|
||||
let mut handle = match bun_native_plugin::OnBeforeParse::from_raw(args, result) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let source_code = match handle.input_source_code() {
|
||||
Ok(source_code) => source_code,
|
||||
Err(_) => {
|
||||
handle.log_error("Fetching source code failed!");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let loader = handle.output_loader();
|
||||
handle.set_output_source_code(source_code.replace("foo", "bar"), loader);
|
||||
```
|
||||
|
||||
Use napi-rs to compile the plugin to a `.node` file, then you can `require()` it from JS and use it:
|
||||
|
||||
```js
|
||||
await Bun.build({
|
||||
entrypoints: ["index.ts"],
|
||||
setup(build) {
|
||||
const myNativePlugin = require("./path/to/plugin.node");
|
||||
|
||||
build.onBeforeParse(
|
||||
{ filter: /\.ts/ },
|
||||
{ napiModule: myNativePlugin, symbol: "on_before_parse_impl" },
|
||||
);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### `onBeforeParse`
|
||||
|
||||
```ts
|
||||
onBeforeParse(
|
||||
args: { filter: RegExp; namespace?: string },
|
||||
callback: { napiModule: NapiModule; symbol: string; external?: unknown },
|
||||
): void;
|
||||
```
|
||||
|
||||
This lifecycle callback is run immediately before a file is parsed by Bun's bundler.
|
||||
|
||||
As input, it receives the file's contents and can optionally return new source code.
|
||||
|
||||
This callback can be called from any thread and so the napi module implementation must be thread-safe.
|
||||
|
||||
@@ -531,17 +531,17 @@ Bun implements the following matchers. Full Jest compatibility is on the roadmap
|
||||
|
||||
---
|
||||
|
||||
- ❌
|
||||
- ✅
|
||||
- [`.toMatchInlineSnapshot()`](https://jestjs.io/docs/expect#tomatchinlinesnapshotpropertymatchers-inlinesnapshot)
|
||||
|
||||
---
|
||||
|
||||
- ❌
|
||||
- ✅
|
||||
- [`.toThrowErrorMatchingSnapshot()`](https://jestjs.io/docs/expect#tothrowerrormatchingsnapshothint)
|
||||
|
||||
---
|
||||
|
||||
- ❌
|
||||
- ✅
|
||||
- [`.toThrowErrorMatchingInlineSnapshot()`](https://jestjs.io/docs/expect#tothrowerrormatchinginlinesnapshotinlinesnapshot)
|
||||
|
||||
{% /table %}
|
||||
|
||||
15
package.json
15
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "bun",
|
||||
"version": "1.1.38",
|
||||
"version": "1.1.39",
|
||||
"workspaces": [
|
||||
"./packages/bun-types"
|
||||
],
|
||||
@@ -21,7 +21,7 @@
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"source-map-js": "^1.2.0",
|
||||
"typescript": "^5.4.5",
|
||||
"typescript": "^5.7.2",
|
||||
"caniuse-lite": "^1.0.30001620",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"@mdn/browser-compat-data": "~5.5.28"
|
||||
@@ -30,8 +30,8 @@
|
||||
"bun-types": "workspace:packages/bun-types"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -B build/debug",
|
||||
"build:debug": "bun run build",
|
||||
"build": "bun run build:debug",
|
||||
"build:debug": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -B build/debug",
|
||||
"build:valgrind": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -DENABLE_BASELINE=ON -ENABLE_VALGRIND=ON -B build/debug-valgrind",
|
||||
"build:release": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -B build/release",
|
||||
"build:ci": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DCMAKE_VERBOSE_MAKEFILE=ON -DCI=true -B build/release-ci --verbose --fresh",
|
||||
@@ -39,8 +39,8 @@
|
||||
"build:logs": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DENABLE_LOGS=ON -B build/release-logs",
|
||||
"build:safe": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DZIG_OPTIMIZE=ReleaseSafe -B build/release-safe",
|
||||
"build:smol": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=MinSizeRel -B build/release-smol",
|
||||
"build:local": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -DWEBKIT_LOCAL=ON -B build/debug",
|
||||
"build:release:local": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DWEBKIT_LOCAL=ON -B build/release",
|
||||
"build:local": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -DWEBKIT_LOCAL=ON -B build/debug-local",
|
||||
"build:release:local": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -DWEBKIT_LOCAL=ON -B build/release-local",
|
||||
"build:release:with_logs": "cmake . -DCMAKE_BUILD_TYPE=Release -DENABLE_LOGS=true -GNinja -Bbuild-release && ninja -Cbuild-release",
|
||||
"build:debug-zig-release": "cmake . -DCMAKE_BUILD_TYPE=Release -DZIG_OPTIMIZE=Debug -GNinja -Bbuild-debug-zig-release && ninja -Cbuild-debug-zig-release",
|
||||
"css-properties": "bun run src/css/properties/generate_properties.ts",
|
||||
@@ -73,6 +73,7 @@
|
||||
"prettier": "bun run analysis:no-llvm --target prettier",
|
||||
"prettier:check": "bun run analysis:no-llvm --target prettier-check",
|
||||
"prettier:extra": "bun run analysis:no-llvm --target prettier-extra",
|
||||
"prettier:diff": "bun run analysis:no-llvm --target prettier-diff"
|
||||
"prettier:diff": "bun run analysis:no-llvm --target prettier-diff",
|
||||
"node:test": "node ./scripts/runner.node.mjs --quiet --exec-path=$npm_execpath --node-tests "
|
||||
}
|
||||
}
|
||||
|
||||
5
packages/bun-build-mdx-rs/.cargo/config.toml
Normal file
5
packages/bun-build-mdx-rs/.cargo/config.toml
Normal file
@@ -0,0 +1,5 @@
|
||||
[target.aarch64-unknown-linux-musl]
|
||||
linker = "aarch64-linux-musl-gcc"
|
||||
rustflags = ["-C", "target-feature=-crt-static"]
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
202
packages/bun-build-mdx-rs/.gitignore
vendored
Normal file
202
packages/bun-build-mdx-rs/.gitignore
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/node
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=node
|
||||
|
||||
### Node ###
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/node
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/macos
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=macos
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### macOS Patch ###
|
||||
# iCloud generated files
|
||||
*.icloud
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/macos
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/windows
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=windows
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/windows
|
||||
|
||||
#Added by cargo
|
||||
|
||||
/target
|
||||
Cargo.lock
|
||||
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
|
||||
*.node
|
||||
|
||||
dist/
|
||||
|
||||
index.js
|
||||
index.d.ts
|
||||
13
packages/bun-build-mdx-rs/.npmignore
Normal file
13
packages/bun-build-mdx-rs/.npmignore
Normal file
@@ -0,0 +1,13 @@
|
||||
target
|
||||
Cargo.lock
|
||||
.cargo
|
||||
.github
|
||||
npm
|
||||
.eslintrc
|
||||
.prettierignore
|
||||
rustfmt.toml
|
||||
yarn.lock
|
||||
*.node
|
||||
.yarn
|
||||
__test__
|
||||
renovate.json
|
||||
21
packages/bun-build-mdx-rs/Cargo.toml
Normal file
21
packages/bun-build-mdx-rs/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "bun-mdx-rs"
|
||||
version = "0.0.0"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
|
||||
napi = { version = "2.12.2", default-features = false, features = ["napi4"] }
|
||||
napi-derive = "2.12.2"
|
||||
mdxjs = "0.2.11"
|
||||
bun-native-plugin = { path = "../bun-native-plugin-rs" }
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2.0.1"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = "symbols"
|
||||
34
packages/bun-build-mdx-rs/README.md
Normal file
34
packages/bun-build-mdx-rs/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# bun-build-mdx-rs
|
||||
|
||||
This is a proof of concept for using a third-party native addon in `Bun.build()`.
|
||||
|
||||
This uses `mdxjs-rs` to convert MDX to JSX.
|
||||
|
||||
TODO: **This needs to be built & published to npm.**
|
||||
|
||||
## Building locally:
|
||||
|
||||
```sh
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
```js
|
||||
import { build } from "bun";
|
||||
import mdx from "./index.js";
|
||||
|
||||
// TODO: This needs to be prebuilt for the current platform
|
||||
// Probably use a napi-rs template for this
|
||||
import addon from "./target/release/libmdx_bun.dylib" with { type: "file" };
|
||||
|
||||
const results = await build({
|
||||
entrypoints: ["./hello.jsx"],
|
||||
plugins: [mdx({ addon })],
|
||||
minify: true,
|
||||
outdir: "./dist",
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify("production"),
|
||||
},
|
||||
});
|
||||
|
||||
console.log(results);
|
||||
```
|
||||
7
packages/bun-build-mdx-rs/__test__/index.spec.mjs
Normal file
7
packages/bun-build-mdx-rs/__test__/index.spec.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
import test from 'ava'
|
||||
|
||||
import { sum } from '../index.js'
|
||||
|
||||
test('sum from native', (t) => {
|
||||
t.is(sum(1, 2), 3)
|
||||
})
|
||||
5
packages/bun-build-mdx-rs/build.rs
Normal file
5
packages/bun-build-mdx-rs/build.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
extern crate napi_build;
|
||||
|
||||
fn main() {
|
||||
napi_build::setup();
|
||||
}
|
||||
6
packages/bun-build-mdx-rs/input/index.ts
Normal file
6
packages/bun-build-mdx-rs/input/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import page1 from "./page1.mdx";
|
||||
import page2 from "./page2.mdx";
|
||||
import page3 from "./page3.mdx";
|
||||
import page4 from "./page4.mdx";
|
||||
|
||||
console.log(page1, page2, page3, page4);
|
||||
11
packages/bun-build-mdx-rs/input/page1.mdx
Normal file
11
packages/bun-build-mdx-rs/input/page1.mdx
Normal file
@@ -0,0 +1,11 @@
|
||||
# Hello World
|
||||
|
||||
This is a sample MDX file that demonstrates various MDX features.
|
||||
|
||||
## Components
|
||||
|
||||
You can use JSX components directly in MDX:
|
||||
|
||||
<Button onClick={() => alert("Hello!")}>Click me</Button>
|
||||
|
||||
## Code Blocks
|
||||
11
packages/bun-build-mdx-rs/input/page2.mdx
Normal file
11
packages/bun-build-mdx-rs/input/page2.mdx
Normal file
@@ -0,0 +1,11 @@
|
||||
# Hello World
|
||||
|
||||
This is a sample MDX file that demonstrates various MDX features.
|
||||
|
||||
## Components
|
||||
|
||||
You can use JSX components directly in MDX:
|
||||
|
||||
<Button onClick={() => alert("Hello!")}>Click me</Button>
|
||||
|
||||
## Code Blocks
|
||||
11
packages/bun-build-mdx-rs/input/page3.mdx
Normal file
11
packages/bun-build-mdx-rs/input/page3.mdx
Normal file
@@ -0,0 +1,11 @@
|
||||
# Hello World
|
||||
|
||||
This is a sample MDX file that demonstrates various MDX features.
|
||||
|
||||
## Components
|
||||
|
||||
You can use JSX components directly in MDX:
|
||||
|
||||
<Button onClick={() => alert("Hello!")}>Click me</Button>
|
||||
|
||||
## Code Blocks
|
||||
11
packages/bun-build-mdx-rs/input/page4.mdx
Normal file
11
packages/bun-build-mdx-rs/input/page4.mdx
Normal file
@@ -0,0 +1,11 @@
|
||||
# Hello World
|
||||
|
||||
This is a sample MDX file that demonstrates various MDX features.
|
||||
|
||||
## Components
|
||||
|
||||
You can use JSX components directly in MDX:
|
||||
|
||||
<Button onClick={() => alert("Hello!")}>Click me</Button>
|
||||
|
||||
## Code Blocks
|
||||
3
packages/bun-build-mdx-rs/npm/darwin-arm64/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/darwin-arm64/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-darwin-arm64`
|
||||
|
||||
This is the **aarch64-apple-darwin** binary for `bun-mdx-rs`
|
||||
18
packages/bun-build-mdx-rs/npm/darwin-arm64/package.json
Normal file
18
packages/bun-build-mdx-rs/npm/darwin-arm64/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-darwin-arm64",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"main": "bun-mdx-rs.darwin-arm64.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.darwin-arm64.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/darwin-x64/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/darwin-x64/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-darwin-x64`
|
||||
|
||||
This is the **x86_64-apple-darwin** binary for `bun-mdx-rs`
|
||||
18
packages/bun-build-mdx-rs/npm/darwin-x64/package.json
Normal file
18
packages/bun-build-mdx-rs/npm/darwin-x64/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-darwin-x64",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"main": "bun-mdx-rs.darwin-x64.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.darwin-x64.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/linux-arm64-gnu/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/linux-arm64-gnu/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-linux-arm64-gnu`
|
||||
|
||||
This is the **aarch64-unknown-linux-gnu** binary for `bun-mdx-rs`
|
||||
21
packages/bun-build-mdx-rs/npm/linux-arm64-gnu/package.json
Normal file
21
packages/bun-build-mdx-rs/npm/linux-arm64-gnu/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-linux-arm64-gnu",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"main": "bun-mdx-rs.linux-arm64-gnu.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.linux-arm64-gnu.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"libc": [
|
||||
"glibc"
|
||||
]
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/linux-arm64-musl/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/linux-arm64-musl/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-linux-arm64-musl`
|
||||
|
||||
This is the **aarch64-unknown-linux-musl** binary for `bun-mdx-rs`
|
||||
21
packages/bun-build-mdx-rs/npm/linux-arm64-musl/package.json
Normal file
21
packages/bun-build-mdx-rs/npm/linux-arm64-musl/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-linux-arm64-musl",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"main": "bun-mdx-rs.linux-arm64-musl.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.linux-arm64-musl.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"libc": [
|
||||
"musl"
|
||||
]
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/linux-x64-gnu/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/linux-x64-gnu/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-linux-x64-gnu`
|
||||
|
||||
This is the **x86_64-unknown-linux-gnu** binary for `bun-mdx-rs`
|
||||
21
packages/bun-build-mdx-rs/npm/linux-x64-gnu/package.json
Normal file
21
packages/bun-build-mdx-rs/npm/linux-x64-gnu/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-linux-x64-gnu",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"main": "bun-mdx-rs.linux-x64-gnu.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.linux-x64-gnu.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"libc": [
|
||||
"glibc"
|
||||
]
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/linux-x64-musl/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/linux-x64-musl/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-linux-x64-musl`
|
||||
|
||||
This is the **x86_64-unknown-linux-musl** binary for `bun-mdx-rs`
|
||||
21
packages/bun-build-mdx-rs/npm/linux-x64-musl/package.json
Normal file
21
packages/bun-build-mdx-rs/npm/linux-x64-musl/package.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-linux-x64-musl",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"main": "bun-mdx-rs.linux-x64-musl.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.linux-x64-musl.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"libc": [
|
||||
"musl"
|
||||
]
|
||||
}
|
||||
3
packages/bun-build-mdx-rs/npm/win32-x64-msvc/README.md
Normal file
3
packages/bun-build-mdx-rs/npm/win32-x64-msvc/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# `bun-mdx-rs-win32-x64-msvc`
|
||||
|
||||
This is the **x86_64-pc-windows-msvc** binary for `bun-mdx-rs`
|
||||
18
packages/bun-build-mdx-rs/npm/win32-x64-msvc/package.json
Normal file
18
packages/bun-build-mdx-rs/npm/win32-x64-msvc/package.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "bun-mdx-rs-win32-x64-msvc",
|
||||
"version": "0.0.0",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"main": "bun-mdx-rs.win32-x64-msvc.node",
|
||||
"files": [
|
||||
"bun-mdx-rs.win32-x64-msvc.node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
}
|
||||
37
packages/bun-build-mdx-rs/package.json
Normal file
37
packages/bun-build-mdx-rs/package.json
Normal file
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "bun-mdx-rs",
|
||||
"version": "0.0.0",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"napi": {
|
||||
"name": "bun-mdx-rs",
|
||||
"triples": {
|
||||
"additional": [
|
||||
"aarch64-apple-darwin",
|
||||
"aarch64-unknown-linux-gnu",
|
||||
"aarch64-unknown-linux-musl",
|
||||
"x86_64-unknown-linux-musl"
|
||||
]
|
||||
}
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@napi-rs/cli": "^2.18.4",
|
||||
"ava": "^6.0.1"
|
||||
},
|
||||
"ava": {
|
||||
"timeout": "3m"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"scripts": {
|
||||
"artifacts": "napi artifacts",
|
||||
"build": "napi build --platform --release",
|
||||
"build:debug": "napi build --platform",
|
||||
"prepublishOnly": "napi prepublish -t npm",
|
||||
"test": "ava",
|
||||
"universal": "napi universal",
|
||||
"version": "napi version"
|
||||
}
|
||||
}
|
||||
2
packages/bun-build-mdx-rs/rustfmt.toml
Normal file
2
packages/bun-build-mdx-rs/rustfmt.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
tab_spaces = 2
|
||||
edition = "2021"
|
||||
55
packages/bun-build-mdx-rs/src/lib.rs
Normal file
55
packages/bun-build-mdx-rs/src/lib.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use bun_native_plugin::{define_bun_plugin, BunLoader, OnBeforeParse};
|
||||
use mdxjs::{compile, Options as CompileOptions};
|
||||
use napi_derive::napi;
|
||||
|
||||
#[macro_use]
|
||||
extern crate napi;
|
||||
|
||||
define_bun_plugin!("bun-mdx-rs");
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn bun_mdx_rs(
|
||||
args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
) {
|
||||
let args = unsafe { &*args };
|
||||
|
||||
let mut handle = match OnBeforeParse::from_raw(args, result) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let source_str = match handle.input_source_code() {
|
||||
Ok(source_str) => source_str,
|
||||
Err(_) => {
|
||||
handle.log_error("Failed to fetch source code");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut options = CompileOptions::gfm();
|
||||
|
||||
// Leave it as JSX for Bun to handle
|
||||
options.jsx = true;
|
||||
|
||||
let path = match handle.path() {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
handle.log_error(&format!("Failed to get path: {:?}", e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
options.filepath = Some(path.to_string());
|
||||
|
||||
match compile(&source_str, &options) {
|
||||
Ok(compiled) => {
|
||||
handle.set_output_source_code(compiled, BunLoader::BUN_LOADER_JSX);
|
||||
}
|
||||
Err(_) => {
|
||||
handle.log_error("Failed to compile MDX");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
73
packages/bun-native-bundler-plugin-api/bundler_plugin.h
Normal file
73
packages/bun-native-bundler-plugin-api/bundler_plugin.h
Normal file
@@ -0,0 +1,73 @@
|
||||
#ifndef BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
#define BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef enum {
|
||||
BUN_LOADER_JSX = 0,
|
||||
BUN_LOADER_JS = 1,
|
||||
BUN_LOADER_TS = 2,
|
||||
BUN_LOADER_TSX = 3,
|
||||
BUN_LOADER_CSS = 4,
|
||||
BUN_LOADER_FILE = 5,
|
||||
BUN_LOADER_JSON = 6,
|
||||
BUN_LOADER_TOML = 7,
|
||||
BUN_LOADER_WASM = 8,
|
||||
BUN_LOADER_NAPI = 9,
|
||||
BUN_LOADER_BASE64 = 10,
|
||||
BUN_LOADER_DATAURL = 11,
|
||||
BUN_LOADER_TEXT = 12,
|
||||
} BunLoader;
|
||||
|
||||
const BunLoader BUN_LOADER_MAX = BUN_LOADER_TEXT;
|
||||
|
||||
typedef struct BunLogOptions {
|
||||
size_t __struct_size;
|
||||
const uint8_t *message_ptr;
|
||||
size_t message_len;
|
||||
const uint8_t *path_ptr;
|
||||
size_t path_len;
|
||||
const uint8_t *source_line_text_ptr;
|
||||
size_t source_line_text_len;
|
||||
int8_t level;
|
||||
int line;
|
||||
int lineEnd;
|
||||
int column;
|
||||
int columnEnd;
|
||||
} BunLogOptions;
|
||||
|
||||
typedef struct {
|
||||
size_t __struct_size;
|
||||
void *bun;
|
||||
const uint8_t *path_ptr;
|
||||
size_t path_len;
|
||||
const uint8_t *namespace_ptr;
|
||||
size_t namespace_len;
|
||||
uint8_t default_loader;
|
||||
void *external;
|
||||
} OnBeforeParseArguments;
|
||||
|
||||
typedef struct OnBeforeParseResult {
|
||||
size_t __struct_size;
|
||||
uint8_t *source_ptr;
|
||||
size_t source_len;
|
||||
uint8_t loader;
|
||||
int (*fetchSourceCode)(const OnBeforeParseArguments *args,
|
||||
struct OnBeforeParseResult *result);
|
||||
void *plugin_source_code_context;
|
||||
void (*free_plugin_source_code_context)(void *ctx);
|
||||
void (*log)(const OnBeforeParseArguments *args, BunLogOptions *options);
|
||||
} OnBeforeParseResult;
|
||||
|
||||
typedef enum {
|
||||
BUN_LOG_LEVEL_VERBOSE = 0,
|
||||
BUN_LOG_LEVEL_DEBUG = 1,
|
||||
BUN_LOG_LEVEL_INFO = 2,
|
||||
BUN_LOG_LEVEL_WARN = 3,
|
||||
BUN_LOG_LEVEL_ERROR = 4,
|
||||
} BunLogLevel;
|
||||
|
||||
const BunLogLevel BUN_LOG_MAX = BUN_LOG_LEVEL_ERROR;
|
||||
|
||||
#endif // BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
1
packages/bun-native-plugin-rs/.gitignore
vendored
Normal file
1
packages/bun-native-plugin-rs/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
target/
|
||||
286
packages/bun-native-plugin-rs/Cargo.lock
generated
Normal file
286
packages/bun-native-plugin-rs/Cargo.lock
generated
Normal file
@@ -0,0 +1,286 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.70.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"log",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
"shlex",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
|
||||
|
||||
[[package]]
|
||||
name = "bun-native-plugin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cexpr"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
|
||||
dependencies = [
|
||||
"nom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "clang-sys"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"libc",
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.166"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2ccc108bbc0b1331bd061864e7cd823c0cab660bbe6970e66e2c0614decde36"
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.89"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
7
packages/bun-native-plugin-rs/Cargo.toml
Normal file
7
packages/bun-native-plugin-rs/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "bun-native-plugin"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[build-dependencies]
|
||||
bindgen = "0.70.1"
|
||||
248
packages/bun-native-plugin-rs/README.md
Normal file
248
packages/bun-native-plugin-rs/README.md
Normal file
@@ -0,0 +1,248 @@
|
||||
> ⚠️ Note: This is an advanced and experimental API recommended only for plugin developers who are familiar with systems proramming and the C ABI. Use with caution.
|
||||
|
||||
# Bun Native Plugins
|
||||
|
||||
This crate provides a Rustified wrapper over the Bun's native bundler plugin C API.
|
||||
|
||||
Some advantages to _native_ bundler plugins as opposed to regular ones implemented in JS:
|
||||
|
||||
- Native plugins take full advantage of Bun's parallelized bundler pipeline and run on multiple threads at the same time
|
||||
- Unlike JS, native plugins don't need to do the UTF-8 <-> UTF-16 source code string conversions
|
||||
|
||||
What are native bundler plugins exactly? Precisely, they are NAPI modules which expose a C ABI function which implement a plugin lifecycle hook.
|
||||
|
||||
The currently supported lifecycle hooks are:
|
||||
|
||||
- `onBeforeParse` (called immediately before a file is parsed, allows you to modify the source code of the file)
|
||||
|
||||
## Getting started
|
||||
|
||||
Since native bundler plugins are NAPI modules, the easiest way to get started is to create a new [napi-rs](https://github.com/napi-rs/napi-rs) project:
|
||||
|
||||
```bash
|
||||
bun add -g @napi-rs/cli
|
||||
napi new
|
||||
```
|
||||
|
||||
Then install this crate:
|
||||
|
||||
```bash
|
||||
cargo add bun-native-plugin
|
||||
```
|
||||
|
||||
Now, inside the `lib.rs` file, expose a C ABI function which has the same function signature as the plugin lifecycle hook that you want to implement.
|
||||
|
||||
For example, implementing `onBeforeParse`:
|
||||
|
||||
```rs
|
||||
use bun_native_plugin::{define_bun_plugin, OnBeforeParse};
|
||||
use napi_derive::napi;
|
||||
|
||||
/// Define with the name of the plugin
|
||||
define_bun_plugin!("replace-foo-with-bar");
|
||||
|
||||
/// This is necessary for napi-rs to compile this into a proper NAPI module
|
||||
#[napi]
|
||||
pub fn register_bun_plugin() {}
|
||||
|
||||
/// Use `no_mangle` so that we can reference this symbol by name later
|
||||
/// when registering this native plugin in JS.
|
||||
///
|
||||
/// Here we'll create a dummy plugin which replaces all occurences of
|
||||
/// `foo` with `bar`
|
||||
#[no_mangle]
|
||||
pub extern "C" fn on_before_parse_plugin_impl(
|
||||
args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
) {
|
||||
let args = unsafe { &*args };
|
||||
|
||||
// This returns a handle which is a safe wrapper over the raw
|
||||
// C API.
|
||||
let mut handle = OnBeforeParse::from_raw(args, result) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => {
|
||||
// `OnBeforeParse::from_raw` handles error logging
|
||||
// so it fine to return here.
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let input_source_code = match handle.input_source_code() {
|
||||
Ok(source_str) => source_str,
|
||||
Err(_) => {
|
||||
// If we encounter an error, we must log it so that
|
||||
// Bun knows this plugin failed.
|
||||
handle.log_error("Failed to fetch source code!");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let loader = handle.output_loader();
|
||||
let output_source_code = source_str.replace("foo", "bar");
|
||||
handle.set_output_source_code(output_source_code, loader);
|
||||
}
|
||||
```
|
||||
|
||||
Then compile this NAPI module. If you using napi-rs, the `package.json` should have a `build` script you can run:
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
```
|
||||
|
||||
This will produce a `.node` file in the project directory.
|
||||
|
||||
With the compiled NAPI module, you can now register the plugin from JS:
|
||||
|
||||
```js
|
||||
const result = await Bun.build({
|
||||
entrypoints: ["index.ts"],
|
||||
plugins: [
|
||||
{
|
||||
name: "replace-foo-with-bar",
|
||||
setup(build) {
|
||||
const napiModule = require("path/to/napi_module.node");
|
||||
|
||||
// Register the `onBeforeParse` hook to run on all `.ts` files.
|
||||
// We tell it to use function we implemented inside of our `lib.rs` code.
|
||||
build.onBeforeParse(
|
||||
{ filter: /\.ts/ },
|
||||
{ napiModule, symbol: "on_before_parse_plugin_impl" },
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Very important information
|
||||
|
||||
### Error handling and panics
|
||||
|
||||
It is highly recommended to avoid panicking as this will crash the runtime. Instead, you must handle errors and log them:
|
||||
|
||||
```rs
|
||||
let input_source_code = match handle.input_source_code() {
|
||||
Ok(source_str) => source_str,
|
||||
Err(_) => {
|
||||
// If we encounter an error, we must log it so that
|
||||
// Bun knows this plugin failed.
|
||||
handle.log_error("Failed to fetch source code!");
|
||||
return;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Passing state to and from JS: `External`
|
||||
|
||||
One way to communicate data from your plugin and JS and vice versa is through the NAPI's [External](https://napi.rs/docs/concepts/external) type.
|
||||
|
||||
An External in NAPI is like an opaque pointer to data that can be passed to and from JS. Inside your NAPI module, you can retrieve
|
||||
the pointer and modify the data.
|
||||
|
||||
As an example that extends our getting started example above, let's say you wanted to count the number of `foo`'s that the native plugin encounters.
|
||||
|
||||
You would expose a NAPI module function which creates this state. Recall that state in native plugins must be threadsafe. This usually means
|
||||
that your state must be `Sync`:
|
||||
|
||||
```rs
|
||||
struct PluginState {
|
||||
foo_count: std::sync::atomic::AtomicU32,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn create_plugin_state() -> External<PluginState> {
|
||||
let external = External::new(PluginState {
|
||||
foo_count: 0,
|
||||
});
|
||||
|
||||
external
|
||||
}
|
||||
|
||||
|
||||
#[napi]
|
||||
pub fn get_foo_count(plugin_state: External<PluginState>) -> u32 {
|
||||
let plugin_state: &PluginState = &plugin_state;
|
||||
plugin_state.foo_count.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
```
|
||||
|
||||
When you register your plugin from Javascript, you call the napi module function to create the external and then pass it:
|
||||
|
||||
```js
|
||||
const napiModule = require("path/to/napi_module.node");
|
||||
const pluginState = napiModule.createPluginState();
|
||||
|
||||
const result = await Bun.build({
|
||||
entrypoints: ["index.ts"],
|
||||
plugins: [
|
||||
{
|
||||
name: "replace-foo-with-bar",
|
||||
setup(build) {
|
||||
build.onBeforeParse(
|
||||
{ filter: /\.ts/ },
|
||||
{
|
||||
napiModule,
|
||||
symbol: "on_before_parse_plugin_impl",
|
||||
// pass our NAPI external which contains our plugin state here
|
||||
external: pluginState,
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log("Total `foo`s encountered: ", pluginState.getFooCount());
|
||||
```
|
||||
|
||||
Finally, from the native implementation of your plugin, you can extract the external:
|
||||
|
||||
```rs
|
||||
pub extern "C" fn on_before_parse_plugin_impl(
|
||||
args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
) {
|
||||
let args = unsafe { &*args };
|
||||
|
||||
let mut handle = OnBeforeParse::from_raw(args, result) {
|
||||
Ok(handle) => handle,
|
||||
Err(_) => {
|
||||
// `OnBeforeParse::from_raw` handles error logging
|
||||
// so it fine to return here.
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let plugin_state: &PluginState =
|
||||
// This operation is only safe if you pass in an external when registering the plugin.
|
||||
// If you don't, this could lead to a segfault or access of undefined memory.
|
||||
match unsafe { handle.external().and_then(|state| state.ok_or(Error::Unknown)) } {
|
||||
Ok(state) => state,
|
||||
Err(_) => {
|
||||
handle.log_error("Failed to get external!");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Fetch our source code again
|
||||
let input_source_code = match handle.input_source_code() {
|
||||
Ok(source_str) => source_str,
|
||||
Err(_) => {
|
||||
handle.log_error("Failed to fetch source code!");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Count the number of `foo`s and add it to our state
|
||||
let foo_count = source_code.matches("foo").count() as u32;
|
||||
plugin_state.foo_count.fetch_add(foo_count, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
```
|
||||
|
||||
### Concurrency
|
||||
|
||||
Your `extern "C"` plugin function can be called _on any thread_ at _any time_ and _multiple times at once_.
|
||||
|
||||
Therefore, you must design any state management to be threadsafe
|
||||
20
packages/bun-native-plugin-rs/build.rs
Normal file
20
packages/bun-native-plugin-rs/build.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rustc-link-search=./headers");
|
||||
|
||||
let bindings = bindgen::Builder::default()
|
||||
.header("wrapper.h")
|
||||
// Add absolute path to headers directory
|
||||
.clang_arg("-I./headers")
|
||||
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
|
||||
.rustified_enum("BunLogLevel")
|
||||
.rustified_enum("BunLoader")
|
||||
.generate()
|
||||
.expect("Unable to generate bindings");
|
||||
|
||||
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
|
||||
bindings
|
||||
.write_to_file(out_path.join("bindings.rs"))
|
||||
.expect("Couldn't write bindings!");
|
||||
}
|
||||
6
packages/bun-native-plugin-rs/copy_headers.ts
Normal file
6
packages/bun-native-plugin-rs/copy_headers.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
const dirname = join(import.meta.dir, "../", "bun-native-bundler-plugin-api");
|
||||
await Bun.$`rm -rf headers`;
|
||||
await Bun.$`mkdir -p headers`;
|
||||
await Bun.$`cp -R ${dirname} headers/bun-native-bundler-plugin-api`;
|
||||
@@ -0,0 +1,79 @@
|
||||
#ifndef BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
#define BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef enum {
|
||||
BUN_LOADER_JSX = 0,
|
||||
BUN_LOADER_JS = 1,
|
||||
BUN_LOADER_TS = 2,
|
||||
BUN_LOADER_TSX = 3,
|
||||
BUN_LOADER_CSS = 4,
|
||||
BUN_LOADER_FILE = 5,
|
||||
BUN_LOADER_JSON = 6,
|
||||
BUN_LOADER_TOML = 7,
|
||||
BUN_LOADER_WASM = 8,
|
||||
BUN_LOADER_NAPI = 9,
|
||||
BUN_LOADER_BASE64 = 10,
|
||||
BUN_LOADER_DATAURL = 11,
|
||||
BUN_LOADER_TEXT = 12,
|
||||
BUN_LOADER_BUNSH = 13,
|
||||
BUN_LOADER_SQLITE = 14,
|
||||
BUN_LOADER_SQLITE_EMBEDDED = 15
|
||||
} BunLoader;
|
||||
|
||||
const BunLoader BUN_LOADER_MAX = BUN_LOADER_SQLITE_EMBEDDED;
|
||||
|
||||
typedef struct BunLogOptions {
|
||||
size_t __struct_size;
|
||||
const uint8_t* message_ptr;
|
||||
size_t message_len;
|
||||
const uint8_t* path_ptr;
|
||||
size_t path_len;
|
||||
const uint8_t* source_line_text_ptr;
|
||||
size_t source_line_text_len;
|
||||
int8_t level;
|
||||
int line;
|
||||
int lineEnd;
|
||||
int column;
|
||||
int columnEnd;
|
||||
} BunLogOptions;
|
||||
|
||||
typedef struct {
|
||||
size_t __struct_size;
|
||||
void* bun;
|
||||
const uint8_t* path_ptr;
|
||||
size_t path_len;
|
||||
const uint8_t* namespace_ptr;
|
||||
size_t namespace_len;
|
||||
uint8_t default_loader;
|
||||
void *external;
|
||||
} OnBeforeParseArguments;
|
||||
|
||||
typedef struct OnBeforeParseResult {
|
||||
size_t __struct_size;
|
||||
uint8_t* source_ptr;
|
||||
size_t source_len;
|
||||
uint8_t loader;
|
||||
int (*fetchSourceCode)(
|
||||
const OnBeforeParseArguments* args,
|
||||
struct OnBeforeParseResult* result
|
||||
);
|
||||
void* plugin_source_code_context;
|
||||
void (*free_plugin_source_code_context)(void* ctx);
|
||||
void (*log)(const OnBeforeParseArguments* args, BunLogOptions* options);
|
||||
} OnBeforeParseResult;
|
||||
|
||||
|
||||
typedef enum {
|
||||
BUN_LOG_LEVEL_VERBOSE = 0,
|
||||
BUN_LOG_LEVEL_DEBUG = 1,
|
||||
BUN_LOG_LEVEL_INFO = 2,
|
||||
BUN_LOG_LEVEL_WARN = 3,
|
||||
BUN_LOG_LEVEL_ERROR = 4,
|
||||
} BunLogLevel;
|
||||
|
||||
const BunLogLevel BUN_LOG_MAX = BUN_LOG_LEVEL_ERROR;
|
||||
|
||||
#endif // BUN_NATIVE_BUNDLER_PLUGIN_API_H
|
||||
627
packages/bun-native-plugin-rs/src/lib.rs
Normal file
627
packages/bun-native-plugin-rs/src/lib.rs
Normal file
@@ -0,0 +1,627 @@
|
||||
//! > ⚠️ Note: This is an advanced and experimental API recommended only for plugin developers who are familiar with systems proramming and the C ABI. Use with caution.
|
||||
//!
|
||||
//! # Bun Native Plugins
|
||||
//!
|
||||
//! This crate provides a Rustified wrapper over the Bun's native bundler plugin C API.
|
||||
//!
|
||||
//! Some advantages to _native_ bundler plugins as opposed to regular ones implemented in JS:
|
||||
//!
|
||||
//! - Native plugins take full advantage of Bun's parallelized bundler pipeline and run on multiple threads at the same time
|
||||
//! - Unlike JS, native plugins don't need to do the UTF-8 <-> UTF-16 source code string conversions
|
||||
//!
|
||||
//! What are native bundler plugins exactly? Precisely, they are NAPI modules which expose a C ABI function which implement a plugin lifecycle hook.
|
||||
//!
|
||||
//! The currently supported lifecycle hooks are:
|
||||
//!
|
||||
//! - `onBeforeParse` (called immediately before a file is parsed, allows you to modify the source code of the file)
|
||||
//!
|
||||
//! ## Getting started
|
||||
//!
|
||||
//! Since native bundler plugins are NAPI modules, the easiest way to get started is to create a new [napi-rs](https://github.com/napi-rs/napi-rs) project:
|
||||
//!
|
||||
//! ```bash
|
||||
//! bun add -g @napi-rs/cli
|
||||
//! napi new
|
||||
//! ```
|
||||
//!
|
||||
//! Then install this crate:
|
||||
//!
|
||||
//! ```bash
|
||||
//! cargo add bun-native-plugin
|
||||
//! ```
|
||||
//!
|
||||
//! Now, inside the `lib.rs` file, expose a C ABI function which has the same function signature as the plugin lifecycle hook that you want to implement.
|
||||
//!
|
||||
//! For example, implementing `onBeforeParse`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use bun_native_plugin::{OnBeforeParse};
|
||||
//!
|
||||
//! /// This is necessary for napi-rs to compile this into a proper NAPI module
|
||||
//! #[napi]
|
||||
//! pub fn register_bun_plugin() {}
|
||||
//!
|
||||
//! /// Use `no_mangle` so that we can reference this symbol by name later
|
||||
//! /// when registering this native plugin in JS.
|
||||
//! ///
|
||||
//! /// Here we'll create a dummy plugin which replaces all occurences of
|
||||
//! /// `foo` with `bar`
|
||||
//! #[no_mangle]
|
||||
//! pub extern "C" fn on_before_parse_plugin_impl(
|
||||
//! args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
//! result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
//! ) {
|
||||
//! let args = unsafe { &*args };
|
||||
//! let result = unsafe { &mut *result };
|
||||
//!
|
||||
//! // This returns a handle which is a safe wrapper over the raw
|
||||
//! // C API.
|
||||
//! let mut handle = OnBeforeParse::from_raw(args, result) {
|
||||
//! Ok(handle) => handle,
|
||||
//! Err(_) => {
|
||||
//! // `OnBeforeParse::from_raw` handles error logging
|
||||
//! // so it fine to return here.
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! let input_source_code = match handle.input_source_code() {
|
||||
//! Ok(source_str) => source_str,
|
||||
//! Err(_) => {
|
||||
//! // If we encounter an error, we must log it so that
|
||||
//! // Bun knows this plugin failed.
|
||||
//! handle.log_error("Failed to fetch source code!");
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! let loader = handle.output_loader();
|
||||
//! let output_source_code = source_str.replace("foo", "bar");
|
||||
//! handle.set_output_source_code(output_source_code, loader);
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Then compile this NAPI module. If you using napi-rs, the `package.json` should have a `build` script you can run:
|
||||
//!
|
||||
//! ```bash
|
||||
//! bun run build
|
||||
//! ```
|
||||
//!
|
||||
//! This will produce a `.node` file in the project directory.
|
||||
//!
|
||||
//! With the compiled NAPI module, you can now register the plugin from JS:
|
||||
//!
|
||||
//! ```js
|
||||
//! const result = await Bun.build({
|
||||
//! entrypoints: ["index.ts"],
|
||||
//! plugins: [
|
||||
//! {
|
||||
//! name: "replace-foo-with-bar",
|
||||
//! setup(build) {
|
||||
//! const napiModule = require("path/to/napi_module.node");
|
||||
//!
|
||||
//! // Register the `onBeforeParse` hook to run on all `.ts` files.
|
||||
//! // We tell it to use function we implemented inside of our `lib.rs` code.
|
||||
//! build.onBeforeParse(
|
||||
//! { filter: /\.ts/ },
|
||||
//! { napiModule, symbol: "on_before_parse_plugin_impl" },
|
||||
//! );
|
||||
//! },
|
||||
//! },
|
||||
//! ],
|
||||
//! });
|
||||
//! ```
|
||||
//!
|
||||
//! ## Very important information
|
||||
//!
|
||||
//! ### Error handling and panics
|
||||
//!
|
||||
//! It is highly recommended to avoid panicking as this will crash the runtime. Instead, you must handle errors and log them:
|
||||
//!
|
||||
//! ```rust
|
||||
//! let input_source_code = match handle.input_source_code() {
|
||||
//! Ok(source_str) => source_str,
|
||||
//! Err(_) => {
|
||||
//! // If we encounter an error, we must log it so that
|
||||
//! // Bun knows this plugin failed.
|
||||
//! handle.log_error("Failed to fetch source code!");
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//! ```
|
||||
//!
|
||||
//! ### Passing state to and from JS: `External`
|
||||
//!
|
||||
//! One way to communicate data from your plugin and JS and vice versa is through the NAPI's [External](https://napi.rs/docs/concepts/external) type.
|
||||
//!
|
||||
//! An External in NAPI is like an opaque pointer to data that can be passed to and from JS. Inside your NAPI module, you can retrieve
|
||||
//! the pointer and modify the data.
|
||||
//!
|
||||
//! As an example that extends our getting started example above, let's say you wanted to count the number of `foo`'s that the native plugin encounters.
|
||||
//!
|
||||
//! You would expose a NAPI module function which creates this state. Recall that state in native plugins must be threadsafe. This usually means
|
||||
//! that your state must be `Sync`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! struct PluginState {
|
||||
//! foo_count: std::sync::atomic::AtomicU32,
|
||||
//! }
|
||||
//!
|
||||
//! #[napi]
|
||||
//! pub fn create_plugin_state() -> External<PluginState> {
|
||||
//! let external = External::new(PluginState {
|
||||
//! foo_count: 0,
|
||||
//! });
|
||||
//!
|
||||
//! external
|
||||
//! }
|
||||
//!
|
||||
//!
|
||||
//! #[napi]
|
||||
//! pub fn get_foo_count(plugin_state: External<PluginState>) -> u32 {
|
||||
//! let plugin_state: &PluginState = &plugin_state;
|
||||
//! plugin_state.foo_count.load(std::sync::atomic::Ordering::Relaxed)
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! When you register your plugin from Javascript, you call the napi module function to create the external and then pass it:
|
||||
//!
|
||||
//! ```js
|
||||
//! const napiModule = require("path/to/napi_module.node");
|
||||
//! const pluginState = napiModule.createPluginState();
|
||||
//!
|
||||
//! const result = await Bun.build({
|
||||
//! entrypoints: ["index.ts"],
|
||||
//! plugins: [
|
||||
//! {
|
||||
//! name: "replace-foo-with-bar",
|
||||
//! setup(build) {
|
||||
//! build.onBeforeParse(
|
||||
//! { filter: /\.ts/ },
|
||||
//! {
|
||||
//! napiModule,
|
||||
//! symbol: "on_before_parse_plugin_impl",
|
||||
//! // pass our NAPI external which contains our plugin state here
|
||||
//! external: pluginState,
|
||||
//! },
|
||||
//! );
|
||||
//! },
|
||||
//! },
|
||||
//! ],
|
||||
//! });
|
||||
//!
|
||||
//! console.log("Total `foo`s encountered: ", pluginState.getFooCount());
|
||||
//! ```
|
||||
//!
|
||||
//! Finally, from the native implementation of your plugin, you can extract the external:
|
||||
//!
|
||||
//! ```rust
|
||||
//! pub extern "C" fn on_before_parse_plugin_impl(
|
||||
//! args: *const bun_native_plugin::sys::OnBeforeParseArguments,
|
||||
//! result: *mut bun_native_plugin::sys::OnBeforeParseResult,
|
||||
//! ) {
|
||||
//! let args = unsafe { &*args };
|
||||
//! let result = unsafe { &mut *result };
|
||||
//!
|
||||
//! let mut handle = OnBeforeParse::from_raw(args, result) {
|
||||
//! Ok(handle) => handle,
|
||||
//! Err(_) => {
|
||||
//! // `OnBeforeParse::from_raw` handles error logging
|
||||
//! // so it fine to return here.
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! let plugin_state: &PluginState =
|
||||
//! // This operation is only safe if you pass in an external when registering the plugin.
|
||||
//! // If you don't, this could lead to a segfault or access of undefined memory.
|
||||
//! match unsafe { handle.external().and_then(|state| state.ok_or(Error::Unknown)) } {
|
||||
//! Ok(state) => state,
|
||||
//! Err(_) => {
|
||||
//! handle.log_error("Failed to get external!");
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//!
|
||||
//! // Fetch our source code again
|
||||
//! let input_source_code = match handle.input_source_code() {
|
||||
//! Ok(source_str) => source_str,
|
||||
//! Err(_) => {
|
||||
//! handle.log_error("Failed to fetch source code!");
|
||||
//! return;
|
||||
//! }
|
||||
//! };
|
||||
//!
|
||||
//! // Count the number of `foo`s and add it to our state
|
||||
//! let foo_count = source_code.matches("foo").count() as u32;
|
||||
//! plugin_state.foo_count.fetch_add(foo_count, std::sync::atomic::Ordering::Relaxed);
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ### Concurrency
|
||||
//!
|
||||
//! Your `extern "C"` plugin function can be called _on any thread_ at _any time_ and _multiple times at once_.
|
||||
//!
|
||||
//! Therefore, you must design any state management to be threadsafe
|
||||
|
||||
#![allow(non_upper_case_globals)]
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
#[repr(transparent)]
|
||||
pub struct BunPluginName(*const c_char);
|
||||
|
||||
impl BunPluginName {
|
||||
pub const fn new(ptr: *const c_char) -> Self {
|
||||
Self(ptr)
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! define_bun_plugin {
|
||||
($name:expr) => {
|
||||
pub static BUN_PLUGIN_NAME_STRING: &str = $name;
|
||||
|
||||
#[no_mangle]
|
||||
pub static BUN_PLUGIN_NAME: bun_native_plugin::BunPluginName =
|
||||
bun_native_plugin::BunPluginName::new(BUN_PLUGIN_NAME_STRING.as_ptr() as *const _);
|
||||
|
||||
#[napi]
|
||||
fn bun_plugin_register() {}
|
||||
};
|
||||
}
|
||||
|
||||
unsafe impl Sync for BunPluginName {}
|
||||
|
||||
use std::{
|
||||
any::TypeId,
|
||||
borrow::Cow,
|
||||
cell::UnsafeCell,
|
||||
ffi::{c_char, c_void},
|
||||
str::Utf8Error,
|
||||
};
|
||||
|
||||
pub mod sys {
|
||||
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct TaggedObject<T> {
|
||||
type_id: TypeId,
|
||||
pub(crate) object: Option<T>,
|
||||
}
|
||||
|
||||
struct SourceCodeContext {
|
||||
source_ptr: *mut u8,
|
||||
source_len: usize,
|
||||
source_cap: usize,
|
||||
}
|
||||
|
||||
extern "C" fn free_plugin_source_code_context(ctx: *mut c_void) {
|
||||
// SAFETY: The ctx pointer is a pointer to the `SourceCodeContext` struct we allocated.
|
||||
unsafe {
|
||||
drop(Box::from_raw(ctx as *mut SourceCodeContext));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SourceCodeContext {
|
||||
fn drop(&mut self) {
|
||||
if !self.source_ptr.is_null() {
|
||||
// SAFETY: These fields come from a `String` that we allocated.
|
||||
unsafe {
|
||||
drop(String::from_raw_parts(
|
||||
self.source_ptr,
|
||||
self.source_len,
|
||||
self.source_cap,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type BunLogLevel = sys::BunLogLevel;
|
||||
pub type BunLoader = sys::BunLoader;
|
||||
|
||||
fn get_from_raw_str<'a>(ptr: *const u8, len: usize) -> Result<Cow<'a, str>> {
|
||||
let slice: &'a [u8] = unsafe { std::slice::from_raw_parts(ptr, len) };
|
||||
|
||||
// Windows allows invalid UTF-16 strings in the filesystem. These get converted to WTF-8 in Zig.
|
||||
// Meaning the string may contain invalid UTF-8, we'll have to use the safe checked version.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
std::str::from_utf8(slice)
|
||||
.map(Into::into)
|
||||
.or_else(|_| Ok(String::from_utf8_lossy(slice)))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
// SAFETY: The source code comes from Zig, which uses UTF-8, so this should be safe.
|
||||
|
||||
std::str::from_utf8(slice)
|
||||
.map(Into::into)
|
||||
.or_else(|_| Ok(String::from_utf8_lossy(slice)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Error {
|
||||
Utf8(Utf8Error),
|
||||
IncompatiblePluginVersion,
|
||||
ExternalTypeMismatch,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl From<Utf8Error> for Error {
|
||||
fn from(value: Utf8Error) -> Self {
|
||||
Self::Utf8(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// A safe handle for the arguments + result struct for the
|
||||
/// `OnBeforeParse` bundler lifecycle hook.
|
||||
///
|
||||
/// This struct acts as a safe wrapper around the raw C API structs
|
||||
/// (`sys::OnBeforeParseArguments`/`sys::OnBeforeParseResult`) needed to
|
||||
/// implement the `OnBeforeParse` bundler lifecycle hook.
|
||||
///
|
||||
/// To initialize this struct, see the `from_raw` method.
|
||||
pub struct OnBeforeParse<'a> {
|
||||
args_raw: &'a sys::OnBeforeParseArguments,
|
||||
result_raw: *mut sys::OnBeforeParseResult,
|
||||
compilation_context: *mut SourceCodeContext,
|
||||
}
|
||||
|
||||
impl<'a> OnBeforeParse<'a> {
|
||||
/// Initialize this struct from references to their raw counterparts.
|
||||
///
|
||||
/// This function will do a versioning check to ensure that the plugin
|
||||
/// is compatible with the current version of Bun. If the plugin is not
|
||||
/// compatible, it will log an error and return an error result.
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// extern "C" fn on_before_parse_impl(args: *const sys::OnBeforeParseArguments, result: *mut sys::OnBeforeParseResult) {
|
||||
/// let args = unsafe { &*args };
|
||||
/// let result = unsafe { &mut *result };
|
||||
/// let handle = match OnBeforeParse::from_raw(args, result) {
|
||||
/// Ok(handle) => handle,
|
||||
/// Err(()) => return,
|
||||
/// };
|
||||
/// }
|
||||
/// ```
|
||||
pub fn from_raw(
|
||||
args: &'a sys::OnBeforeParseArguments,
|
||||
result: *mut sys::OnBeforeParseResult,
|
||||
) -> Result<Self> {
|
||||
if args.__struct_size < std::mem::size_of::<sys::OnBeforeParseArguments>()
|
||||
|| unsafe { (*result).__struct_size } < std::mem::size_of::<sys::OnBeforeParseResult>()
|
||||
{
|
||||
let message = "This plugin is not compatible with the current version of Bun.";
|
||||
let mut log_options = sys::BunLogOptions {
|
||||
__struct_size: std::mem::size_of::<sys::BunLogOptions>(),
|
||||
message_ptr: message.as_ptr(),
|
||||
message_len: message.len(),
|
||||
path_ptr: args.path_ptr,
|
||||
path_len: args.path_len,
|
||||
source_line_text_ptr: std::ptr::null(),
|
||||
source_line_text_len: 0,
|
||||
level: BunLogLevel::BUN_LOG_LEVEL_ERROR as i8,
|
||||
line: 0,
|
||||
lineEnd: 0,
|
||||
column: 0,
|
||||
columnEnd: 0,
|
||||
};
|
||||
// SAFETY: The `log` function pointer is guaranteed to be valid by the Bun runtime.
|
||||
unsafe {
|
||||
((*result).log.unwrap())(args, &mut log_options);
|
||||
}
|
||||
return Err(Error::IncompatiblePluginVersion);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
args_raw: args,
|
||||
result_raw: result,
|
||||
compilation_context: std::ptr::null_mut() as *mut _,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn path(&self) -> Result<Cow<'_, str>> {
|
||||
get_from_raw_str(self.args_raw.path_ptr, self.args_raw.path_len)
|
||||
}
|
||||
|
||||
pub fn namespace(&self) -> Result<Cow<'_, str>> {
|
||||
get_from_raw_str(self.args_raw.namespace_ptr, self.args_raw.namespace_len)
|
||||
}
|
||||
|
||||
/// Get the external object from the `OnBeforeParse` arguments.
|
||||
///
|
||||
/// The external object is set by the plugin definition inside of JS:
|
||||
/// ```js
|
||||
/// await Bun.build({
|
||||
/// plugins: [
|
||||
/// {
|
||||
/// name: "my-plugin",
|
||||
/// setup(builder) {
|
||||
/// const native_plugin = require("./native_plugin.node");
|
||||
/// const external = native_plugin.createExternal();
|
||||
/// builder.external({ napiModule: native_plugin, symbol: 'onBeforeParse', external });
|
||||
/// },
|
||||
/// },
|
||||
/// ],
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// The external object must be created from NAPI for this function to be safe!
|
||||
///
|
||||
/// This function will return an error if the external object is not a
|
||||
/// valid tagged object for the given type.
|
||||
///
|
||||
/// This function will return `Ok(None)` if there is no external object
|
||||
/// set.
|
||||
///
|
||||
/// # Example
|
||||
/// The code to create the external from napi-rs:
|
||||
/// ```rs
|
||||
/// #[no_mangle]
|
||||
/// #[napi]
|
||||
/// pub fn create_my_external() -> External<MyStruct> {
|
||||
/// let external = External::new(MyStruct::new());
|
||||
///
|
||||
/// external
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The code to extract the external:
|
||||
/// ```rust
|
||||
/// let external = match handle.external::<MyStruct>() {
|
||||
/// Ok(Some(external)) => external,
|
||||
/// _ => {
|
||||
/// handle.log_error("Could not get external object.");
|
||||
/// return;
|
||||
/// },
|
||||
/// };
|
||||
/// ```
|
||||
pub unsafe fn external<T: 'static + Sync>(&self) -> Result<Option<&'static T>> {
|
||||
if self.args_raw.external.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let external: *mut TaggedObject<T> = self.args_raw.external as *mut TaggedObject<T>;
|
||||
|
||||
unsafe {
|
||||
if (*external).type_id != TypeId::of::<T>() {
|
||||
return Err(Error::ExternalTypeMismatch);
|
||||
}
|
||||
|
||||
Ok((*external).object.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as [`crate::bun_native_plugin::OnBeforeParse::external`], but returns a mutable reference.
|
||||
///
|
||||
/// This is unsafe as you must ensure that no other invocation of the plugin
|
||||
/// simultaneously holds a mutable reference to the external.
|
||||
pub unsafe fn external_mut<T: 'static + Sync>(&mut self) -> Result<Option<&mut T>> {
|
||||
if self.args_raw.external.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let external: *mut TaggedObject<T> = self.args_raw.external as *mut TaggedObject<T>;
|
||||
|
||||
unsafe {
|
||||
if (*external).type_id != TypeId::of::<T>() {
|
||||
return Err(Error::ExternalTypeMismatch);
|
||||
}
|
||||
|
||||
Ok((*external).object.as_mut())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the input source code for the current file.
|
||||
///
|
||||
/// On Windows, this function may return an `Err(Error::Utf8(...))` if the
|
||||
/// source code contains invalid UTF-8.
|
||||
pub fn input_source_code(&self) -> Result<Cow<'_, str>> {
|
||||
let fetch_result = unsafe {
|
||||
((*self.result_raw).fetchSourceCode.unwrap())(self.args_raw, self.result_raw)
|
||||
};
|
||||
|
||||
if fetch_result != 0 {
|
||||
Err(Error::Unknown)
|
||||
} else {
|
||||
// SAFETY: We don't hand out mutable references to `result_raw` so dereferencing here is safe.
|
||||
unsafe {
|
||||
get_from_raw_str((*self.result_raw).source_ptr, (*self.result_raw).source_len)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the output source code for the current file.
|
||||
pub fn set_output_source_code(&mut self, source: String, loader: BunLoader) {
|
||||
let source_cap = source.capacity();
|
||||
let source = source.leak();
|
||||
let source_ptr = source.as_mut_ptr();
|
||||
let source_len = source.len();
|
||||
|
||||
if self.compilation_context.is_null() {
|
||||
self.compilation_context = Box::into_raw(Box::new(SourceCodeContext {
|
||||
source_ptr,
|
||||
source_len,
|
||||
source_cap,
|
||||
}));
|
||||
|
||||
// SAFETY: We don't hand out mutable references to `result_raw` so dereferencing it is safe.
|
||||
unsafe {
|
||||
(*self.result_raw).plugin_source_code_context =
|
||||
self.compilation_context as *mut c_void;
|
||||
(*self.result_raw).free_plugin_source_code_context =
|
||||
Some(free_plugin_source_code_context);
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
// SAFETY: If we're here we know that `compilation_context` is not null.
|
||||
let context = &mut *self.compilation_context;
|
||||
|
||||
drop(String::from_raw_parts(
|
||||
context.source_ptr,
|
||||
context.source_len,
|
||||
context.source_cap,
|
||||
));
|
||||
|
||||
context.source_ptr = source_ptr;
|
||||
context.source_len = source_len;
|
||||
context.source_cap = source_cap;
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: We don't hand out mutable references to `result_raw` so dereferencing it is safe.
|
||||
unsafe {
|
||||
(*self.result_raw).loader = loader as u8;
|
||||
(*self.result_raw).source_ptr = source_ptr;
|
||||
(*self.result_raw).source_len = source_len;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the output loader for the current file.
|
||||
pub fn set_output_loader(&self, loader: BunLogLevel) {
|
||||
// SAFETY: We don't hand out mutable references to `result_raw` so dereferencing it is safe.
|
||||
unsafe {
|
||||
(*self.result_raw).loader = loader as u8;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the output loader for the current file.
|
||||
pub fn output_loader(&self) -> BunLoader {
|
||||
unsafe { std::mem::transmute((*self.result_raw).loader as u32) }
|
||||
}
|
||||
|
||||
/// Log an error message.
|
||||
pub fn log_error(&self, message: &str) {
|
||||
self.log(message, BunLogLevel::BUN_LOG_LEVEL_ERROR)
|
||||
}
|
||||
|
||||
/// Log a message with the given level.
|
||||
pub fn log(&self, message: &str, level: BunLogLevel) {
|
||||
let mut log_options = sys::BunLogOptions {
|
||||
__struct_size: std::mem::size_of::<sys::BunLogOptions>(),
|
||||
message_ptr: message.as_ptr(),
|
||||
message_len: message.len(),
|
||||
path_ptr: self.args_raw.path_ptr,
|
||||
path_len: self.args_raw.path_len,
|
||||
source_line_text_ptr: std::ptr::null(),
|
||||
source_line_text_len: 0,
|
||||
level: level as i8,
|
||||
line: 0,
|
||||
lineEnd: 0,
|
||||
column: 0,
|
||||
columnEnd: 0,
|
||||
};
|
||||
unsafe {
|
||||
((*self.result_raw).log.unwrap())(self.args_raw, &mut log_options);
|
||||
}
|
||||
}
|
||||
}
|
||||
1
packages/bun-native-plugin-rs/wrapper.h
Normal file
1
packages/bun-native-plugin-rs/wrapper.h
Normal file
@@ -0,0 +1 @@
|
||||
#include <bun-native-bundler-plugin-api/bundler_plugin.h>
|
||||
Binary file not shown.
@@ -97,6 +97,8 @@ export async function getBuild(): Promise<number> {
|
||||
}
|
||||
|
||||
export async function getSemver(tag?: string, build?: number): Promise<string> {
|
||||
const { tag_name: latest_tag_name } = await getRelease();
|
||||
const version = latest_tag_name.replace("bun-v", "");
|
||||
const { tag_name } = await getRelease(tag);
|
||||
if (tag_name !== "canary") {
|
||||
return tag_name.replace("bun-v", "");
|
||||
@@ -106,7 +108,7 @@ export async function getSemver(tag?: string, build?: number): Promise<string> {
|
||||
}
|
||||
const sha = await getSha(tag_name, "short");
|
||||
const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
|
||||
return `${Bun.version}-canary.${date}.${build}+${sha}`;
|
||||
return `${version}-canary.${date}.${build}+${sha}`;
|
||||
}
|
||||
|
||||
export function formatTag(tag: string): string {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { spawn } from "../spawn";
|
||||
import { chmod, join, rename, rm, tmp, write } from "../fs";
|
||||
import { unzipSync } from "zlib";
|
||||
import type { Platform } from "../platform";
|
||||
import { os, arch, supportedPlatforms } from "../platform";
|
||||
import { os, arch, abi, supportedPlatforms } from "../platform";
|
||||
import { debug, error } from "../console";
|
||||
|
||||
declare const version: string;
|
||||
@@ -12,7 +12,7 @@ declare const owner: string;
|
||||
|
||||
export async function importBun(): Promise<string> {
|
||||
if (!supportedPlatforms.length) {
|
||||
throw new Error(`Unsupported platform: ${os} ${arch}`);
|
||||
throw new Error(`Unsupported platform: ${os} ${arch} ${abi || ""}`);
|
||||
}
|
||||
for (const platform of supportedPlatforms) {
|
||||
try {
|
||||
@@ -121,7 +121,8 @@ async function downloadBun(platform: Platform, dst: string): Promise<void> {
|
||||
}
|
||||
|
||||
export function optimizeBun(path: string): void {
|
||||
const installScript = os === "win32" ? 'powershell -c "irm bun.sh/install.ps1 | iex"' : "curl -fsSL https://bun.sh/install | bash";
|
||||
const installScript =
|
||||
os === "win32" ? 'powershell -c "irm bun.sh/install.ps1 | iex"' : "curl -fsSL https://bun.sh/install | bash";
|
||||
try {
|
||||
rename(path, join(__dirname, "bin", "bun.exe"));
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawn } from "./spawn";
|
||||
import { read } from "./fs";
|
||||
import { exists, read } from "./fs";
|
||||
import { debug } from "./console";
|
||||
|
||||
export const os = process.platform;
|
||||
@@ -10,9 +10,12 @@ export const avx2 =
|
||||
arch === "x64" &&
|
||||
((os === "linux" && isLinuxAVX2()) || (os === "darwin" && isDarwinAVX2()) || (os === "win32" && isWindowsAVX2()));
|
||||
|
||||
export const abi = os === "linux" && isLinuxMusl() ? "musl" : undefined;
|
||||
|
||||
export type Platform = {
|
||||
os: string;
|
||||
arch: string;
|
||||
abi?: "musl";
|
||||
avx2?: boolean;
|
||||
bin: string;
|
||||
exe: string;
|
||||
@@ -57,6 +60,28 @@ export const platforms: Platform[] = [
|
||||
bin: "bun-linux-x64-baseline",
|
||||
exe: "bin/bun",
|
||||
},
|
||||
{
|
||||
os: "linux",
|
||||
arch: "aarch64",
|
||||
abi: "musl",
|
||||
bin: "bun-linux-aarch64-musl",
|
||||
exe: "bin/bun",
|
||||
},
|
||||
{
|
||||
os: "linux",
|
||||
arch: "x64",
|
||||
abi: "musl",
|
||||
avx2: true,
|
||||
bin: "bun-linux-x64-musl",
|
||||
exe: "bin/bun",
|
||||
},
|
||||
{
|
||||
os: "linux",
|
||||
arch: "x64",
|
||||
abi: "musl",
|
||||
bin: "bun-linux-x64-musl-baseline",
|
||||
exe: "bin/bun",
|
||||
},
|
||||
{
|
||||
os: "win32",
|
||||
arch: "x64",
|
||||
@@ -73,9 +98,24 @@ export const platforms: Platform[] = [
|
||||
];
|
||||
|
||||
export const supportedPlatforms: Platform[] = platforms
|
||||
.filter(platform => platform.os === os && platform.arch === arch && (!platform.avx2 || avx2))
|
||||
.filter(
|
||||
platform =>
|
||||
platform.os === os &&
|
||||
platform.arch === arch &&
|
||||
(!platform.avx2 || avx2) &&
|
||||
(!platform.abi || abi === platform.abi),
|
||||
)
|
||||
.sort((a, b) => (a.avx2 === b.avx2 ? 0 : a.avx2 ? -1 : 1));
|
||||
|
||||
function isLinuxMusl(): boolean {
|
||||
try {
|
||||
return exists("/etc/alpine-release");
|
||||
} catch (error) {
|
||||
debug("isLinuxMusl failed", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLinuxAVX2(): boolean {
|
||||
try {
|
||||
return read("/proc/cpuinfo").includes("avx2");
|
||||
|
||||
9
packages/bun-types/ambient.d.ts
vendored
Normal file
9
packages/bun-types/ambient.d.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
declare module "*.txt" {
|
||||
var text: string;
|
||||
export = text;
|
||||
}
|
||||
|
||||
declare module "*.toml" {
|
||||
var contents: any;
|
||||
export = contents;
|
||||
}
|
||||
65
packages/bun-types/bun.d.ts
vendored
65
packages/bun-types/bun.d.ts
vendored
@@ -14,6 +14,7 @@
|
||||
* This module aliases `globalThis.Bun`.
|
||||
*/
|
||||
declare module "bun" {
|
||||
import type { FFIFunctionCallableSymbol } from "bun:ffi";
|
||||
import type { Encoding as CryptoEncoding } from "crypto";
|
||||
import type { CipherNameAndProtocol, EphemeralKeyInfo, PeerCertificate } from "tls";
|
||||
interface Env {
|
||||
@@ -1552,6 +1553,26 @@ declare module "bun" {
|
||||
* https://nodejs.org/api/packages.html#exports
|
||||
*/
|
||||
conditions?: Array<string> | string;
|
||||
|
||||
/**
|
||||
* Controls how environment variables are handled during bundling.
|
||||
*
|
||||
* Can be one of:
|
||||
* - `"inline"`: Injects environment variables into the bundled output by converting `process.env.FOO`
|
||||
* references to string literals containing the actual environment variable values
|
||||
* - `"disable"`: Disables environment variable injection entirely
|
||||
* - A string ending in `*`: Inlines environment variables that match the given prefix.
|
||||
* For example, `"MY_PUBLIC_*"` will only include env vars starting with "MY_PUBLIC_"
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* Bun.build({
|
||||
* env: "MY_PUBLIC_*",
|
||||
* entrypoints: ["src/index.ts"],
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
env?: "inline" | "disable" | `${string}*`;
|
||||
minify?:
|
||||
| boolean
|
||||
| {
|
||||
@@ -3873,7 +3894,6 @@ declare module "bun" {
|
||||
* The default loader for this file extension
|
||||
*/
|
||||
loader: Loader;
|
||||
|
||||
/**
|
||||
* Defer the execution of this callback until all other modules have been parsed.
|
||||
*
|
||||
@@ -3882,7 +3902,7 @@ declare module "bun" {
|
||||
defer: () => Promise<void>;
|
||||
}
|
||||
|
||||
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined;
|
||||
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined | void;
|
||||
type OnLoadCallback = (args: OnLoadArgs) => OnLoadResult | Promise<OnLoadResult>;
|
||||
type OnStartCallback = () => void | Promise<void>;
|
||||
|
||||
@@ -3899,6 +3919,10 @@ declare module "bun" {
|
||||
* The namespace of the importer.
|
||||
*/
|
||||
namespace: string;
|
||||
/**
|
||||
* The directory to perform file-based resolutions in.
|
||||
*/
|
||||
resolveDir: string;
|
||||
/**
|
||||
* The kind of import this resolve is for.
|
||||
*/
|
||||
@@ -3928,7 +3952,30 @@ declare module "bun" {
|
||||
args: OnResolveArgs,
|
||||
) => OnResolveResult | Promise<OnResolveResult | undefined | null> | undefined | null;
|
||||
|
||||
type FFIFunctionCallable = Function & {
|
||||
// Making a nominally typed function so that the user must get it from dlopen
|
||||
readonly __ffi_function_callable: typeof FFIFunctionCallableSymbol;
|
||||
};
|
||||
|
||||
interface PluginBuilder {
|
||||
/**
|
||||
* Register a callback which will be invoked when bundling starts.
|
||||
* @example
|
||||
* ```ts
|
||||
* Bun.plugin({
|
||||
* setup(builder) {
|
||||
* builder.onStart(() => {
|
||||
* console.log("bundle just started!!")
|
||||
* });
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
onStart(callback: OnStartCallback): void;
|
||||
onBeforeParse(
|
||||
constraints: PluginConstraints,
|
||||
callback: { napiModule: unknown; symbol: string; external?: unknown | undefined },
|
||||
): void;
|
||||
/**
|
||||
* Register a callback to load imports with a specific import specifier
|
||||
* @param constraints The constraints to apply the plugin to
|
||||
@@ -3961,20 +4008,6 @@ declare module "bun" {
|
||||
* ```
|
||||
*/
|
||||
onResolve(constraints: PluginConstraints, callback: OnResolveCallback): void;
|
||||
/**
|
||||
* Register a callback which will be invoked when bundling starts.
|
||||
* @example
|
||||
* ```ts
|
||||
* Bun.plugin({
|
||||
* setup(builder) {
|
||||
* builder.onStart(() => {
|
||||
* console.log("bundle just started!!")
|
||||
* });
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
onStart(callback: OnStartCallback): void;
|
||||
/**
|
||||
* The config object passed to `Bun.build` as is. Can be mutated.
|
||||
*/
|
||||
|
||||
24
packages/bun-types/ffi.d.ts
vendored
24
packages/bun-types/ffi.d.ts
vendored
@@ -566,17 +566,21 @@ declare module "bun:ffi" {
|
||||
|
||||
type ToFFIType<T extends FFITypeOrString> = T extends FFIType ? T : T extends string ? FFITypeStringToType[T] : never;
|
||||
|
||||
const FFIFunctionCallableSymbol: unique symbol;
|
||||
type ConvertFns<Fns extends Symbols> = {
|
||||
[K in keyof Fns]: (
|
||||
...args: Fns[K]["args"] extends infer A extends readonly FFITypeOrString[]
|
||||
? { [L in keyof A]: FFITypeToArgsType[ToFFIType<A[L]>] }
|
||||
: // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
|
||||
[unknown] extends [Fns[K]["args"]]
|
||||
? []
|
||||
: never
|
||||
) => [unknown] extends [Fns[K]["returns"]] // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
|
||||
? undefined
|
||||
: FFITypeToReturnsType[ToFFIType<NonNullable<Fns[K]["returns"]>>];
|
||||
[K in keyof Fns]: {
|
||||
(
|
||||
...args: Fns[K]["args"] extends infer A extends readonly FFITypeOrString[]
|
||||
? { [L in keyof A]: FFITypeToArgsType[ToFFIType<A[L]>] }
|
||||
: // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
|
||||
[unknown] extends [Fns[K]["args"]]
|
||||
? []
|
||||
: never
|
||||
): [unknown] extends [Fns[K]["returns"]] // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
|
||||
? undefined
|
||||
: FFITypeToReturnsType[ToFFIType<NonNullable<Fns[K]["returns"]>>];
|
||||
__ffi_function_callable: typeof FFIFunctionCallableSymbol;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
16
packages/bun-types/globals.d.ts
vendored
16
packages/bun-types/globals.d.ts
vendored
@@ -1,5 +1,3 @@
|
||||
export {};
|
||||
|
||||
type _ReadableStream<T> = typeof globalThis extends {
|
||||
onerror: any;
|
||||
ReadableStream: infer T;
|
||||
@@ -141,16 +139,6 @@ import type { TextDecoder as NodeTextDecoder, TextEncoder as NodeTextEncoder } f
|
||||
import type { MessagePort } from "worker_threads";
|
||||
import type { WebSocket as _WebSocket } from "ws";
|
||||
|
||||
declare module "*.txt" {
|
||||
var text: string;
|
||||
export = text;
|
||||
}
|
||||
|
||||
declare module "*.toml" {
|
||||
var contents: any;
|
||||
export = contents;
|
||||
}
|
||||
|
||||
declare global {
|
||||
var Bun: typeof import("bun");
|
||||
|
||||
@@ -1835,10 +1823,10 @@ declare global {
|
||||
readonly main: boolean;
|
||||
|
||||
/** Alias of `import.meta.dir`. Exists for Node.js compatibility */
|
||||
readonly dirname: string;
|
||||
dirname: string;
|
||||
|
||||
/** Alias of `import.meta.path`. Exists for Node.js compatibility */
|
||||
readonly filename: string;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
1
packages/bun-types/index.d.ts
vendored
1
packages/bun-types/index.d.ts
vendored
@@ -20,3 +20,4 @@
|
||||
/// <reference path="./sqlite.d.ts" />
|
||||
/// <reference path="./wasm.d.ts" />
|
||||
/// <reference path="./deprecated.d.ts" />
|
||||
/// <reference path="./ambient.d.ts" />
|
||||
|
||||
2
packages/bun-types/sqlite.d.ts
vendored
2
packages/bun-types/sqlite.d.ts
vendored
@@ -1127,7 +1127,7 @@ declare module "bun:sqlite" {
|
||||
*
|
||||
* @since Bun v1.1.14
|
||||
*/
|
||||
interface Changes {
|
||||
export interface Changes {
|
||||
/**
|
||||
* The number of rows changed by the last `run` or `exec` call.
|
||||
*/
|
||||
|
||||
51
packages/bun-types/test.d.ts
vendored
51
packages/bun-types/test.d.ts
vendored
@@ -1295,6 +1295,57 @@ declare module "bun:test" {
|
||||
* @param hint Hint used to identify the snapshot in the snapshot file.
|
||||
*/
|
||||
toMatchSnapshot(propertyMatchers?: object, hint?: string): void;
|
||||
/**
|
||||
* Asserts that a value matches the most recent inline snapshot.
|
||||
*
|
||||
* @example
|
||||
* expect("Hello").toMatchInlineSnapshot();
|
||||
* expect("Hello").toMatchInlineSnapshot(`"Hello"`);
|
||||
*
|
||||
* @param value The latest automatically-updated snapshot value.
|
||||
*/
|
||||
toMatchInlineSnapshot(value?: string): void;
|
||||
/**
|
||||
* Asserts that a value matches the most recent inline snapshot.
|
||||
*
|
||||
* @example
|
||||
* expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) });
|
||||
* expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) }, `
|
||||
* {
|
||||
* "v": Any<Date>,
|
||||
* }
|
||||
* `);
|
||||
*
|
||||
* @param propertyMatchers Object containing properties to match against the value.
|
||||
* @param value The latest automatically-updated snapshot value.
|
||||
*/
|
||||
toMatchInlineSnapshot(propertyMatchers?: object, value?: string): void;
|
||||
/**
|
||||
* Asserts that a function throws an error matching the most recent snapshot.
|
||||
*
|
||||
* @example
|
||||
* function fail() {
|
||||
* throw new Error("Oops!");
|
||||
* }
|
||||
* expect(fail).toThrowErrorMatchingSnapshot();
|
||||
* expect(fail).toThrowErrorMatchingSnapshot("This one should say Oops!");
|
||||
*
|
||||
* @param value The latest automatically-updated snapshot value.
|
||||
*/
|
||||
toThrowErrorMatchingSnapshot(hint?: string): void;
|
||||
/**
|
||||
* Asserts that a function throws an error matching the most recent snapshot.
|
||||
*
|
||||
* @example
|
||||
* function fail() {
|
||||
* throw new Error("Oops!");
|
||||
* }
|
||||
* expect(fail).toThrowErrorMatchingInlineSnapshot();
|
||||
* expect(fail).toThrowErrorMatchingInlineSnapshot(`"Oops!"`);
|
||||
*
|
||||
* @param value The latest automatically-updated snapshot value.
|
||||
*/
|
||||
toThrowErrorMatchingInlineSnapshot(value?: string): void;
|
||||
/**
|
||||
* Asserts that an object matches a subset of properties.
|
||||
*
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CString, dlopen, FFIType, Pointer, read, suffix } from "bun:ffi";
|
||||
import { CString, dlopen, FFIType, JSCallback, Pointer, read, suffix } from "bun:ffi";
|
||||
import * as tsd from "./utilities.test";
|
||||
|
||||
// `suffix` is either "dylib", "so", or "dll" depending on the platform
|
||||
@@ -62,12 +62,14 @@ const lib = dlopen(
|
||||
},
|
||||
);
|
||||
|
||||
declare const ptr: Pointer;
|
||||
|
||||
tsd.expectType<CString>(lib.symbols.sqlite3_libversion());
|
||||
tsd.expectType<number>(lib.symbols.add(1, 2));
|
||||
|
||||
tsd.expectType<Pointer | null>(lib.symbols.ptr_type(0));
|
||||
tsd.expectType<Pointer | null>(lib.symbols.ptr_type(ptr));
|
||||
|
||||
tsd.expectType<Pointer | null>(lib.symbols.fn_type(0));
|
||||
tsd.expectType<Pointer | null>(lib.symbols.fn_type(new JSCallback(() => {}, {})));
|
||||
|
||||
function _arg(
|
||||
...params: [
|
||||
@@ -166,16 +168,16 @@ tsd.expectType<void>(lib2.symbols.multi_args(1, 2));
|
||||
tsd.expectTypeEquals<ReturnType<(typeof lib2)["symbols"]["no_returns"]>, undefined>(true);
|
||||
tsd.expectTypeEquals<Parameters<(typeof lib2)["symbols"]["no_args"]>, []>(true);
|
||||
|
||||
tsd.expectType<number>(read.u8(0));
|
||||
tsd.expectType<number>(read.u8(0, 0));
|
||||
tsd.expectType<number>(read.i8(0, 0));
|
||||
tsd.expectType<number>(read.u16(0, 0));
|
||||
tsd.expectType<number>(read.i16(0, 0));
|
||||
tsd.expectType<number>(read.u32(0, 0));
|
||||
tsd.expectType<number>(read.i32(0, 0));
|
||||
tsd.expectType<bigint>(read.u64(0, 0));
|
||||
tsd.expectType<bigint>(read.i64(0, 0));
|
||||
tsd.expectType<number>(read.f32(0, 0));
|
||||
tsd.expectType<number>(read.f64(0, 0));
|
||||
tsd.expectType<number>(read.ptr(0, 0));
|
||||
tsd.expectType<number>(read.intptr(0, 0));
|
||||
tsd.expectType<number>(read.u8(ptr));
|
||||
tsd.expectType<number>(read.u8(ptr, 0));
|
||||
tsd.expectType<number>(read.i8(ptr, 0));
|
||||
tsd.expectType<number>(read.u16(ptr, 0));
|
||||
tsd.expectType<number>(read.i16(ptr, 0));
|
||||
tsd.expectType<number>(read.u32(ptr, 0));
|
||||
tsd.expectType<number>(read.i32(ptr, 0));
|
||||
tsd.expectType<bigint>(read.u64(ptr, 0));
|
||||
tsd.expectType<bigint>(read.i64(ptr, 0));
|
||||
tsd.expectType<number>(read.f32(ptr, 0));
|
||||
tsd.expectType<number>(read.f64(ptr, 0));
|
||||
tsd.expectType<number>(read.ptr(ptr, 0));
|
||||
tsd.expectType<number>(read.intptr(ptr, 0));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { Changes, Database } from "bun:sqlite";
|
||||
import { expectType } from "./utilities.test";
|
||||
|
||||
const db = new Database(":memory:");
|
||||
@@ -22,7 +22,7 @@ expectType<Array<{ name: string; dob: number }>>(allResults);
|
||||
expectType<{ name: string; dob: number } | null>(getResults);
|
||||
// tslint:disable-next-line:invalid-void
|
||||
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
|
||||
expectType<void>(runResults);
|
||||
expectType<Changes>(runResults);
|
||||
|
||||
const query3 = db.prepare<
|
||||
{ name: string; dob: number }, // return type first
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext"],
|
||||
"skipLibCheck": false,
|
||||
"strict": true,
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"disableSolutionSearching": true,
|
||||
"noUnusedLocals": true,
|
||||
"noEmit": true,
|
||||
"resolveJsonModule": true
|
||||
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"noEmit": false,
|
||||
"declarationDir": "out"
|
||||
},
|
||||
"files": ["ambient.d.ts"], // ambient defines .txt and .toml loaders
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
|
||||
@@ -623,18 +623,34 @@ inline __attribute__((always_inline)) LIBUS_SOCKET_DESCRIPTOR bsd_bind_listen_fd
|
||||
setsockopt(listenFd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &optval2, sizeof(optval2));
|
||||
#endif
|
||||
} else {
|
||||
#if defined(SO_REUSEPORT)
|
||||
int optval2 = 1;
|
||||
setsockopt(listenFd, SOL_SOCKET, SO_REUSEPORT, (void *) &optval2, sizeof(optval2));
|
||||
#endif
|
||||
#if defined(SO_REUSEPORT)
|
||||
if((options & LIBUS_LISTEN_REUSE_PORT)) {
|
||||
int optval2 = 1;
|
||||
setsockopt(listenFd, SOL_SOCKET, SO_REUSEPORT, (void *) &optval2, sizeof(optval2));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(SO_REUSEADDR)
|
||||
#ifndef _WIN32
|
||||
|
||||
// Unlike on Unix, here we don't set SO_REUSEADDR, because it doesn't just
|
||||
// allow binding to addresses that are in use by sockets in TIME_WAIT, it
|
||||
// effectively allows 'stealing' a port which is in use by another application.
|
||||
// See libuv issue #1360.
|
||||
|
||||
|
||||
int optval3 = 1;
|
||||
setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, (void *) &optval3, sizeof(optval3));
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef IPV6_V6ONLY
|
||||
// TODO: revise support to match node.js
|
||||
// if (listenAddr->ai_family == AF_INET6) {
|
||||
// int disabled = (options & LIBUS_SOCKET_IPV6_ONLY) != 0;
|
||||
// setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &disabled, sizeof(disabled));
|
||||
// }
|
||||
int disabled = 0;
|
||||
setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &disabled, sizeof(disabled));
|
||||
#endif
|
||||
@@ -949,8 +965,10 @@ int bsd_connect_udp_socket(LIBUS_SOCKET_DESCRIPTOR fd, const char *host, int por
|
||||
char port_string[16];
|
||||
snprintf(port_string, 16, "%d", port);
|
||||
|
||||
if (getaddrinfo(host, port_string, &hints, &result)) {
|
||||
return -1;
|
||||
int gai_error = getaddrinfo(host, port_string, &hints, &result);
|
||||
|
||||
if (gai_error != 0) {
|
||||
return gai_error;
|
||||
}
|
||||
|
||||
if (result == NULL) {
|
||||
|
||||
@@ -1858,9 +1858,6 @@ ssl_wrapped_context_on_close(struct us_internal_ssl_socket_t *s, int code,
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
|
||||
if (wrapped_context->events.on_close) {
|
||||
wrapped_context->events.on_close((struct us_socket_t *)s, code, reason);
|
||||
}
|
||||
|
||||
// writting here can cause the context to not be writable anymore but its the
|
||||
// user responsability to check for that
|
||||
@@ -1868,6 +1865,10 @@ ssl_wrapped_context_on_close(struct us_internal_ssl_socket_t *s, int code,
|
||||
wrapped_context->old_events.on_close((struct us_socket_t *)s, code, reason);
|
||||
}
|
||||
|
||||
if (wrapped_context->events.on_close) {
|
||||
wrapped_context->events.on_close((struct us_socket_t *)s, code, reason);
|
||||
}
|
||||
|
||||
us_socket_context_unref(0, wrapped_context->tcp_context);
|
||||
return s;
|
||||
}
|
||||
@@ -1880,9 +1881,6 @@ ssl_wrapped_context_on_writable(struct us_internal_ssl_socket_t *s) {
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
|
||||
if (wrapped_context->events.on_writable) {
|
||||
wrapped_context->events.on_writable((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
// writting here can cause the context to not be writable anymore but its the
|
||||
// user responsability to check for that
|
||||
@@ -1890,6 +1888,10 @@ ssl_wrapped_context_on_writable(struct us_internal_ssl_socket_t *s) {
|
||||
wrapped_context->old_events.on_writable((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->events.on_writable) {
|
||||
wrapped_context->events.on_writable((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -1916,14 +1918,14 @@ ssl_wrapped_context_on_timeout(struct us_internal_ssl_socket_t *s) {
|
||||
struct us_wrapped_socket_context_t *wrapped_context =
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
if (wrapped_context->old_events.on_timeout) {
|
||||
wrapped_context->old_events.on_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->events.on_timeout) {
|
||||
wrapped_context->events.on_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->old_events.on_timeout) {
|
||||
wrapped_context->old_events.on_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
@@ -1935,15 +1937,14 @@ ssl_wrapped_context_on_long_timeout(struct us_internal_ssl_socket_t *s) {
|
||||
struct us_wrapped_socket_context_t *wrapped_context =
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
if (wrapped_context->old_events.on_long_timeout) {
|
||||
wrapped_context->old_events.on_long_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->events.on_long_timeout) {
|
||||
wrapped_context->events.on_long_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->old_events.on_long_timeout) {
|
||||
wrapped_context->old_events.on_long_timeout((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -1954,14 +1955,13 @@ ssl_wrapped_context_on_end(struct us_internal_ssl_socket_t *s) {
|
||||
struct us_wrapped_socket_context_t *wrapped_context =
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
|
||||
if (wrapped_context->events.on_end) {
|
||||
wrapped_context->events.on_end((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
if (wrapped_context->old_events.on_end) {
|
||||
wrapped_context->old_events.on_end((struct us_socket_t *)s);
|
||||
}
|
||||
if (wrapped_context->events.on_end) {
|
||||
wrapped_context->events.on_end((struct us_socket_t *)s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -1973,13 +1973,13 @@ ssl_wrapped_on_connect_error(struct us_internal_ssl_socket_t *s, int code) {
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
|
||||
if (wrapped_context->old_events.on_connect_error) {
|
||||
wrapped_context->old_events.on_connect_error((struct us_connecting_socket_t *)s, code);
|
||||
}
|
||||
if (wrapped_context->events.on_connect_error) {
|
||||
wrapped_context->events.on_connect_error((struct us_connecting_socket_t *)s, code);
|
||||
}
|
||||
|
||||
if (wrapped_context->old_events.on_connect_error) {
|
||||
wrapped_context->old_events.on_connect_error((struct us_connecting_socket_t *)s, code);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -1990,14 +1990,14 @@ ssl_wrapped_on_socket_connect_error(struct us_internal_ssl_socket_t *s, int code
|
||||
struct us_wrapped_socket_context_t *wrapped_context =
|
||||
(struct us_wrapped_socket_context_t *)us_internal_ssl_socket_context_ext(
|
||||
context);
|
||||
|
||||
if (wrapped_context->old_events.on_connecting_socket_error) {
|
||||
wrapped_context->old_events.on_connecting_socket_error((struct us_socket_t *)s, code);
|
||||
}
|
||||
if (wrapped_context->events.on_connecting_socket_error) {
|
||||
wrapped_context->events.on_connecting_socket_error((struct us_socket_t *)s, code);
|
||||
}
|
||||
|
||||
if (wrapped_context->old_events.on_connecting_socket_error) {
|
||||
wrapped_context->old_events.on_connecting_socket_error((struct us_socket_t *)s, code);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -2153,6 +2153,8 @@ us_socket_context_on_socket_connect_error(
|
||||
socket->ssl_read_wants_write = 0;
|
||||
socket->fatal_error = 0;
|
||||
socket->handshake_state = HANDSHAKE_PENDING;
|
||||
// always resume the socket
|
||||
us_socket_resume(1, &socket->s);
|
||||
return socket;
|
||||
}
|
||||
|
||||
|
||||
@@ -96,6 +96,10 @@ enum {
|
||||
LIBUS_LISTEN_EXCLUSIVE_PORT = 1,
|
||||
/* Allow socket to keep writing after readable side closes */
|
||||
LIBUS_SOCKET_ALLOW_HALF_OPEN = 2,
|
||||
/* Setting reusePort allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+*/
|
||||
LIBUS_LISTEN_REUSE_PORT = 4,
|
||||
/* etting ipv6Only will disable dual-stack support, i.e., binding to host :: won't make 0.0.0.0 be bound.*/
|
||||
LIBUS_SOCKET_IPV6_ONLY = 8,
|
||||
};
|
||||
|
||||
/* Library types publicly available */
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <sys/ioctl.h>
|
||||
#endif
|
||||
|
||||
|
||||
/* The loop has 2 fallthrough polls */
|
||||
void us_internal_loop_data_init(struct us_loop_t *loop, void (*wakeup_cb)(struct us_loop_t *loop),
|
||||
void (*pre_cb)(struct us_loop_t *loop), void (*post_cb)(struct us_loop_t *loop)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bun-vscode",
|
||||
"version": "0.0.19",
|
||||
"version": "0.0.22",
|
||||
"author": "oven",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -21,7 +21,6 @@
|
||||
"activationEvents": [
|
||||
"onStartupFinished"
|
||||
],
|
||||
"browser": "dist/web-extension.js",
|
||||
"bugs": {
|
||||
"url": "https://github.com/oven-sh/bun/issues"
|
||||
},
|
||||
@@ -46,6 +45,18 @@
|
||||
"scope": "window",
|
||||
"default": null
|
||||
},
|
||||
"bun.diagnosticsSocket.enabled": {
|
||||
"type": "boolean",
|
||||
"description": "If Bun extension should communicate with Bun over a socket to show errors in editor.",
|
||||
"scope": "window",
|
||||
"default": true
|
||||
},
|
||||
"bun.bunlockb.enabled": {
|
||||
"type": "boolean",
|
||||
"description": "If visual lockfile viewer (`bun.lockb`) should be enabled ",
|
||||
"scope": "window",
|
||||
"default": true
|
||||
},
|
||||
"bun.debugTerminal.enabled": {
|
||||
"type": "boolean",
|
||||
"description": "If Bun should be added to the JavaScript Debug Terminal.",
|
||||
@@ -321,7 +332,7 @@
|
||||
]
|
||||
},
|
||||
"description": "The Visual Studio Code extension for Bun.",
|
||||
"displayName": "Bun for Visual Studio Code",
|
||||
"displayName": "Bun",
|
||||
"engines": {
|
||||
"vscode": "^1.60.0"
|
||||
},
|
||||
@@ -358,4 +369,4 @@
|
||||
"../bun-debug-adapter-protocol",
|
||||
"../bun-inspector-protocol"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -53,3 +53,7 @@ export function activate(context: vscode.ExtensionContext) {
|
||||
// Only register for text editors
|
||||
context.subscriptions.push(vscode.commands.registerTextEditorCommand("extension.bun.runUnsavedCode", runUnsavedCode));
|
||||
}
|
||||
|
||||
export function getConfig<T>(path: string, scope?: vscode.ConfigurationScope) {
|
||||
return vscode.workspace.getConfiguration("bun", scope).get<T>(path);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
UnixSignal,
|
||||
WebSocketDebugAdapter,
|
||||
} from "../../../bun-debug-adapter-protocol";
|
||||
import { getConfig } from "../extension";
|
||||
|
||||
export const DEBUG_CONFIGURATION: vscode.DebugConfiguration = {
|
||||
type: "bun",
|
||||
@@ -120,6 +121,7 @@ async function injectDebugTerminal(terminal: vscode.Terminal): Promise<void> {
|
||||
...env,
|
||||
"BUN_INSPECT": `${adapter.url}?${query}`,
|
||||
"BUN_INSPECT_NOTIFY": signal.url,
|
||||
BUN_INSPECT_CONNECT_TO: "",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -351,6 +353,7 @@ class TerminalDebugSession extends FileDebugSession {
|
||||
env: {
|
||||
"BUN_INSPECT": `${this.adapter.url}?wait=1`,
|
||||
"BUN_INSPECT_NOTIFY": this.signal.url,
|
||||
BUN_INSPECT_CONNECT_TO: "",
|
||||
},
|
||||
isTransient: true,
|
||||
iconPath: new vscode.ThemeIcon("debug-console"),
|
||||
@@ -370,10 +373,6 @@ function getRuntime(scope?: vscode.ConfigurationScope): string {
|
||||
return "bun";
|
||||
}
|
||||
|
||||
function getConfig<T>(path: string, scope?: vscode.ConfigurationScope) {
|
||||
return vscode.workspace.getConfiguration("bun", scope).get<T>(path);
|
||||
}
|
||||
|
||||
export async function runUnsavedCode() {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor || !editor.document.isUntitled) return;
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import { Socket } from "node:net";
|
||||
import * as os from "node:os";
|
||||
import { inspect } from "node:util";
|
||||
import * as vscode from "vscode";
|
||||
import {
|
||||
getAvailablePort,
|
||||
getRandomId,
|
||||
NodeSocketDebugAdapter,
|
||||
TCPSocketSignal,
|
||||
UnixSignal,
|
||||
WebSocketDebugAdapter,
|
||||
} from "../../../../bun-debug-adapter-protocol";
|
||||
import type { JSC } from "../../../../bun-inspector-protocol";
|
||||
import { createGlobalStateGenerationFn, typedGlobalState } from "../../global-state";
|
||||
import { typedGlobalState } from "../../global-state";
|
||||
import { getConfig } from "../../extension";
|
||||
|
||||
const output = vscode.window.createOutputChannel("Bun - Diagnostics");
|
||||
|
||||
@@ -70,15 +71,14 @@ class BunDiagnosticsManager {
|
||||
private readonly editorState: EditorStateManager;
|
||||
private readonly signal: UnixSignal | TCPSocketSignal;
|
||||
private readonly context: vscode.ExtensionContext;
|
||||
public readonly inspectUrl: string;
|
||||
|
||||
public get notifyUrl() {
|
||||
public get signalUrl() {
|
||||
return this.signal.url;
|
||||
}
|
||||
|
||||
private static async getOrRecreateSignal(context: vscode.ExtensionContext) {
|
||||
const globalState = typedGlobalState(context.globalState);
|
||||
const existing = globalState.get("BUN_INSPECT_NOTIFY");
|
||||
const existing = globalState.get("BUN_INSPECT_CONNECT_TO");
|
||||
|
||||
const isWin = os.platform() === "win32";
|
||||
|
||||
@@ -102,7 +102,7 @@ class BunDiagnosticsManager {
|
||||
if (isWin) {
|
||||
const port = await getAvailablePort();
|
||||
|
||||
await globalState.update("BUN_INSPECT_NOTIFY", {
|
||||
await globalState.update("BUN_INSPECT_CONNECT_TO", {
|
||||
type: "tcp",
|
||||
port,
|
||||
});
|
||||
@@ -113,7 +113,7 @@ class BunDiagnosticsManager {
|
||||
} else {
|
||||
const signal = new UnixSignal();
|
||||
|
||||
await globalState.update("BUN_INSPECT_NOTIFY", {
|
||||
await globalState.update("BUN_INSPECT_CONNECT_TO", {
|
||||
type: "unix",
|
||||
url: signal.url,
|
||||
});
|
||||
@@ -124,30 +124,29 @@ class BunDiagnosticsManager {
|
||||
}
|
||||
}
|
||||
|
||||
private static getOrCreateOldVersionInspectURL = createGlobalStateGenerationFn(
|
||||
"DIAGNOSTICS_BUN_INSPECT",
|
||||
async () => {
|
||||
const url =
|
||||
process.platform === "win32"
|
||||
? `ws://127.0.0.1:${await getAvailablePort()}/${getRandomId()}`
|
||||
: `ws+unix://${os.tmpdir()}/${getRandomId()}.sock`;
|
||||
// private static getOrCreateOldVersionInspectURL = createGlobalStateGenerationFn(
|
||||
// "DIAGNOSTICS_BUN_INSPECT",
|
||||
// async () => {
|
||||
// const url =
|
||||
// process.platform === "win32"
|
||||
// ? `ws://127.0.0.1:${await getAvailablePort()}/${getRandomId()}`
|
||||
// : `ws+unix://${os.tmpdir()}/${getRandomId()}.sock`;
|
||||
|
||||
return url;
|
||||
},
|
||||
);
|
||||
// return url;
|
||||
// },
|
||||
// );
|
||||
|
||||
public static async initialize(context: vscode.ExtensionContext) {
|
||||
const signal = await BunDiagnosticsManager.getOrRecreateSignal(context);
|
||||
const oldVersionInspectURL = await BunDiagnosticsManager.getOrCreateOldVersionInspectURL(context.globalState);
|
||||
|
||||
return new BunDiagnosticsManager(context, signal, oldVersionInspectURL);
|
||||
return new BunDiagnosticsManager(context, signal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when Bun pings BUN_INSPECT_NOTIFY (indicating a program has started).
|
||||
*/
|
||||
private async handleSocketConnection() {
|
||||
const debugAdapter = new WebSocketDebugAdapter(this.inspectUrl);
|
||||
private async handleSocketConnection(socket: Socket) {
|
||||
const debugAdapter = new NodeSocketDebugAdapter(socket);
|
||||
|
||||
this.editorState.clearAll("A new socket connected");
|
||||
|
||||
@@ -246,15 +245,10 @@ class BunDiagnosticsManager {
|
||||
});
|
||||
}
|
||||
|
||||
private constructor(
|
||||
context: vscode.ExtensionContext,
|
||||
signal: UnixSignal | TCPSocketSignal,
|
||||
oldVersionInspectURL: string,
|
||||
) {
|
||||
private constructor(context: vscode.ExtensionContext, signal: UnixSignal | TCPSocketSignal) {
|
||||
this.editorState = new EditorStateManager();
|
||||
this.signal = signal;
|
||||
this.context = context;
|
||||
this.inspectUrl = oldVersionInspectURL;
|
||||
|
||||
this.context.subscriptions.push(
|
||||
// on did type
|
||||
@@ -263,9 +257,7 @@ class BunDiagnosticsManager {
|
||||
}),
|
||||
);
|
||||
|
||||
this.signal.on("Signal.received", () => {
|
||||
this.handleSocketConnection();
|
||||
});
|
||||
this.signal.on("Signal.Socket.connect", this.handleSocketConnection.bind(this));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,12 +266,14 @@ const description = new vscode.MarkdownString(
|
||||
);
|
||||
|
||||
export async function registerDiagnosticsSocket(context: vscode.ExtensionContext) {
|
||||
context.environmentVariableCollection.clear();
|
||||
context.environmentVariableCollection.description = description;
|
||||
|
||||
if (!getConfig("diagnosticsSocket.enabled")) return;
|
||||
|
||||
const manager = await BunDiagnosticsManager.initialize(context);
|
||||
|
||||
context.environmentVariableCollection.replace("BUN_INSPECT_NOTIFY", manager.notifyUrl);
|
||||
context.environmentVariableCollection.replace("BUN_INSPECT", `${manager.inspectUrl}?report=1?wait=1`); // Intentionally invalid query params
|
||||
context.environmentVariableCollection.replace("BUN_INSPECT_CONNECT_TO", manager.signalUrl);
|
||||
|
||||
context.subscriptions.push(manager);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import * as vscode from "vscode";
|
||||
import { styleLockfile } from "./lockfile.style";
|
||||
import { getConfig } from "../../extension";
|
||||
|
||||
export type BunLockfile = vscode.CustomDocument & {
|
||||
readonly preview: string;
|
||||
@@ -36,6 +37,11 @@ export class BunLockfileEditorProvider implements vscode.CustomReadonlyEditorPro
|
||||
}
|
||||
|
||||
function renderLockfile({ webview }: vscode.WebviewPanel, preview: string, extensionUri: vscode.Uri): void {
|
||||
if (!getConfig("bunlockb.enabled")) {
|
||||
webview.html = "<code>bun.bunlockb</code> config option is disabled."
|
||||
return
|
||||
}
|
||||
|
||||
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "assets", "vscode.css"));
|
||||
const lockfileContent = styleLockfile(preview);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import * as vscode from "vscode";
|
||||
import { debugCommand } from "../debug";
|
||||
import { BunTask } from "./tasks";
|
||||
import { getConfig } from "../../extension";
|
||||
|
||||
/**
|
||||
* Parses tasks defined in the package.json.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user