« get me outta code hell

live-dev-server.js « build-modes « write « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/write/build-modes/live-dev-server.js
blob: 8160c8f92948d3f74f6a0bb2b725d3cc140e5b00 (plain)
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import {spawn} from 'node:child_process';
import * as http from 'node:http';
import {readFile, stat} from 'node:fs/promises';
import * as path from 'node:path';
import {inspect as nodeInspect} from 'node:util';

import {ENABLE_COLOR, logInfo, logWarn, progressCallAll} from '#cli';
import {watchContentDependencies} from '#content-dependencies';
import {quickEvaluate} from '#content-function';
import * as html from '#html';
import * as pageSpecs from '#page-specs';
import {serializeThings} from '#serialize';

import {
  getPagePathname,
  getURLsFrom,
  getURLsFromRoot,
} from '#urls';

import {bindUtilities} from '../bind-utilities.js';
import {generateRandomLinkDataJSON, generateRedirectHTML} from '../common-templates.js';

const defaultHost = '0.0.0.0';
const defaultPort = 8002;

export const description = `Hosts a local HTTP server which generates page content as it is requested, instead of all at once; reacts to changes in data files, so new reloads will be up-to-date with on-disk YAML data (<- not implemented yet, check back soon!)\n\nIntended for local development ONLY; this custom HTTP server is NOT rigorously tested and almost certainly has security flaws`;

function inspect(value, opts = {}) {
  return nodeInspect(value, {colors: ENABLE_COLOR, ...opts});
}

export function getCLIOptions() {
  return {
    host: {
      help: `Hostname to which HTTP server is bound\nDefaults to ${defaultHost}`,
      type: 'value',
    },

    port: {
      help: `Port to which HTTP server is bound\nDefaults to ${defaultPort}`,
      type: 'value',
      validate(size) {
        if (parseInt(size) !== parseFloat(size)) return 'an integer';
        if (parseInt(size) < 1024 || parseInt(size) > 49151) return 'a user/registered port (1024-49151)';
        return true;
      },
    },

    'loud-responses': {
      help: `Enables outputting [200] and [404] responses in the server log, which are suppressed by default`,
      type: 'flag',
    },

    'show-timings': {
      help: `Enables outputting timings in the server log for how long pages to take to generate`,
      type: 'flag',
    },

    'serve-sfx': {
      help: `Plays the specified sound file once the HTTP server is ready (this requires mpv)`,
      type: 'value',
    },

    'skip-serving': {
      help: `Causes the build to exit when it would start serving over HTTP instead\n\nMainly useful for testing performance`,
      type: 'flag',
    },
  };
}

