Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bun): Add bun adapter #1059

Merged
merged 5 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/start-bun/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# start-bun

Adapter for Solid apps that builds a Bun server.

This is very experimental; the adapter API isn't at all fleshed out, and things will definitely change.
84 changes: 84 additions & 0 deletions packages/start-bun/entry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//@ts-check
import fs from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

//@ts-ignore It will be generated when building.
import manifest from "../../dist/public/route-manifest.json";
//@ts-ignore It will be generated when building.
import handler from "./entry-server.js";

const { PORT = 3000 } = process.env;

const __dirname = dirname(fileURLToPath(import.meta.url));
const paths = {
assets: join(__dirname, "/public")
};

const hasAssets = fs.existsSync(paths.assets);
const assetsWebPath = "/assets/";

const env = { manifest };

const server = Bun.serve({
port: PORT,
async fetch(req) {
const { pathname } = new URL(req.url);

/**
* @param {string} assetPath
*/
env.getStaticHTML = async assetPath => {
let text = Bun.file(join(paths.assets, `${assetPath}.html`));
return new Response(text, {
headers: {
"content-type": "text/html"
}
});
};

function internalFetch(route, init = {}) {
if (route.startsWith("http")) {
return fetch(route, init);
}

let url = new URL(route, "http://internal");
const request = new Request(url.href, init);
console.log("[internal]", req.method, url.href);
return handler({
request: request,
httpServer: server,
clientAddress: "0.0.0.0", // FIXME
locals: {},
env,
fetch: internalFetch
});
}

if (hasAssets && pathname.startsWith(assetsWebPath)) {
try {
const assetFile = Bun.file(join(paths.assets, pathname));
const blob = await assetFile.arrayBuffer();
return new Response(blob, {
headers: {
"content-type": assetFile.type,
"cache-control": "public, max-age=31536000, immutable"
}
});
} catch (e) {
console.log("[assets] not found: %s", pathname);
}
}

const response = await handler({
request: req,
httpServer: server,
clientAddress: "0.0.0.0", // FIXME
locals: {},
env,
fetch: internalFetch
});

return response;
},
});
60 changes: 60 additions & 0 deletions packages/start-bun/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import common from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import nodeResolve from "@rollup/plugin-node-resolve";
import { readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import { rollup } from "rollup";
import { createAdapter } from "solid-start/vite";
import { fileURLToPath, pathToFileURL } from "url";

export default function bunAdapter() {
return createAdapter({
name: "bun",
start: (config, { port }) => {
process.env.PORT = port;
import(pathToFileURL(join(config.root, "dist", "server.js")).toString());
return `http://localhost:${process.env.PORT}`;
},
async build(config, builder) {
const ssrExternal = config?.ssr?.external || [];
const __dirname = dirname(fileURLToPath(import.meta.url));

if (!config.solidOptions.ssr) {
await builder.spaClient(join(config.root, "dist", "public"));
await builder.server(join(config.root, ".solid", "server"));
} else if (config.solidOptions.experimental.islands) {
await builder.islandsClient(join(config.root, "dist", "public"));
await builder.server(join(config.root, ".solid", "server"));
} else {
await builder.client(join(config.root, "dist", "public"));
await builder.server(join(config.root, ".solid", "server"));
}

let text = readFileSync(join(__dirname, "entry.js")).toString();

writeFileSync(join(config.root, ".solid", "server", "server.js"), text);

builder.debug(`bundling server with rollup`);

const bundle = await rollup({
input: join(config.root, ".solid", "server", "server.js"),
plugins: [
json(),
nodeResolve({
preferBuiltins: true,
exportConditions: ["node", "solid"]
}),
common({ strictRequires: true, ...config.build.commonjsOptions })
],
external: ["stream/web", ...ssrExternal]
});
// or write the bundle to disk
await bundle.write({ format: "esm", dir: join(config.root, "dist") });

// closes the bundle
await bundle.close();

builder.debug(`bundling server done`);
}
});
}
24 changes: 24 additions & 0 deletions packages/start-bun/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "solid-start-bun",
"version": "0.3.5",
"main": "./index.js",
"type": "module",
"solid": {
"type": "adapter"
},
"dependencies": {
"@rollup/plugin-commonjs": "^24.1.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.1.0",
"rollup": "^3.26.2"
},
"devDependencies": {
"bun-types": "^1.0.1",
"solid-start": "workspace:*",
"vite": "^4.4.6"
},
"peerDependencies": {
"solid-start": "*",
"vite": "*"
}
}
15 changes: 14 additions & 1 deletion packages/start/vite/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -632,14 +632,27 @@ const findAny = (path, name, exts = [".js", ".ts", ".jsx", ".tsx", ".mjs", ".mts
return null;
};

const findAdapter = () => {
if (process.env.START_ADAPTER) {
return process.env.START_ADAPTER;
}

// https://bun.sh/guides/util/detect-bun
if (process.versions.bun) {
return "solid-start-bun";
}

return "solid-start-node";
}

/**
* @param {import('./plugin').Options} options
* @returns {import('vite').PluginOption[]}
*/
export default function solidStart(options) {
options = Object.assign(
{
adapter: process.env.START_ADAPTER ? process.env.START_ADAPTER : "solid-start-node",
adapter: findAdapter(),
appRoot: "src",
routesDir: "routes",
ssr:
Expand Down
Loading
Loading