MCPcopy Create free account
hub / github.com/vercel/vercel / compileUserCode

Function compileUserCode

packages/node/src/bundling-handler.js:160–239  ·  view source on GitHub ↗

* Compile a user module and return a (req, res) handler regardless of * export shape. Mirrors the detection logic in serverless-handler.mts.

(filePath)

Source from the content-addressed store, hash-verified

158 * export shape. Mirrors the detection logic in serverless-handler.mts.
159 */
160async function compileUserCode(filePath) {
161 let server = null;
162 let serverFound;
163
164 // Monkey-patch http.Server.prototype.listen to capture server instances
165 // created during module import (e.g. Express apps calling app.listen()).
166 const originalListen = http.Server.prototype.listen;
167 http.Server.prototype.listen = function () {
168 server = this;
169 http.Server.prototype.listen = originalListen;
170 if (serverFound) serverFound();
171 return this;
172 };
173
174 try {
175 let listener = await loadModule(filePath);
176 listener = unwrapDefaults(listener);
177
178 // 1. Web handlers (GET, POST, fetch, etc.)
179 const isWebHandler =
180 HTTP_METHODS.some(m => typeof listener[m] === 'function') ||
181 typeof listener.fetch === 'function';
182
183 if (isWebHandler) {
184 return createWebHandler(listener);
185 }
186
187 // 2. Function handler: (req, res) => { ... }
188 if (typeof listener === 'function') {
189 return listener;
190 }
191
192 // 3. Server handler: http.createServer(...).listen()
193 // Wait briefly for async server creation if not captured yet.
194 if (!server) {
195 await new Promise(r => {
196 serverFound = r;
197 setTimeout(r, 1000);
198 });
199 }
200
201 if (server) {
202 // Start the captured server on a random port and proxy requests to it.
203 await new Promise(r => server.listen(0, '127.0.0.1', r));
204 const { port } = server.address();
205
206 return (req, res) => {
207 const proxyReq = http.request(
208 {
209 hostname: '127.0.0.1',
210 port,
211 path: req.url,
212 method: req.method,
213 headers: {
214 ...req.headers,
215 host: req.headers['x-forwarded-host'] || req.headers.host,
216 },
217 },

Callers 1

Calls 4

loadModuleFunction · 0.85
unwrapDefaultsFunction · 0.85
createWebHandlerFunction · 0.85
addressMethod · 0.45

Tested by

no test coverage detected