1+ /**
2+ * Copyright 2025 Google LLC
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+ import * as esbuild from 'esbuild' ;
18+ import http from 'node:http' ;
19+
20+ // Start esbuild's server on port 3000
21+ let ctx = await esbuild . context ( {
22+ bundle : true ,
23+ target : 'es2020' ,
24+ outfile : 'dist/bundle.js' ,
25+ sourcemap : true ,
26+ entryPoints : [ 'src/index.ts' ] ,
27+ } ) ;
28+
29+ // The return value tells us where esbuild's local server is. It might
30+ // not be 3000 if that port was busy.
31+ let { host, port } = await ctx . serve ( { servedir : 'dist' , port : 3000 } ) ;
32+
33+ // Then start a proxy server on port 8000
34+ http . createServer ( ( req , res ) => {
35+ const options = {
36+ hostname : host ,
37+ port : port ,
38+ path : req . url ,
39+ method : req . method ,
40+ headers : req . headers ,
41+ } ;
42+
43+ // Forward each incoming request to esbuild
44+ const proxyReq = http . request ( options , proxyRes => {
45+ // If esbuild returns "not found", send a custom 404 page
46+ if ( proxyRes . statusCode === 404 ) {
47+ res . writeHead ( 404 , { 'Content-Type' : 'text/html' } ) ;
48+ res . end ( '<h1>Not found</h1>' ) ;
49+ return ;
50+ }
51+
52+ // Otherwise, forward the response from esbuild to the client.
53+ // Include cross origin headers for Wasm threaded support.
54+ const headers = {
55+ ...proxyRes . headers ,
56+ 'Cross-Origin-Opener-Policy' : 'same-origin' ,
57+ 'Cross-Origin-Embedder-Policy' : 'require-corp' ,
58+ } ;
59+ res . writeHead ( proxyRes . statusCode , headers ) ;
60+ proxyRes . pipe ( res , { end : true } ) ;
61+ } ) ;
62+
63+ // Forward the body of the request to esbuild
64+ req . pipe ( proxyReq , { end : true } ) ;
65+ } ) . listen ( 8000 ) ;
66+
67+ console . log ( 'Server listening on http://localhost:8000' ) ;
0 commit comments