export async function go({
  cliOptions,
  _dataPath,
  mediaPath,
  mediaCachePath,

  defaultLanguage,
  languages,
  missingImagePaths,
  srcRootPath,
  thumbsCache,
  urls,
  wikiData,

  cachebust,
  developersComment,
  getSizeOfAdditionalFile,
  getSizeOfImagePath,
  niceShowAggregate,
}) {
  const showError = (error) => {
    if (niceShowAggregate) {
      if (error.errors || error.cause) {
        niceShowAggregate(error);
        return;
      }
    }

    console.error(inspect(error, {depth: Infinity}));
  };

  const host = cliOptions['host'] ?? defaultHost;
  const port = parseInt(cliOptions['port'] ?? defaultPort);
  const loudResponses = cliOptions['loud-responses'] ?? false;
  const showTimings = cliOptions['show-timings'] ?? false;
  const skipServing = cliOptions['skip-serving'] ?? false;
  const serveSFX = cliOptions['serve-sfx'] ?? null;

  const contentDependenciesWatcher = await watchContentDependencies({
    showAggregate: niceShowAggregate,
  });

  const {contentDependencies} = contentDependenciesWatcher;

  contentDependenciesWatcher.on('error', () => {});
  await new Promise(resolve => contentDependenciesWatcher.once('ready', resolve));

  let targetSpecPairs = getPageSpecsWithTargets({wikiData});
  const pages = progressCallAll(`Computing page data & paths for ${targetSpecPairs.length} targets.`,
    targetSpecPairs.flatMap(({
      pageSpec,
      target,
      targetless,
    }) => () => {
      if (targetless) {
        const result = pageSpec.pathsTargetless({wikiData});
        return Array.isArray(result) ? result : [result];
      } else {
        return pageSpec.pathsForTarget(target);
      }
    })).flat();

  logInfo`Will be serving a total of ${pages.length} pages.`;

  const urlToPageMap = Object.fromEntries(pages
    .filter(page => page.type === 'page' || page.type === 'redirect')
    .flatMap(page => {
      let servePath;
      if (page.type === 'page')
        servePath = page.path;
      else if (page.type === 'redirect')
        servePath = page.fromPath;

      return Object.values(languages).map(language => {
        const baseDirectory =
          language === defaultLanguage ? '' : language.code;

        const pathname = getPagePathname({
          baseDirectory,
          pagePath: servePath,
          urls,
        });

        return [pathname, {
          baseDirectory,
          language,
          page,
          servePath,
        }];
      });
    }));

  const server = http.createServer(async (request, response) => {
    const contentTypeHTML = {'Content-Type': 'text/html; charset=utf-8'};
    const contentTypeJSON = {'Content-Type': 'application/json; charset=utf-8'};
    const contentTypePlain = {'Content-Type': 'text/plain; charset=utf-8'};

    const requestTime = new Date().toLocaleDateString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit'});
    const requestHead =
      (loudResponses
        ? `${requestTime} - ${request.socket.remoteAddress}`
        : `${requestTime}`);

    let url;
    try {
      url = new URL(request.url, `http://${request.headers.host}`);
    } catch (error) {
      response.writeHead(500, contentTypePlain);
      response.end('Failed to parse request URL\n');
      return;
    }

    const {pathname} = url;

    // Specialized routes

    if (pathname === '/random-link-data.json') {
      try {
        const json = generateRandomLinkDataJSON({
          serializeThings,
          wikiData,
        });

        response.writeHead(200, contentTypeJSON);
        response.end(json);
        if (loudResponses) console.log(`${requestHead} [200] ${pathname}`);
      } catch (error) {
        response.writeHead(500, contentTypeJSON);
        response.end(`Internal error serializing wiki JSON`);
        console.error(`${requestHead} [500] ${pathname}`);
        showError(error);
      }
      return;
    }

    const {
      area: localFileArea,
      path: localFilePath
    } = pathname.match(/^\/(?<area>static|util|media|thumb)\/(?<path>.*)/)?.groups ?? {};

    if (localFileArea) {
      // Not security tested, man, this is a dev server!!
      const safePath = path.posix.resolve('/', localFilePath).replace(/^\//, '');

      let localDirectory;
      if (localFileArea === 'static' || localFileArea === 'util') {
        localDirectory = path.join(srcRootPath, localFileArea);
      } else if (localFileArea === 'media') {
        localDirectory = mediaPath;
      } else if (localFileArea === 'thumb') {
        localDirectory = mediaCachePath;
      }

      let filePath;
      try {
        filePath = path.resolve(localDirectory, decodeURI(safePath.split('/').join(path.sep)));
      } catch (error) {
        response.writeHead(404, contentTypePlain);
        response.end(`No ${localFileArea} file found for: ${safePath}`);
        console.log(`${requestHead} [404] ${pathname}`);
        console.log(`Failed to decode request pathname`);
      }

      try {
        await stat(filePath);
      } catch (error) {
        if (error.code === 'ENOENT') {
          response.writeHead(404, contentTypePlain);
          response.end(`No ${localFileArea} file found for: ${safePath}`);
          console.log(`${requestHead} [404] ${pathname}`);
          console.log(`ENOENT for stat: ${filePath}`);
        } else {
          response.writeHead(500, contentTypePlain);
          response.end(`Internal error accessing ${localFileArea} file for: ${safePath}`);
          console.error(`${requestHead} [500] ${pathname}`);
          showError(error);
        }
        return;
      }

      const extname = path.extname(safePath).slice(1).toLowerCase();

      const contentType = {
        // BRB covering all my bases
        'aac': 'audio/aac',
        'bmp': 'image/bmp',
        'css': 'text/css',
        'csv': 'text/csv',
        'gif': 'image/gif',
        'ico': 'image/vnd.microsoft.icon',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'js': 'text/javascript',
        'mjs': 'text/javascript',
        'mp3': 'audio/mpeg',
        'mp4': 'video/mp4',
        'oga': 'audio/ogg',
        'ogg': 'audio/ogg',
        'ogv': 'video/ogg',
        'opus': 'audio/opus',
        'png': 'image/png',
        'pdf': 'application/pdf',
        'svg': 'image/svg+xml',
        'ttf': 'font/ttf',
        'txt': 'text/plain',
        'wav': 'audio/wav',
        'weba': 'audio/webm',
        'webm': 'video/webm',
        'woff': 'font/woff',
        'woff2': 'font/woff2',
        'xml': 'application/xml',
        'zip': 'application/zip',
      }[extname];

      try {
        const {size} = await stat(filePath);
        const buffer = await readFile(filePath)
        response.writeHead(200, contentType ? {
          'Content-Type': contentType,
          'Content-Length': size,
        } : {});
        response.end(buffer);
        if (loudResponses) console.log(`${requestHead} [200] ${pathname}`);
      } catch (error) {
        response.writeHead(500, contentTypePlain);
        response.end(`Failed during file-to-response pipeline`);
        console.error(`${requestHead} [500] ${pathname}`);
        showError(error);
      }
      return;
    }

    // Other routes determined by page and URL specs

    // URL to page map expects trailing slash but no leading slash.
    const pathnameKey = pathname.replace(/^\//, '') + (pathname.endsWith('/') ? '' : '/');

    if (!Object.hasOwn(urlToPageMap, pathnameKey)) {
      response.writeHead(404, contentTypePlain);
      response.end(`No page found for: ${pathnameKey}\n`);
      if (loudResponses) console.log(`${requestHead} [404] ${pathname}`);
      return;
    }

    // All pages expect to be served at a URL with a trailing slash, which must
    // be fulfilled for relative URLs (ex. href="../lofam5/") to work. Redirect
    // if there is no trailing slash in the request URL.
    if (!pathname.endsWith('/')) {
      const target = pathname + '/';
      response.writeHead(301, {
        ...contentTypePlain,
        'Location': target,
      });
      response.end(`Redirecting to: ${target}\n`);
      console.log(`${requestHead} [301] (trl. slash) ${pathname}`);
      return;
    }

    const {
      baseDirectory,
      language,
      page,
      servePath,
    } = urlToPageMap[pathnameKey];

    const to = getURLsFrom({
      baseDirectory,
      pagePath: servePath,
      urls,
    });

    const absoluteTo = getURLsFromRoot({
      baseDirectory,
      urls,
    });

    try {
      if (page.type === 'redirect') {
        const title =
          page.title ??
          page.getTitle?.({language});

        const target = to('localized.' + page.toPath[0], ...page.toPath.slice(1));

        response.writeHead(301, {
          ...contentTypeHTML,
          'Location': target,
        });

        const redirectHTML = generateRedirectHTML(title, target, {language});

        response.end(redirectHTML);

        console.log(`${requestHead} [301] (redirect) ${pathname}`);
        return;
      }

      const timeStart = Date.now();

      const bound = bindUtilities({
        absoluteTo,
        cachebust,
        defaultLanguage,
        getSizeOfAdditionalFile,
        getSizeOfImagePath,
        language,
        languages,
        missingImagePaths,
        pagePath: servePath,
        thumbsCache,
        to,
        urls,
        wikiData,
      });

      const topLevelResult =
        quickEvaluate({
          contentDependencies,
          extraDependencies: {...bound, appendIndexHTML: false},

          name: page.contentFunction.name,
          args: page.contentFunction.args ?? [],
        });

      const {pageHTML} = html.resolve(topLevelResult);

      const timeEnd = Date.now();
      const timeDelta = timeEnd - timeStart;

      if (showTimings) {
        const timeString =
          (timeDelta > 100
            ? `${(timeDelta / 1000).toFixed(2)}s`
            : `${timeDelta}ms`);

        console.log(`${requestHead} [200, ${timeString}] ${pathname}`);
      } else if (loudResponses) {
        console.log(`${requestHead} [200] ${pathname}`);
      }

      response.writeHead(200, contentTypeHTML);
      response.end(pageHTML);
    } catch (error) {
      console.error(`${requestHead} [500] ${pathname}`);
      showError(error);
      response.writeHead(500, contentTypePlain);
      response.end(`Error generating page, view server log for details\n`);
    }
  });

  const address = `http://${host}:${port}/`;

  server.on('error', error => {
    if (error.code === 'EADDRINUSE') {
      logWarn`Port ${port} is already in use - will (continually) retry after 10 seconds.`;
      logWarn`Press ^C here (control+C) to exit and change ${'--port'} number, or stop the server currently running on port ${port}.`;
      setTimeout(() => {
        server.close();
        server.listen(port, host);
      }, 10_000);
    } else {
      console.error(`Server error detected (code: ${error.code})`);
      showError(error);
    }
  });

  server.on('listening', () => {
    logInfo`${'All done!'} Listening at: ${address}`;
    logInfo`Press ^C here (control+C) to stop the server and exit.`;
    if (showTimings && loudResponses) {
      logInfo`Printing all HTTP responses, plus page generation timings.`;
    } else if (showTimings) {
      logInfo`Printing page generation timings.`;
    } else if (loudResponses) {
      logInfo`Printing all HTTP responses.`
    } else {
      logInfo`Suppressing [200] and [404] response logging.`
      logInfo`(Pass --loud-responses to show these.)`;
    }

    if (serveSFX) {
      spawn('mpv', [serveSFX, '--volume=75']);
    }
  });

  if (skipServing) {
    logInfo`Ready to serve! But --skip-serving was passed, so all done.`;
  } else {
    server.listen(port, host);

    // Just keep going... forever!!!
    await new Promise(() => {});
  }

  return true;
}

function getPageSpecsWithTargets({
  wikiData,
}) {
  return Object.values(pageSpecs)
    .filter(pageSpec => pageSpec.condition?.({wikiData}) ?? true)
    .flatMap(pageSpec => [
      ...pageSpec.targets
        ? pageSpec.targets({wikiData})
            .map(target => ({pageSpec, target}))
        : [],
      Object.hasOwn(pageSpec, 'pathsTargetless') &&
        {pageSpec, targetless: true},
    ])
    .filter(Boolean);
}