-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
102 lines (88 loc) · 2.86 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { createServer as createViteServer } from "vite";
import { createServer } from "node:http";
import { fileURLToPath, URL } from "node:url";
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const __dirname = dirname(fileURLToPath(import.meta.url));
const port = 3000;
const host = "localhost";
/**
* Create a request listener for the server.
* We use Vite as a middleware to serve the files and handle the requests.
* We use standard Node.js HTTP server to handle the requests.
* @returns {Promise<import('http').RequestListener>}
*/
const createRequestListener = async () => {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "custom",
});
return async (req, res) => {
try {
const parsedUrl = new URL(req.url, `http://${host}:${port}`);
let serveUrl = parsedUrl.pathname;
if (vite.middlewares) {
try {
await new Promise((resolve) => vite.middlewares(req, res, resolve));
} catch (err) {
console.error(err);
}
}
if (req.method === "GET" && serveUrl.endsWith(".js")) {
res.setHeader("Content-Type", "application/javascript");
}
if (serveUrl === "/") {
serveUrl = "/index.html";
}
if (serveUrl.endsWith(".html")) {
const template = readFileSync(
resolve(__dirname, "./index.html"),
"utf-8",
);
const transformedTemplate = await vite.transformIndexHtml(
serveUrl,
template,
);
const { renderDialog, renderButton, renderHead } =
await vite.ssrLoadModule("/src/entry-server.ts");
const rpEndpoint = (idp) =>
`https://example.com/proxy.php?client_id=SOME_CLIENT_ID&action=login&redirect_uri=SOME_REDIRECT_URI&idp=${idp}&state=SOME_STATE`;
const lang = "it";
const appDialog = await renderDialog({
lang,
rpEndpoint,
targetSelf: true,
withDemo: true,
});
const appButton = await renderButton({ lang, type: "spid" });
const appHeadHtml = await renderHead();
const html = transformedTemplate.replace(
"<!--spid-cie-button-ssr-outlet-->",
appDialog + appButton,
);
const finalHtml = html.replace(
"<!--spid-cie-button-ssr-head-outlet-->",
appHeadHtml,
);
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(finalHtml);
} else {
res.end();
}
} catch (err) {
console.error(err);
res.writeHead(500);
res.end(err.message);
}
};
};
/**
* Start the server
*/
createRequestListener().then((requestListener) => {
const server = createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
});