@plurid/plurid-react-server 0.0.0-14 → 0.0.0-16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +69 -5
  2. package/distribution/index.d.mts +244 -0
  3. package/distribution/index.d.ts +244 -6
  4. package/distribution/index.js +1573 -1056
  5. package/distribution/index.js.map +1 -0
  6. package/distribution/index.mjs +1642 -0
  7. package/distribution/index.mjs.map +1 -0
  8. package/package.json +129 -133
  9. package/distribution/__tests__/sanity.test.d.ts +0 -0
  10. package/distribution/data/constants/general/index.d.ts +0 -34
  11. package/distribution/data/constants/index.d.ts +0 -2
  12. package/distribution/data/constants/stiller/index.d.ts +0 -2
  13. package/distribution/data/interfaces/external/index.d.ts +0 -151
  14. package/distribution/data/interfaces/index.d.ts +0 -2
  15. package/distribution/data/interfaces/internal/index.d.ts +0 -83
  16. package/distribution/data/templates/index.d.ts +0 -2
  17. package/distribution/index.es.js +0 -1095
  18. package/distribution/objects/ContentGenerator/index.d.ts +0 -7
  19. package/distribution/objects/LiveServer/index.d.ts +0 -13
  20. package/distribution/objects/Renderer/index.d.ts +0 -22
  21. package/distribution/objects/Renderer/template/index.d.ts +0 -3
  22. package/distribution/objects/Server/index.d.ts +0 -57
  23. package/distribution/objects/Stiller/__tests__/index.test.d.ts +0 -1
  24. package/distribution/objects/Stiller/index.d.ts +0 -24
  25. package/distribution/objects/StillsGenerator/index.d.ts +0 -8
  26. package/distribution/objects/StillsManager/index.d.ts +0 -9
  27. package/distribution/utilities/pttp/index.d.ts +0 -6
  28. package/distribution/utilities/template/index.d.ts +0 -9
  29. package/distribution/utilities/wrapping/index.d.ts +0 -28
