MCPcopy Create free account
hub / github.com/firebase/firebase-tools / initMiddleware

Function initMiddleware

src/hosting/initMiddleware.ts:16–74  ·  view source on GitHub ↗
(
  init: TemplateServerResponse,
)

Source from the content-addressed store, hash-verified

14 * @return the middleware function.
15 */
16export function initMiddleware(
17 init: TemplateServerResponse,
18): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {
19 return (req, res, next) => {
20 const parsedUrl = new URL(req.url || "", `http://${req.headers.host}`);
21 const match = RegExp(SDK_PATH_REGEXP).exec(parsedUrl.pathname);
22 if (match) {
23 const version = match[1];
24 const sdkName = match[2];
25 const u = new URL(`https://www.gstatic.com/firebasejs/${version}/${sdkName}`);
26 const c = new Client({ urlPrefix: u.origin, auth: false });
27 const headers: { [key: string]: string } = {};
28 const acceptEncoding = req.headers["accept-encoding"];
29 if (typeof acceptEncoding === "string" && acceptEncoding) {
30 headers["accept-encoding"] = acceptEncoding;
31 }
32 c.request<unknown, NodeJS.ReadableStream>({
33 method: "GET",
34 path: u.pathname,
35 headers,
36 responseType: "stream",
37 resolveOnHTTPError: true,
38 compress: false,
39 })
40 .then((sdkRes) => {
41 if (sdkRes.status === 404) {
42 return next();
43 }
44 for (const [key, value] of Object.entries(sdkRes.response.headers.raw())) {
45 res.setHeader(key, value);
46 }
47 sdkRes.body.pipe(res);
48 })
49 .catch((e) => {
50 utils.logLabeledWarning(
51 "hosting",
52 `Could not load Firebase SDK ${sdkName} v${version}, check your internet connection.`,
53 );
54 logger.debug(e);
55 });
56 } else if (parsedUrl.pathname === "/__/firebase/init.js") {
57 // In theory we should be able to get this from req.query but for some
58 // when testing this functionality, req.query and req.params were always
59 // empty or undefined.
60 const query = parsedUrl.searchParams;
61 res.setHeader("Content-Type", "application/javascript");
62 if (query.get("useEmulator") === "true") {
63 res.end(init.emulatorsJs);
64 } else {
65 res.end(init.js);
66 }
67 } else if (parsedUrl.pathname === "/__/firebase/init.json") {
68 res.setHeader("Content-Type", "application/json");
69 res.end(init.json);
70 } else {
71 next();
72 }
73 };

Callers 2

startServerFunction · 0.90

Calls 3

requestMethod · 0.95
getMethod · 0.65
nextFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…