-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
260 lines (229 loc) · 6.69 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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
const express = require("express");
const fs = require("fs");
const path = require("path");
const url = require("url");
const { readdirSync, readFileSync } = fs;
const { join, parse } = path;
// Constants
const SERVER_PORT = process.env.PORT || 9060;
const PUBLIC_DIR = "public";
const ASSETS_FILE = ".glitch-assets";
// Add any files that you'd like actually served up by this server, no tricks!!
const ACTUALLY_SERVE_FILENAMES_MATCHING = ["index.html"];
/**
* @typedef File
* @property {string} name - The base filename with extension
* @property {string} location - The path of the file, either a Glitch CDN link or path relative to the root project directory
*
* @typedef ExtToFile
* @type {Object.<string, File[]>}
*/
// In-memory store
/** @type File[] */
let publicFiles = undefined;
/** @type ExtToFile */
let publicFilesByExt = undefined;
/** @type File[] */
let assetFiles = undefined;
/** @type ExtToFile */
let assetFilesByExt = undefined;
// Helper functions
function publicPath(path) {
if (path) {
return join(__dirname, PUBLIC_DIR, path);
}
return join(__dirname, PUBLIC_DIR);
}
function normalize(string) {
return string.toLowerCase();
}
function random(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function shouldIgnore(path) {
const { ext } = parse(path);
// Ignore any directories
if (!ext) {
return true;
}
return false;
}
function shouldActuallyServe(path) {
const { base } = parse(path);
if (path === "/" || ACTUALLY_SERVE_FILENAMES_MATCHING.includes(base)) {
return true;
}
return false;
}
function mapFilesToExt(files) {
/** @type ExtensionItemMap */
const extMap = {};
// Create a map of extensions to filenames
files.forEach((item) => {
const { ext } = parse(item.name);
const e = normalize(ext);
if (!extMap.hasOwnProperty(e)) {
extMap[e] = [];
}
extMap[e].push(item);
});
return extMap;
}
function getRandomFile(path, list) {
if (!list || list.length === 0) {
return;
}
const { name: oldName, ext } = parse(path);
let tries = 0;
let selectedName = oldName;
let selectedPath = "";
while (tries <= 10 && selectedName === oldName) {
const randomIndex = random(0, list.length - 1);
const selectedFile = list[randomIndex];
if (selectedFile) {
const { name: newName } = parse(selectedFile.name);
selectedName = newName;
selectedPath = selectedFile.location;
}
tries++;
}
return { name: `${selectedName}${ext}`, location: selectedPath };
}
function listPublicFiles() {
try {
const publicDir = publicPath();
const files = readdirSync(publicDir, {
encoding: "utf-8",
recursive: true,
});
return files
.filter((f) => !shouldIgnore(f))
.map((f) => ({ name: f, location: publicPath(f) }));
} catch (err) {
console.error(`failed to list files from ${PUBLIC_DIR}:`, err);
return [];
}
}
function listGlitchAssets() {
/** @type File[] */
const filesList = [];
try {
const assetPath = join(__dirname, ASSETS_FILE);
const glitchFiles = readFileSync(assetPath, { encoding: "utf-8" });
glitchFiles
.trim()
.split("\n")
.forEach((assetString) => {
try {
const asset = JSON.parse(assetString);
if (asset.hasOwnProperty("name") && asset.hasOwnProperty("url")) {
filesList.push({ name: asset.name, location: asset.url });
}
} catch (err) {
// Ignore any errors parsing individual JSON elements
console.error(
`failed to parse glitch asset string "${assetString}" to json`,
err
);
}
});
} catch (err) {
console.error(`failed to list glitch assets from ${ASSETS_FILE}:`, err);
}
return filesList;
}
function sendAsset(res, location) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.redirect(location);
}
// Server and request handlers
const app = express();
// Handler for any Glitch assets, where the request is for
// the path "/assets/filename.jpg"
app.use("/assets", (req, res, next) => {
const { path } = req;
if (shouldActuallyServe(path)) {
next();
return;
}
const { ext } = parse(path);
const assetToSend = getRandomFile(
decodeURI(path),
assetFilesByExt[normalize(ext)]
);
if (assetToSend !== undefined) {
console.log(`request for ${path} > 👻 > sending ${assetToSend.name}`);
sendAsset(res, assetToSend.location);
} else {
console.warn(`request for ${path} > 👻 > sorry not found`);
res.status(404);
}
return;
});
// Handler for any files in the "public" folder, which usually
// includes js, css, html, and anything else not considered an asset
// and request matches the path "public/some-page.html"
app.use("/public", (req, res, next) => {
const { path } = req;
if (shouldActuallyServe(path)) {
next();
return;
}
const { ext } = parse(path);
const fileToSend = getRandomFile(
decodeURI(path),
publicFilesByExt[normalize(ext)]
);
if (fileToSend !== undefined) {
console.log(`request for ${path} > 👻 > sending ${fileToSend.name}`);
res.sendFile(fileToSend.location);
return;
} else {
console.warn(`request for ${path} > 👻 > sorry not found`);
res.status(404);
}
});
// Always serve the index file on "/"
app.get("/", (_req, res) => {
res.sendFile(publicPath("index.html"));
});
// Getting to this wildcard route handler means that we
// actually want to serve the requested file
app.get("*", (req, res) => {
const { base } = parse(req.path);
// Check all the files in memory to see if there's a match
const filesToCheck = [...assetFiles, ...publicFiles];
const fileFound = filesToCheck.find((f) => f.name === base);
if (fileFound) {
if (fileFound.location.startsWith("https")) {
sendAsset(res, fileFound.location);
return;
} else {
res.sendFile(fileFound.location);
return;
}
} else {
res.sendStatus(404);
}
});
app.listen(SERVER_PORT, () => {
console.log(`* ~ * 👻 server running on ${SERVER_PORT} 👻 * ~ *`);
});
/**
* The below code executes as soon as the server starts up
* and makes a list of all the files in the `public` directory
* as well as CDN assets, stored in the `.glitch-assets` file
*/
// Get a list of files from public directory
publicFiles = listPublicFiles();
// Map that file list by ext type for easy access
publicFilesByExt = mapFilesToExt(publicFiles);
// Get a list of files from glitch assets
assetFiles = listGlitchAssets();
// Map that file list by ext type for easy access
assetFilesByExt = mapFilesToExt(assetFiles);