@@ -1,1095 +0,0 @@
1
- import fs, { promises } from "fs";
2
-
3
- import path from "path";
4
-
5
- import express from "express";
6
-
7
- import compression from "compression";
8
-
9
- import { json } from "body-parser";
10
-
11
- import open from "open";
12
-
13
- import { StyleSheetManager, ServerStyleSheet } from "styled-components";
14
-
15
- import { time, uuid } from "@plurid/plurid-functions";
16
-
17
- import { routing } from "@plurid/plurid-engine";
18
-
19
- import { PluridProvider, PluridRouterStatic, serverComputeMetastate } from "@plurid/plurid-react";
20
-
21
- import { minify } from "html-minifier";
22
-
23
- import React from "react";
24
-
25
- import { renderToString } from "react-dom/server";
26
-
27
- import { HelmetProvider } from "react-helmet-async";
28
-
29
- import http from "http";
30
-
31
- import { fork } from "child_process";
32
-
33
- import detectPort from "detect-port";
34
-
35
- function __awaiter(thisArg, _arguments, P, generator) {
36
- function adopt(value) {
37
- return value instanceof P ? value : new P((function(resolve) {
38
- resolve(value);
39
- }));
40
- }
41
- return new (P || (P = Promise))((function(resolve, reject) {
42
- function fulfilled(value) {
43
- try {
44
- step(generator.next(value));
45
- } catch (e) {
46
- reject(e);
47
- }
48
- }
49
- function rejected(value) {
50
- try {
51
- step(generator["throw"](value));
52
- } catch (e) {
53
- reject(e);
54
- }
55
- }
56
- function step(result) {
57
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
58
- }
59
- step((generator = generator.apply(thisArg, _arguments || [])).next());
60
- }));
61
- }
62
-
63
- function __await(v) {
64
- return this instanceof __await ? (this.v = v, this) : new __await(v);
65
- }
66
-
67
- function __asyncGenerator(thisArg, _arguments, generator) {
68
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
69
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
70
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
71
- return this;
72
- }, i;
73
- function verb(n) {
74
- if (g[n]) i[n] = function(v) {
75
- return new Promise((function(a, b) {
76
- q.push([ n, v, a, b ]) > 1 || resume(n, v);
77
- }));
78
- };
79
- }
80
- function resume(n, v) {
81
- try {
82
- step(g[n](v));
83
- } catch (e) {
84
- settle(q[0][3], e);
85
- }
86
- }
87
- function step(r) {
88
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
89
- }
90
- function fulfill(value) {
91
- resume("next", value);
92
- }
93
- function reject(value) {
94
- resume("throw", value);
95
- }
96
- function settle(f, v) {
97
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
98
- }
99
- }
100
-
101
- const DEFAULT_SERVER_PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
102
-
103
- const DEFAULT_SERVER_OPTIONS_SERVER_NAME = "Plurid Server";
104
-
105
- const DEFAULT_SERVER_OPTIONS_HOSTNAME = "origin";
106
-
107
- const DEFAULT_SERVER_OPTIONS_QUIET = false;
108
-
109
- const DEFAULT_SERVER_OPTIONS_COMPRESSION = true;
110
-
111
- const DEFAULT_SERVER_OPTIONS_OPEN = false;
112
-
113
- const DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY = "build";
114
-
115
- const DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY = "assets";
116
-
117
- const DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY = "stills";
118
-
119
- const DEFAULT_SERVER_OPTIONS_GATEWAY = "/gateway";
120
-
121
- const DEFAULT_SERVER_OPTIONS = {
122
- SERVER_NAME: DEFAULT_SERVER_OPTIONS_SERVER_NAME,
123
- HOSTNAME: DEFAULT_SERVER_OPTIONS_HOSTNAME,
124
- QUIET: DEFAULT_SERVER_OPTIONS_QUIET,
125
- COMPRESSION: DEFAULT_SERVER_OPTIONS_COMPRESSION,
126
- OPEN: DEFAULT_SERVER_OPTIONS_OPEN,
127
- BUILD_DIRECTORY: DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY,
128
- ASSETS_DIRECTORY: DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY,
129
- STILLS_DIRECTORY: DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY,
130
- GATEWAY: DEFAULT_SERVER_OPTIONS_GATEWAY
131
- };
132
-
133
- const DEFAULT_RENDERER_LANGUAGE = "en";
134
-
135
- const DEFAULT_RENDERER_ROOT = "root";
136
-
137
- const DEFAULT_RENDERER_PLURID_STATE = "{}";
138
-
139
- const DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE = "/vendor.js";
140
-
141
- const DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE = "/index.js";
142
-
143
- const DEFAULT__PRELOADED_PLURID_METASTATE__ = "__PRELOADED_PLURID_METASTATE__";
144
-
145
- const CATCH_ALL_ROUTE = "*";
146
-
147
- const NOT_FOUND_ROUTE = process.env.PLURID_SERVER_NOT_FOUND_ROUTE || "/not-found";
148
-
149
- const PTTP_ROUTE = process.env.PLURID_SERVER_PTTP_ROUTE || "/pttp";
150
-
151
- const environment = {
152
- production: process.env.ENV_MODE === "production",
153
- development: process.env.ENV_MODE === "development"
154
- };
155
-
156
- const defaultStillerOptions = {
157
- waitUntil: "networkidle0",
158
- timeout: 3e4,
159
- ignore: []
160
- };
161
-
162
- const cleanTemplate = template => minify(template, {
163
- collapseWhitespace: true,
164
- conservativeCollapse: true,
165
- collapseInlineTagWhitespace: false
166
- });
167
-
168
- const resolveBackgroundStyle = store => {
169
- var _a;
170
- const defaultBackground = {
171
- gradientBackground: "hsl(220, 10%, 32%)",
172
- gradientForeground: "hsl(220, 10%, 18%)"
173
- };
174
- try {
175
- const storeJSON = JSON.parse(store);
176
- const generalPluridTheme = (_a = storeJSON === null || storeJSON === void 0 ? void 0 : storeJSON.themes) === null || _a === void 0 ? void 0 : _a.general;
177
- if (!generalPluridTheme) {
178
- return defaultBackground;
179
- }
180
- const gradientBackground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorTertiary : generalPluridTheme.backgroundColorPrimary;
181
- const gradientForeground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorPrimary : generalPluridTheme.backgroundColorTertiary;
182
- return {
183
- gradientBackground: gradientBackground,
184
- gradientForeground: gradientForeground
185
- };
186
- } catch (error) {
187
- return defaultBackground;
188
- }
189
- };
190
-
191
- const recordToString = record => {
192
- if (!record) {
193
- return "";
194
- }
195
- let recordString = "";
196
- for (const [key, value] of Object.entries(record)) {
197
- recordString += `${key}="${value}"`;
198
- }
199
- return recordString;
200
- };
201
-
202
- const assetsPathRewrite = content => content.replace(/="client\//g, '="/');
203
-
204
- const globalsInjector = globals => {
205
- let globalsScript = "";
206
- for (const [key, value] of Object.entries(globals)) {
207
- const globalScript = `window.${key} = ${value};\n`;
208
- globalsScript += globalScript;
209
- }
210
- return globalsScript;
211
- };
212
-
213
- const NOT_FOUND_TEMPLATE = cleanTemplate(`\n<!DOCTYPE html>\n<html>\n <head>\n <title>[404] Not Found</title>\n <style>\n html, body {\n margin: 0;\n background: #242b33;\n color: #ddd;\n user-select: none;\n }\n\n .not-found {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;\n }\n </style>\n </head>\n\n <body>\n <div class="not-found">[404] Not Found</div>\n </body>\n</html>\n`);
214
-
215
- const SERVER_ERROR_TEMPLATE = cleanTemplate(`\n<!DOCTYPE html>\n<html>\n <head>\n <title>[500] Server Error</title>\n <style>\n html, body {\n margin: 0;\n background: #242b33;\n color: #ddd;\n user-select: none;\n }\n\n .error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;\n }\n </style>\n </head>\n\n <body>\n <div class="error">[500] Server Error</div>\n </body>\n</html>\n`);
216
-
217
- const template = data => {
218
- const {htmlLanguage: htmlLanguage, head: head, htmlAttributes: htmlAttributes, bodyAttributes: bodyAttributes, defaultStyle: defaultStyle, styles: styles, headScripts: headScripts, bodyScripts: bodyScripts, vendorScriptSource: vendorScriptSource, mainScriptSource: mainScriptSource, root: root, content: content, defaultPreloadedPluridMetastate: defaultPreloadedPluridMetastate, pluridMetastate: pluridMetastate, globals: globals, minify: minify} = data;
219
- const injectedGlobals = globalsInjector(globals);
220
- const templateString = `\n<!DOCTYPE html>\n<html lang="${htmlLanguage}" ${htmlAttributes}>\n <head>\n ${head}\n\n ${defaultStyle && `<style>\n ${defaultStyle}\n </style>`}\n\n ${styles}\n\n ${headScripts.join("\n")}\n\n <script src="${vendorScriptSource}"><\/script>\n <script defer src="${mainScriptSource}"><\/script>\n </head>\n <body ${bodyAttributes}>\n <div id="${root}">${content}</div>\n\n <script>\n ${injectedGlobals}\n window.${defaultPreloadedPluridMetastate} = ${pluridMetastate};\n <\/script>\n\n ${bodyScripts.join("\n")}\n </body>\n</html>\n `;
221
- if (!minify) {
222
- return templateString;
223
- }
224
- return cleanTemplate(templateString);
225
- };
226
-
227
- class PluridRenderer {
228
- constructor(configuration) {
229
- const {htmlLanguage: htmlLanguage, head: head, htmlAttributes: htmlAttributes, bodyAttributes: bodyAttributes, defaultStyle: defaultStyle, styles: styles, headScripts: headScripts, bodyScripts: bodyScripts, vendorScriptSource: vendorScriptSource, mainScriptSource: mainScriptSource, content: content, root: root, defaultPreloadedPluridMetastate: defaultPreloadedPluridMetastate, pluridMetastate: pluridMetastate, globals: globals, minify: minify} = configuration;
230
- const {gradientBackground: gradientBackground, gradientForeground: gradientForeground} = resolveBackgroundStyle("");
231
- const defaultStyleBasic = `\n body {\n background: radial-gradient(ellipse at center, ${gradientBackground} 0%, ${gradientForeground} 100%);\n height: 100%;\n margin: 0;\n }\n `;
232
- this.htmlLanguage = htmlLanguage || DEFAULT_RENDERER_LANGUAGE;
233
- this.head = head || "";
234
- this.htmlAttributes = htmlAttributes;
235
- this.bodyAttributes = bodyAttributes || "";
236
- this.defaultStyle = defaultStyle !== null && defaultStyle !== void 0 ? defaultStyle : defaultStyleBasic;
237
- this.styles = styles;
238
- this.headScripts = headScripts;
239
- this.bodyScripts = bodyScripts;
240
- this.vendorScriptSource = vendorScriptSource || DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE;
241
- this.mainScriptSource = mainScriptSource || DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE;
242
- this.root = root || DEFAULT_RENDERER_ROOT;
243
- this.content = assetsPathRewrite(content) || "";
244
- this.defaultPreloadedPluridMetastate = defaultPreloadedPluridMetastate || DEFAULT__PRELOADED_PLURID_METASTATE__;
245
- this.pluridMetastate = pluridMetastate || DEFAULT_RENDERER_PLURID_STATE;
246
- this.globals = globals !== null && globals !== void 0 ? globals : {};
247
- this.minify = minify !== null && minify !== void 0 ? minify : true;
248
- }
249
- html() {
250
- const data = {
251
- htmlLanguage: this.htmlLanguage,
252
- head: this.head,
253
- htmlAttributes: this.htmlAttributes,
254
- bodyAttributes: this.bodyAttributes,
255
- defaultStyle: this.defaultStyle,
256
- styles: this.styles,
257
- headScripts: this.headScripts,
258
- bodyScripts: this.bodyScripts,
259
- vendorScriptSource: this.vendorScriptSource,
260
- mainScriptSource: this.mainScriptSource,
261
- root: this.root,
262
- content: this.content,
263
- defaultPreloadedPluridMetastate: this.defaultPreloadedPluridMetastate,
264
- pluridMetastate: this.pluridMetastate,
265
- globals: this.globals,
266
- minify: this.minify
267
- };
268
- return template(data);
269
- }
270
- }
271
-
272
- const wrapping = (WrappedComponent, WrappeeComponent, properties) => class extends React.Component {
273
- constructor(props) {
274
- super(props);
275
- }
276
- render() {
277
- return React.createElement(WrappedComponent, Object.assign({}, properties), React.createElement(WrappeeComponent, null));
278
- }
279
- };
280
-
281
- class PluridContentGenerator {
282
- constructor(data) {
283
- this.data = data;
284
- }
285
- render() {
286
- var _a;
287
- return __awaiter(this, void 0, void 0, (function*() {
288
- const {pluridMetastate: pluridMetastate, routes: routes, planes: planes, exterior: exterior, shell: shell, gateway: gateway, gatewayEndpoint: gatewayEndpoint, gatewayQuery: gatewayQuery, helmet: helmet, services: services, stylesheet: stylesheet, preserveResult: preserveResult, matchedPlane: matchedPlane, pathname: pathname, hostname: hostname} = this.data;
289
- const RoutedApplication = () => React.createElement(PluridProvider, {
290
- metastate: pluridMetastate
291
- }, React.createElement(PluridRouterStatic, {
292
- path: pathname,
293
- directPlane: matchedPlane === null || matchedPlane === void 0 ? void 0 : matchedPlane.value,
294
- routes: routes,
295
- planes: planes,
296
- exterior: exterior,
297
- shell: shell,
298
- gateway: gateway,
299
- gatewayEndpoint: gatewayEndpoint,
300
- gatewayQuery: gatewayQuery,
301
- hostname: hostname
302
- }));
303
- let Wrap = wrapping(HelmetProvider, RoutedApplication, {
304
- context: helmet
305
- });
306
- for (const service of services) {
307
- const preserveProperties = (_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.providers) === null || _a === void 0 ? void 0 : _a[service.name];
308
- Wrap = wrapping(service.Provider, Wrap, Object.assign(Object.assign({}, service.properties), preserveProperties));
309
- }
310
- const content = renderToString(React.createElement(StyleSheetManager, {
311
- sheet: stylesheet.instance
312
- }, React.createElement(Wrap, null)));
313
- return content;
314
- }));
315
- }
316
- }
317
-
318
- const resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
319
- if (typeof planeMatch.data.component === "function") {
320
- return;
321
- }
322
- if (typeof planeMatch.data.component === "string") {
323
- return {
324
- name: planeMatch.data.component,
325
- url: elementqlEndpoint
326
- };
327
- }
328
- return {
329
- name: planeMatch.data.component.name,
330
- url: planeMatch.data.component.url || elementqlEndpoint
331
- };
332
- };
333
-
334
- const {IsoMatcher: PluridIsoMatcher} = routing;
335
-
336
- class PluridServer {
337
- constructor(configuration) {
338
- const {routes: routes, planes: planes, preserves: preserves, helmet: helmet, styles: styles, middleware: middleware, exterior: exterior, shell: shell, services: services, options: options, template: template, usePTTP: usePTTP, pttpHandler: pttpHandler, elementqlEndpoint: elementqlEndpoint} = configuration;
339
- this.routes = routes;
340
- this.planes = planes || [];
341
- this.preserves = preserves;
342
- this.helmet = helmet;
343
- this.styles = styles || [];
344
- this.middleware = middleware || [];
345
- this.exterior = exterior;
346
- this.shell = shell;
347
- this.services = services || [];
348
- this.options = this.handleOptions(options);
349
- this.template = template;
350
- this.usePTTP = usePTTP !== null && usePTTP !== void 0 ? usePTTP : false;
351
- this.pttpHandler = pttpHandler;
352
- this.elementqlEndpoint = elementqlEndpoint;
353
- this.serverApplication = express();
354
- this.port = DEFAULT_SERVER_PORT;
355
- this.isoMatcher = new PluridIsoMatcher({
356
- routes: this.routes,
357
- routePlanes: this.planes
358
- }, this.options.hostname);
359
- this.configureServer();
360
- this.handleEndpoints();
361
- process.addListener("SIGINT", (() => {
362
- this.stop();
363
- process.exit(0);
364
- }));
365
- }
366
- static analysis(pluridServer) {
367
- return {
368
- routes: pluridServer.routes,
369
- options: pluridServer.options
370
- };
371
- }
372
- start(port = this.port) {
373
- this.port = port;
374
- const serverlink = `http://localhost:${port}`;
375
- if (this.debugAllows("info")) {
376
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}\n`);
377
- }
378
- this.server = this.serverApplication.listen(port);
379
- this.open(serverlink);
380
- return this.server;
381
- }
382
- stop() {
383
- if (this.server) {
384
- if (this.debugAllows("info")) {
385
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}\n`);
386
- }
387
- this.server.close();
388
- } else {
389
- if (this.debugAllows("info")) {
390
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}\n`);
391
- }
392
- }
393
- }
394
- handle() {
395
- return {
396
- post: (path, ...handlers) => {
397
- this.serverApplication.post(path, ...handlers);
398
- return this.serverApplication;
399
- },
400
- patch: (path, ...handlers) => {
401
- this.serverApplication.patch(path, ...handlers);
402
- return this.serverApplication;
403
- },
404
- put: (path, ...handlers) => {
405
- this.serverApplication.put(path, ...handlers);
406
- return this.serverApplication;
407
- },
408
- delete: (path, ...handlers) => {
409
- this.serverApplication.delete(path, ...handlers);
410
- return this.serverApplication;
411
- }
412
- };
413
- }
414
- instance() {
415
- return this.serverApplication;
416
- }
417
- handleEndpoints() {
418
- this.serverApplication.get(CATCH_ALL_ROUTE, ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
419
- this.handleGetRequest(request, response, next);
420
- }))));
421
- if (this.usePTTP) {
422
- this.serverApplication.post(PTTP_ROUTE, json(), ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
423
- this.handlePTTPRequest(request, response);
424
- }))));
425
- }
426
- }
427
- handleGetRequest(request, response, next) {
428
- return __awaiter(this, void 0, void 0, (function*() {
429
- const requestID = request.requestID || uuid.generate();
430
- try {
431
- if (this.debugAllows("info")) {
432
- console.info(`[${time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`);
433
- }
434
- const ignorable = this.ignoreGetRequest(request.path);
435
- if (ignorable) {
436
- if (this.debugAllows("info")) {
437
- const requestTime = this.computeRequestTime(request);
438
- console.info(`[${time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`);
439
- }
440
- next();
441
- return;
442
- }
443
- const {preserveResponded: preserveResponded, preserveResult: preserveResult, preserveAfterServe: preserveAfterServe} = yield this.resolvePreserve(request, response);
444
- if (preserveResponded) {
445
- if (this.debugAllows("info")) {
446
- const requestTime = this.computeRequestTime(request);
447
- console.info(`[${time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`);
448
- }
449
- return;
450
- }
451
- const {externalRedirect: externalRedirect, matchingPath: matchingPath} = this.resolveMatchingPath(preserveResult, request.originalUrl);
452
- if (externalRedirect) {
453
- if (this.debugAllows("info")) {
454
- const requestTime = this.computeRequestTime(request);
455
- console.info(`[${time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`);
456
- }
457
- response.status(302).redirect(matchingPath);
458
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
459
- return;
460
- }
461
- const isoMatch = this.isoMatcher.match(matchingPath, "route");
462
- if (!isoMatch) {
463
- const isoMatchNotFound = this.isoMatcher.match(NOT_FOUND_ROUTE, "route");
464
- if (!isoMatchNotFound) {
465
- if (this.debugAllows("info")) {
466
- const requestTime = this.computeRequestTime(request);
467
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
468
- }
469
- response.status(404).send(NOT_FOUND_TEMPLATE);
470
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
471
- return;
472
- }
473
- const renderer = yield this.renderApplication(isoMatchNotFound, preserveResult);
474
- if (this.debugAllows("info")) {
475
- const requestTime = this.computeRequestTime(request);
476
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
477
- }
478
- response.status(404).send(renderer.html());
479
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
480
- response.status(404).end();
481
- return;
482
- }
483
- const renderer = yield this.renderApplication(isoMatch, preserveResult);
484
- if (this.debugAllows("info")) {
485
- const requestTime = this.computeRequestTime(request);
486
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`);
487
- }
488
- response.send(renderer.html());
489
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
490
- return;
491
- } catch (error) {
492
- if (this.debugAllows("error")) {
493
- const requestTime = this.computeRequestTime(request);
494
- console.error(`[${time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`, error);
495
- }
496
- response.status(500).send(SERVER_ERROR_TEMPLATE);
497
- return;
498
- }
499
- }));
500
- }
501
- handlePTTPRequest(request, response) {
502
- return __awaiter(this, void 0, void 0, (function*() {
503
- const requestID = request.requestID || uuid.generate();
504
- try {
505
- if (this.debugAllows("info")) {
506
- console.info(`[${time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`);
507
- }
508
- response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
509
- response.setHeader("Access-Control-Allow-Credentials", "true");
510
- const data = request.body;
511
- if (!data && !data.path) {
512
- if (this.debugAllows("warn")) {
513
- const requestTime = this.computeRequestTime(request);
514
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
515
- }
516
- response.status(400).end();
517
- return;
518
- }
519
- if (this.pttpHandler) {
520
- const pttpHandled = yield this.pttpHandler(data.path);
521
- if (pttpHandled) {
522
- if (this.debugAllows("info")) {
523
- const requestTime = this.computeRequestTime(request);
524
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`);
525
- }
526
- return;
527
- }
528
- }
529
- const planeMatch = this.isoMatcher.match(data.path);
530
- if (!planeMatch) {
531
- if (this.debugAllows("warn")) {
532
- const requestTime = this.computeRequestTime(request);
533
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
534
- }
535
- response.status(400).end();
536
- return;
537
- }
538
- const elementMatch = resolveElementFromPlaneMatch(planeMatch, this.elementqlEndpoint);
539
- if (!elementMatch) {
540
- if (this.debugAllows("warn")) {
541
- const requestTime = this.computeRequestTime(request);
542
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`);
543
- }
544
- response.status(404).end();
545
- return;
546
- }
547
- const elementURL = elementMatch.url;
548
- if (!elementURL) {
549
- if (this.debugAllows("warn")) {
550
- const requestTime = this.computeRequestTime(request);
551
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
552
- }
553
- response.status(400).end();
554
- return;
555
- }
556
- if (this.debugAllows("info")) {
557
- const requestTime = this.computeRequestTime(request);
558
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`);
559
- }
560
- const elementName = elementMatch.name;
561
- const linksTo = [];
562
- const element = {
563
- url: elementURL,
564
- name: elementName,
565
- json: {
566
- elements: [ {
567
- name: elementName
568
- } ]
569
- },
570
- linksTo: linksTo
571
- };
572
- response.json({
573
- element: element
574
- });
575
- } catch (error) {
576
- if (this.debugAllows("error")) {
577
- const requestTime = this.computeRequestTime(request);
578
- console.error(`[${time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`, error);
579
- }
580
- response.status(500).send(SERVER_ERROR_TEMPLATE);
581
- return;
582
- }
583
- }));
584
- }
585
- ignoreGetRequest(path) {
586
- for (const ignore of this.options.ignore) {
587
- const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
588
- if (path === normalizedIgnore) {
589
- return true;
590
- }
591
- if (normalizedIgnore.endsWith("/*")) {
592
- const curatedIgnore = normalizedIgnore.replace("/*", "");
593
- if (path.startsWith(curatedIgnore)) {
594
- return true;
595
- }
596
- }
597
- }
598
- return false;
599
- }
600
- resolveMatchingPath(preserveResult, path) {
601
- const redirect = preserveResult ? preserveResult.redirect : "";
602
- const externalRedirect = !!(redirect === null || redirect === void 0 ? void 0 : redirect.startsWith("http"));
603
- const matchingPath = redirect || path;
604
- return {
605
- externalRedirect: externalRedirect,
606
- matchingPath: matchingPath
607
- };
608
- }
609
- resolvePreserve(request, response) {
610
- return __awaiter(this, void 0, void 0, (function*() {
611
- const catchAll = this.preserves.find((preserve => preserve.serve === CATCH_ALL_ROUTE));
612
- const notFound = this.preserves.find((preserve => preserve.serve === NOT_FOUND_ROUTE));
613
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
614
- let preserveOnServe;
615
- let preserveAfterServe;
616
- let preserveOnError;
617
- if (isoMatch || catchAll || notFound) {
618
- const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find((preserve => preserve.serve === (isoMatch === null || isoMatch === void 0 ? void 0 : isoMatch.data.value)));
619
- if (preserve) {
620
- preserveOnServe = preserve.onServe;
621
- preserveAfterServe = preserve.afterServe;
622
- preserveOnError = preserve.onError;
623
- }
624
- }
625
- let preserveResult;
626
- if (preserveOnServe) {
627
- const transmission = {
628
- context: {
629
- route: request.originalUrl,
630
- match: isoMatch
631
- },
632
- request: request,
633
- response: response
634
- };
635
- try {
636
- preserveResult = yield preserveOnServe(transmission);
637
- if (preserveResult) {
638
- if (preserveResult.responded) {
639
- return {
640
- preserveResponded: true,
641
- preserveResult: preserveResult,
642
- preserveAfterServe: preserveAfterServe
643
- };
644
- }
645
- }
646
- } catch (error) {
647
- if (preserveOnError) {
648
- const onErrorResponse = yield preserveOnError(error, transmission);
649
- if (onErrorResponse) {
650
- if (onErrorResponse.responded) {
651
- return {
652
- preserveResponded: true,
653
- preserveResult: preserveResult,
654
- preserveAfterServe: preserveAfterServe
655
- };
656
- }
657
- if (!onErrorResponse.depreserve) {
658
- return {
659
- preserveResponded: false,
660
- preserveResult: preserveResult,
661
- preserveAfterServe: preserveAfterServe
662
- };
663
- }
664
- }
665
- }
666
- }
667
- }
668
- return {
669
- preserveResponded: false,
670
- preserveResult: preserveResult,
671
- preserveAfterServe: preserveAfterServe
672
- };
673
- }));
674
- }
675
- resolvePreserveAfterServe(preserveAfterServe, request, response) {
676
- return __awaiter(this, void 0, void 0, (function*() {
677
- if (preserveAfterServe) {
678
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
679
- const transmission = {
680
- context: {
681
- route: request.originalUrl,
682
- match: isoMatch
683
- },
684
- request: request,
685
- response: response
686
- };
687
- yield preserveAfterServe(transmission);
688
- }
689
- }));
690
- }
691
- handleGateway(path, request, preserveResult) {
692
- return __awaiter(this, void 0, void 0, (function*() {
693
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
694
- if (path !== gatewayEndpoint) {
695
- return;
696
- }
697
- ({
698
- path: {
699
- value: gatewayEndpoint
700
- },
701
- pathname: gatewayEndpoint,
702
- parameters: {},
703
- query: {
704
- __gatewayQuery: request.originalUrl
705
- },
706
- fragments: {
707
- texts: [],
708
- elements: []
709
- },
710
- route: gatewayEndpoint
711
- });
712
- return "";
713
- }));
714
- }
715
- renderApplication(isoMatch, preserveResult, matchedPlane) {
716
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
717
- return __awaiter(this, void 0, void 0, (function*() {
718
- const globals = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.globals;
719
- const mergedHtmlLanguage = ((_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _a === void 0 ? void 0 : _a.htmlLanguage) || ((_b = this.template) === null || _b === void 0 ? void 0 : _b.htmlLanguage);
720
- const pluridMetastate = yield serverComputeMetastate(isoMatch, this.routes, globals, this.options.hostname);
721
- const {content: content, styles: styles} = yield this.getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane);
722
- const stringedStyles = this.styles.reduce(((accumulator, style) => accumulator + style), "");
723
- const preserveStyles = ((_d = (_c = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _c === void 0 ? void 0 : _c.styles) === null || _d === void 0 ? void 0 : _d.join(" ")) || "";
724
- const mergedStyles = styles + stringedStyles + preserveStyles;
725
- const {helmet: helmet} = this.helmet;
726
- const head = helmet ? `\n ${helmet.meta.toString()}\n ${helmet.title.toString()}\n ${helmet.base.toString()}\n ${helmet.link.toString()}\n ${helmet.style.toString()}\n ${helmet.noscript.toString()}\n ${helmet.script.toString()}\n ` : "";
727
- const htmlAttributes = Object.assign(Object.assign({}, (_e = this.template) === null || _e === void 0 ? void 0 : _e.htmlAttributes), helmet === null || helmet === void 0 ? void 0 : helmet.htmlAttributes.toComponent());
728
- const mergedHtmlAttributes = recordToString(htmlAttributes) + (((_f = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _f === void 0 ? void 0 : _f.htmlAttributes) || "");
729
- const bodyAttributes = (helmet === null || helmet === void 0 ? void 0 : helmet.bodyAttributes.toString()) || "";
730
- const preserveBodyAttributes = ((_g = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _g === void 0 ? void 0 : _g.bodyAttributes) || "";
731
- const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
732
- const headScripts = ((_h = this.template) === null || _h === void 0 ? void 0 : _h.headScripts) || [];
733
- const mergedHeadScripts = [ ...headScripts, ...((_j = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _j === void 0 ? void 0 : _j.headScripts) || [] ];
734
- const bodyScripts = ((_k = this.template) === null || _k === void 0 ? void 0 : _k.bodyScripts) || [];
735
- const mergedBodyScripts = [ ...bodyScripts, ...((_l = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _l === void 0 ? void 0 : _l.bodyScripts) || [] ];
736
- const renderer = new PluridRenderer({
737
- htmlLanguage: mergedHtmlLanguage,
738
- head: head,
739
- htmlAttributes: mergedHtmlAttributes,
740
- bodyAttributes: mergedBodyAttributes,
741
- defaultStyle: (_m = this.template) === null || _m === void 0 ? void 0 : _m.defaultStyle,
742
- styles: mergedStyles,
743
- headScripts: mergedHeadScripts,
744
- bodyScripts: mergedBodyScripts,
745
- vendorScriptSource: (_o = this.template) === null || _o === void 0 ? void 0 : _o.vendorScriptSource,
746
- mainScriptSource: (_p = this.template) === null || _p === void 0 ? void 0 : _p.mainScriptSource,
747
- root: (_q = this.template) === null || _q === void 0 ? void 0 : _q.root,
748
- content: content,
749
- defaultPreloadedPluridMetastate: (_r = this.template) === null || _r === void 0 ? void 0 : _r.defaultPreloadedPluridMetastate,
750
- pluridMetastate: JSON.stringify(pluridMetastate),
751
- globals: globals,
752
- minify: (_s = this.template) === null || _s === void 0 ? void 0 : _s.minify
753
- });
754
- return renderer;
755
- }));
756
- }
757
- getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
758
- return __awaiter(this, void 0, void 0, (function*() {
759
- const stylesheet = new ServerStyleSheet;
760
- let content = "";
761
- let styles = "";
762
- try {
763
- const gateway = false;
764
- const gatewayQuery = "";
765
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
766
- const contentHandler = new PluridContentGenerator({
767
- services: this.services,
768
- stylesheet: stylesheet,
769
- exterior: this.exterior,
770
- shell: this.shell,
771
- helmet: this.helmet,
772
- routes: this.routes,
773
- planes: this.planes,
774
- pluridMetastate: pluridMetastate,
775
- gateway: gateway,
776
- gatewayEndpoint: gatewayEndpoint,
777
- gatewayQuery: gatewayQuery,
778
- preserveResult: preserveResult,
779
- pathname: isoMatch.match.value,
780
- hostname: this.options.hostname,
781
- matchedPlane: isoMatch.kind === "RoutePlane" ? {
782
- value: isoMatch.match.value
783
- } : undefined
784
- });
785
- content = yield contentHandler.render();
786
- styles = stylesheet.getStyleTags();
787
- } catch (error) {
788
- if (this.options.debug !== "none" && !this.options.quiet) {
789
- const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
790
- if (this.debugAllows("error")) {
791
- console.error(errorText, error);
792
- }
793
- }
794
- return {
795
- content: "",
796
- styles: ""
797
- };
798
- } finally {
799
- stylesheet.seal();
800
- }
801
- return {
802
- content: content,
803
- styles: styles
804
- };
805
- }));
806
- }
807
- computeRequestTime(request) {
808
- const requestTime = request.requestTime;
809
- if (!requestTime) {
810
- return "";
811
- }
812
- const now = Date.now();
813
- const difference = now - requestTime;
814
- return ` in ${difference} ms`;
815
- }
816
- handleOptions(partialOptions) {
817
- var _a, _b;
818
- const options = {
819
- serverName: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.serverName) || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
820
- hostname: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.hostname) || DEFAULT_SERVER_OPTIONS.HOSTNAME,
821
- quiet: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.quiet) || DEFAULT_SERVER_OPTIONS.QUIET,
822
- debug: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug) ? partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug : environment.production ? "error" : "info",
823
- compression: (_a = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.compression) !== null && _a !== void 0 ? _a : DEFAULT_SERVER_OPTIONS.COMPRESSION,
824
- open: (_b = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.open) !== null && _b !== void 0 ? _b : DEFAULT_SERVER_OPTIONS.OPEN,
825
- buildDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.buildDirectory) || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
826
- assetsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.assetsDirectory) || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
827
- gatewayEndpoint: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.gatewayEndpoint) || DEFAULT_SERVER_OPTIONS.GATEWAY,
828
- staticCache: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.staticCache) || 0,
829
- ignore: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.ignore) || [],
830
- stillsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stillsDirectory) || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
831
- stiller: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stiller) || defaultStillerOptions
832
- };
833
- return options;
834
- }
835
- configureServer() {
836
- const clientPath = path.join(this.options.buildDirectory, "./client");
837
- this.serverApplication.disable("x-powered-by");
838
- this.serverApplication.use(((request, _, next) => {
839
- const requestID = uuid.generate();
840
- request.requestID = requestID;
841
- const requestTime = Date.now();
842
- request.requestTime = requestTime;
843
- next();
844
- }));
845
- if (this.options.compression) {
846
- this.serverApplication.use(compression());
847
- this.serverApplication.get("/vendor.js", ((request, response, next) => {
848
- response.setHeader("Content-Type", "application/javascript");
849
- const vendorBrotliExists = fs.existsSync(path.join(clientPath, "vendor.js.br"));
850
- const acceptEncoding = request.header("Accept-Encoding");
851
- if ((acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("br")) && vendorBrotliExists) {
852
- request.url += ".br";
853
- response.set("Content-Encoding", "br");
854
- next();
855
- return;
856
- }
857
- next();
858
- }));
859
- }
860
- this.serverApplication.use(express.static(clientPath, {
861
- maxAge: this.options.staticCache
862
- }));
863
- this.loadMiddleware();
864
- }
865
- loadMiddleware() {
866
- for (const middleware of this.middleware) {
867
- this.serverApplication.use(((req, res, next) => middleware(req, res, next)));
868
- }
869
- }
870
- open(serverlink) {
871
- try {
872
- const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
873
- if (processDoNotOpen) {
874
- return;
875
- }
876
- if (this.options.open) {
877
- open(serverlink);
878
- }
879
- } catch (error) {
880
- return;
881
- }
882
- }
883
- debugAllows(level) {
884
- if (this.options.quiet) {
885
- return false;
886
- }
887
- if (this.options.debug === "none") {
888
- return false;
889
- }
890
- switch (level) {
891
- case "error":
892
- return true;
893
-
894
- case "warn":
895
- if (this.options.debug === "error") {
896
- return false;
897
- }
898
- return true;
899
-
900
- case "info":
901
- if (this.options.debug === "error" || this.options.debug === "warn") {
902
- return false;
903
- }
904
- return true;
905
-
906
- default:
907
- return false;
908
- }
909
- }
910
- }
911
-
912
- class LiveServer {
913
- constructor(options) {
914
- this.sockets = [];
915
- this.resolveOptions = options => {
916
- const defaultServerPath = "./source/server/index.ts";
917
- const resolvedOptions = {
918
- server: (options === null || options === void 0 ? void 0 : options.server) || defaultServerPath
919
- };
920
- return resolvedOptions;
921
- };
922
- this.options = this.resolveOptions(options);
923
- this.expressServer = express();
924
- this.setupExpressServer();
925
- this.httpServer = http.createServer(this.expressServer);
926
- this.setupHttpServer();
927
- }
928
- setupExpressServer() {}
929
- setupHttpServer() {
930
- this.httpServer.on("connection", (socket => {
931
- this.sockets.push(socket);
932
- socket.once("close", (() => {
933
- this.sockets.splice(this.sockets.indexOf(socket), 1);
934
- }));
935
- }));
936
- this.httpServer.on("error", (error => {
937
- throw error;
938
- }));
939
- }
940
- start() {}
941
- }
942
-
943
- const replacePluridResolution = html => {
944
- const normalResolution = "width: 1366px; height: 768px;";
945
- const zeroResolution = "width: 0px; height: 0px;";
946
- return html.replace(normalResolution, zeroResolution);
947
- };
948
-
949
- const isCurrentUserRoot = () => process.getuid() == 0;
950
-
951
- const render = (puppeteer, host, route, configuration) => __awaiter(void 0, void 0, void 0, (function*() {
952
- const start = Date.now();
953
- const browser = yield puppeteer.launch({
954
- defaultViewport: {
955
- width: 1366,
956
- height: 768
957
- },
958
- headless: true,
959
- args: isCurrentUserRoot() ? [ "--no-sandbox" ] : undefined
960
- });
961
- const page = yield browser.newPage();
962
- try {
963
- const url = host + route;
964
- yield page.goto(url, {
965
- waitUntil: configuration.waitUntil,
966
- timeout: configuration.timeout
967
- });
968
- } catch (err) {
969
- throw new Error(`${route} timed out.`);
970
- }
971
- const pageContent = yield page.content();
972
- const html = replacePluridResolution(pageContent);
973
- yield browser.close();
974
- const stilltime = Date.now() - start;
975
- console.info(`\tStilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
976
- return {
977
- route: route,
978
- html: html,
979
- stilltime: stilltime
980
- };
981
- }));
982
-
983
- class Stiller {
984
- constructor(options) {
985
- try {
986
- this.puppeteer = require("puppeteer");
987
- } catch (error) {
988
- console.error("could not load puppeteer: check puppeteer is installed");
989
- }
990
- const {host: host, routes: routes, configuration: configuration} = options;
991
- this.host = host;
992
- this.routes = routes;
993
- this.configuration = configuration;
994
- }
995
- still() {
996
- return __asyncGenerator(this, arguments, (function* still_1() {
997
- for (const route of this.routes) {
998
- yield yield __await(yield __await(render(this.puppeteer, this.host, route, this.configuration)));
999
- }
1000
- }));
1001
- }
1002
- }
1003
-
1004
- class StillsGenerator {
1005
- constructor(options) {
1006
- this.options = this.resolveOptions(options);
1007
- }
1008
- resolveOptions(options) {
1009
- var _a, _b;
1010
- const stillsGeneratorOptions = {
1011
- server: (_a = options === null || options === void 0 ? void 0 : options.server) !== null && _a !== void 0 ? _a : "./build/server.js",
1012
- build: (_b = options === null || options === void 0 ? void 0 : options.build) !== null && _b !== void 0 ? _b : "./build/"
1013
- };
1014
- return stillsGeneratorOptions;
1015
- }
1016
- initialize() {
1017
- return __awaiter(this, void 0, void 0, (function*() {
1018
- const serverPath = path.join(process.cwd(), this.options.server);
1019
- const buildPath = path.join(process.cwd(), this.options.build);
1020
- const pluridServer = require(serverPath);
1021
- const serverInformation = PluridServer.analysis(pluridServer);
1022
- const stillerOptions = serverInformation.options.stiller;
1023
- const serverPort = (yield detectPort(9900)) + "";
1024
- const child = fork(serverPath, [], {
1025
- stdio: "pipe",
1026
- env: {
1027
- PORT: serverPort,
1028
- PLURID_OPEN: "false"
1029
- }
1030
- });
1031
- const stillRoutes = [];
1032
- for (const route of serverInformation.routes) {
1033
- if (route.value.includes("/:")) {
1034
- continue;
1035
- }
1036
- if (stillerOptions.ignore.includes(route.value)) {
1037
- continue;
1038
- }
1039
- stillRoutes.push(route);
1040
- }
1041
- const stillRoutesPaths = stillRoutes.map((stillRoute => stillRoute.value));
1042
- console.info("\n\tParsed the following still routes:");
1043
- for (const stillRoutePath of stillRoutesPaths) {
1044
- console.info(`\t ${stillRoutePath}`);
1045
- }
1046
- yield new Promise((resolve => setTimeout(resolve, 1500)));
1047
- const startTime = Date.now();
1048
- const estimatedDuration = 3 * serverInformation.routes.length;
1049
- console.info(`\n\tStarting to generate stills... (this may take about ${estimatedDuration} seconds)\n`);
1050
- const stiller = new Stiller({
1051
- host: "http://localhost:" + serverPort,
1052
- routes: [ ...stillRoutesPaths ],
1053
- configuration: {
1054
- waitUntil: stillerOptions.waitUntil,
1055
- timeout: stillerOptions.timeout
1056
- }
1057
- });
1058
- const sequence = stiller.still();
1059
- const stills = [];
1060
- let next;
1061
- while (!(next = yield sequence.next()).done) {
1062
- stills.push(next.value);
1063
- }
1064
- const endTime = Date.now();
1065
- const duration = (endTime - startTime) / 1e3;
1066
- const plural = stills.length === 1 ? "" : "s";
1067
- console.info(`\n\tGenerated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.\n`);
1068
- const stillsPath = path.join(buildPath, "./stills");
1069
- yield promises.mkdir(stillsPath, {
1070
- recursive: true
1071
- });
1072
- const metadataFile = [];
1073
- for (const still of stills) {
1074
- if (!still) {
1075
- continue;
1076
- }
1077
- const stillName = uuid.generate() + ".json";
1078
- const metadataItem = {
1079
- route: still.route,
1080
- name: stillName
1081
- };
1082
- metadataFile.push(metadataItem);
1083
- const stillJSON = JSON.stringify(still, null, 4);
1084
- const stillFile = path.join(stillsPath, stillName);
1085
- yield promises.writeFile(stillFile, stillJSON);
1086
- }
1087
- const metadataFilePath = path.join(stillsPath, "metadata.json");
1088
- const metadataJSON = JSON.stringify(metadataFile, null, 4);
1089
- yield promises.writeFile(metadataFilePath, metadataJSON);
1090
- child.kill(2);
1091
- }));
1092
- }
1093
- }
1094
-
1095
- export { LiveServer as PluridLiveServer, StillsGenerator as PluridStillsGenerator, PluridServer as default };