Skip to content

Commit

Permalink
Upgrade esbuild and rewrite its build scripts after major breaking ch…
Browse files Browse the repository at this point in the history
…anges

We use esbuild in tiny-react-sandbox, which we use so that we can
test the react code without needing to go through the whole process
of building packages, publishing to Verdaccio and building examples
on each change.

We need to upgrade esbuild (or at least we thought we needed to
when this started two hours ago) to fix issues importing from crypto
package (which we use for Seafowl hashing).

The latest ESBuild contains breaking changes because it rewrites
the incremental build APIs, so we need to rewrite basically the
entirety of dev.mjs to use the new APIs, which also include live
reload so we can drop our hacky implementation of it.

This commit implements dev.mjs to work properly with watch mode,
live reload, and also importing from 'crypto'

See: evanw/esbuild#2816
  • Loading branch information
milesrichardson committed Mar 15, 2023
1 parent 2975ae1 commit 06ccfc4
Show file tree
Hide file tree
Showing 9 changed files with 285 additions and 70 deletions.
9 changes: 9 additions & 0 deletions packages/tiny-react-sandbox/crypto-shim.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This is a shim for the 'crypto' module, so that esbuild can import this shim.
// We can't use esbuild externals, because that produces a "dynamic require,"
// As long as our consuming code only attempts to access 'webcrypto' so long
// as window.crypto does not exist, then it's okay that this is an empty shim.
export const webcrypto = {
subtle: () => {
throw new Error("This shouldn't actually be called");
},
};
93 changes: 29 additions & 64 deletions packages/tiny-react-sandbox/dev.mjs
Original file line number Diff line number Diff line change
@@ -1,80 +1,45 @@
/**
* Adapted from:
* * https://github.com/evanw/esbuild/issues/802#issuecomment-1116495659
* * https://github.com/evanw/esbuild/issues/802#issuecomment-819578182
*/

import esbuild from "esbuild";
import { createServer, request } from "http";
import process from "process";
import path from "node:path";

const clients = [];

esbuild
.build({
const context = await esbuild
.context({
entryPoints: [
"./pages/ast-debugger.tsx",
"./pages/dsx.tsx",
"./pages/ddn.tsx",
],
bundle: true,
external: ["crypto"],
outdir: "./www/dist",
watch: {
onRebuild(error, result) {
clients.forEach((res) => res.write("data: update\n\n"));
clients.length = 0;
console.log(error ? error : "...");
// This plugin overrides the "crypto" module to export a (basically) empty shim,
// which is okay as long as our code only accesses the module if window.crypto does not exist
plugins: [
{
name: "hide-crypto",
setup(build) {
build.onResolve({ filter: /^crypto/ }, () => ({
path: path.join(process.cwd(), "crypto-shim.mjs"),
}));
},
},
},
inject: ["./react-shim.mjs"],
],
})
.catch(() => process.exit(1));

esbuild.serve({ servedir: "./www", host: "localhost" }, {}).then(() => {
createServer((req, res) => {
const { url, method, headers } = req;
if (req.url === "/esbuild")
return clients.push(
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
})
);
const path = ~url.split("/").pop().indexOf(".") ? url : `/index.html`;
// NOTE: SSE limited to 6 tabs; any additional tabs will appear not to load
// @see: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
req.pipe(
request(
{ hostname: "127.0.0.1", port: 8000, path, method, headers },
(prxRes) => {
if (url.startsWith("/dist/")) {
const jsReloadIIFE =
' (() => new EventSource("/esbuild").onmessage = () => location.reload())();';
.catch(() => {
console.log("ERROR");
process.exit(1);
});

const newHeaders = {
...prxRes.headers,
"content-length":
parseInt(prxRes.headers["content-length"], 10) +
jsReloadIIFE.length,
};
await context.rebuild();

res.writeHead(prxRes.statusCode, newHeaders);
res.write(jsReloadIIFE);
} else {
res.writeHead(prxRes.statusCode, prxRes.headers);
}
prxRes.pipe(res, { end: true });
}
),
{ end: true }
);
}).listen(3000);
await context.watch();

setTimeout(() => {
console.log("Listening on localhost:3000 ...");
console.log(" http://localhost:3000/ast-debugger.html");
console.log(" http://localhost:3000/dsx.html");
console.log(" http://localhost:3000/ddn.html");
});
const serveResult = await context.serve({
servedir: "./www",
host: "localhost",
});

console.log(`Listening on http://${serveResult.host}:${serveResult.port}`);
console.log(" http://localhost:3000/ast-debugger.html");
console.log(" http://localhost:3000/dsx.html");
console.log(" http://localhost:3000/ddn.html");
2 changes: 1 addition & 1 deletion packages/tiny-react-sandbox/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
"devDependencies": {
"@types/react": "18.0.14",
"@types/react-dom": "18.0.5",
"esbuild": "0.14.49"
"esbuild": "0.17.11"
}
}
2 changes: 0 additions & 2 deletions packages/tiny-react-sandbox/react-shim.mjs

This file was deleted.

5 changes: 4 additions & 1 deletion packages/tiny-react-sandbox/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@
"extends": "../../tsconfig.base.json",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["www/dist"],
"references": [{ "path": "../client-http" }, { "path": "../react" }]
"references": [{ "path": "../client-http" }, { "path": "../react" }],
"compilerOptions": {
"jsx": "react-jsx"
}
}
1 change: 1 addition & 0 deletions packages/tiny-react-sandbox/www/ast-debugger.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html>
<head><script type="text/javascript">new EventSource("/esbuild").addEventListener("change", () => location.reload());</script></head>
<body>
<div id="root" />
<script src="dist/ast-debugger.js"></script>
Expand Down
4 changes: 4 additions & 0 deletions packages/tiny-react-sandbox/www/ddn.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript">new EventSource("/esbuild").addEventListener("change", () => location.reload());</script>
</head>
<body>
<div id="root" />
<script src="dist/ddn.js"></script>
Expand Down
4 changes: 4 additions & 0 deletions packages/tiny-react-sandbox/www/dsx.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript">new EventSource("/esbuild").addEventListener("change", () => location.reload());</script>
</head>
<body>
<div id="root" />
<script src="dist/dsx.js"></script>
Expand Down
Loading

0 comments on commit 06ccfc4

Please sign in to comment.