-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
236 lines (199 loc) Β· 5.77 KB
/
Copy pathdev-server.js
File metadata and controls
236 lines (199 loc) Β· 5.77 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const http = require("http");
const { spawn } = require("child_process");
const { WebSocketServer } = require("ws");
const CONFIG = {
port: 3004,
wsPort: 3005,
yamlFile: "api.yaml",
outputFile: "index.html",
buildCommand: "npx",
buildArgs: [
"@redocly/cli",
"build-docs",
"api.yaml",
"--output",
"index.html",
],
};
console.log("π Starting OpenAPI dev server...");
// Create WebSocket server for live reload
const wss = new WebSocketServer({ port: CONFIG.wsPort });
const clients = new Set();
wss.on("connection", (ws) => {
clients.add(ws);
console.log("π‘ Browser connected for live reload");
ws.on("close", () => {
clients.delete(ws);
});
});
// Function to notify all connected browsers to reload
function notifyReload() {
clients.forEach((client) => {
if (client.readyState === 1) {
// WebSocket.OPEN
client.send("reload");
}
});
}
// Function to build the documentation
function buildDocs() {
console.log("π¨ Building documentation...");
const build = spawn(CONFIG.buildCommand, CONFIG.buildArgs, {
stdio: "pipe",
});
let output = "";
let errorOutput = "";
build.stdout.on("data", (data) => {
output += data.toString();
});
build.stderr.on("data", (data) => {
errorOutput += data.toString();
});
build.on("close", (code) => {
if (code === 0) {
console.log("β
Documentation built successfully");
// Inject live reload script into the HTML
injectLiveReload();
// Notify browsers to reload
setTimeout(() => {
notifyReload();
console.log("π Page reloaded in browser");
}, 100);
} else {
console.error("β Build failed:");
console.error(errorOutput);
}
});
}
// Function to inject live reload script into HTML
function injectLiveReload() {
try {
let html = fs.readFileSync(CONFIG.outputFile, "utf8");
// Remove existing live reload script if present
html = html.replace(
/<script id="live-reload-script">[\s\S]*?<\/script>/g,
""
);
const liveReloadScript = `
<script id="live-reload-script">
(function() {
const ws = new WebSocket('ws://localhost:${CONFIG.wsPort}');
ws.onmessage = function(event) {
if (event.data === 'reload') {
console.log('π Reloading page due to file changes...');
window.location.reload();
}
};
ws.onopen = function() {
console.log('π‘ Connected to live reload server');
};
ws.onerror = function() {
console.log('β Live reload connection failed');
};
})();
</script>`;
// Inject before closing </body> tag, or at the end if no </body>
if (html.includes("</body>")) {
html = html.replace("</body>", liveReloadScript + "\n</body>");
} else {
html += liveReloadScript;
}
fs.writeFileSync(CONFIG.outputFile, html);
} catch (error) {
console.warn("β οΈ Could not inject live reload script:", error.message);
}
}
// File watcher
function setupWatcher() {
console.log(`π Watching ${CONFIG.yamlFile} for changes...`);
let timeout;
fs.watchFile(CONFIG.yamlFile, { interval: 100 }, (curr, prev) => {
if (curr.mtime !== prev.mtime) {
console.log(`π ${CONFIG.yamlFile} changed`);
// Debounce rapid changes
clearTimeout(timeout);
timeout = setTimeout(buildDocs, 200);
}
});
}
// HTTP server to serve the documentation
function createServer() {
const server = http.createServer((req, res) => {
let filePath = req.url === "/" ? CONFIG.outputFile : req.url.slice(1);
// Security: prevent directory traversal
filePath = path.resolve(filePath);
const serverRoot = process.cwd();
if (!filePath.startsWith(serverRoot)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
// Check if file exists
if (!fs.existsSync(filePath)) {
res.writeHead(404);
res.end("Not Found");
return;
}
// Determine content type
const ext = path.extname(filePath).toLowerCase();
const contentTypes = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
const contentType = contentTypes[ext] || "text/plain";
try {
const content = fs.readFileSync(filePath);
res.writeHead(200, { "Content-Type": contentType });
res.end(content);
} catch (error) {
res.writeHead(500);
res.end("Internal Server Error");
}
});
server.listen(CONFIG.port, () => {
console.log(`π Server running at http://localhost:${CONFIG.port}`);
console.log(`π Documentation will be available once built`);
console.log("");
console.log("π‘ Tips:");
console.log(" - Edit your api.yaml file to see live updates");
console.log(" - Press Ctrl+C to stop the server");
console.log("");
});
return server;
}
// Graceful shutdown
function setupGracefulShutdown(server) {
process.on("SIGINT", () => {
console.log("\nπ Shutting down dev server...");
fs.unwatchFile(CONFIG.yamlFile);
wss.close();
server.close(() => {
console.log("π Dev server stopped");
process.exit(0);
});
});
}
// Check if YAML file exists
if (!fs.existsSync(CONFIG.yamlFile)) {
console.error(`β Error: ${CONFIG.yamlFile} not found`);
console.log(
"Make sure your OpenAPI spec file exists in the current directory"
);
process.exit(1);
}
// Initialize everything
const server = createServer();
setupGracefulShutdown(server);
setupWatcher();
// Initial build
buildDocs();