@plurid/plurid-react-server 0.0.0-15 → 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 -1059
  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 -152
  14. package/distribution/data/interfaces/index.d.ts +0 -2
  15. package/distribution/data/interfaces/internal/index.d.ts +0 -84
  16. package/distribution/data/templates/index.d.ts +0 -2
  17. package/distribution/index.es.js +0 -1098
  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 -58
  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,1098 +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, routerProperties: routerProperties, 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
- routerProperties: routerProperties
303
- }));
304
- let Wrap = wrapping(HelmetProvider, RoutedApplication, {
305
- context: helmet
306
- });
307
- for (const service of services) {
308
- const preserveProperties = (_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.providers) === null || _a === void 0 ? void 0 : _a[service.name];
309
- Wrap = wrapping(service.Provider, Wrap, Object.assign(Object.assign({}, service.properties), preserveProperties));
310
- }
311
- const content = renderToString(React.createElement(StyleSheetManager, {
312
- sheet: stylesheet.instance
313
- }, React.createElement(Wrap, null)));
314
- return content;
315
- }));
316
- }
317
- }
318
-
319
- const resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
320
- if (typeof planeMatch.data.component === "function") {
321
- return;
322
- }
323
- if (typeof planeMatch.data.component === "string") {
324
- return {
325
- name: planeMatch.data.component,
326
- url: elementqlEndpoint
327
- };
328
- }
329
- return {
330
- name: planeMatch.data.component.name,
331
- url: planeMatch.data.component.url || elementqlEndpoint
332
- };
333
- };
334
-
335
- const {IsoMatcher: PluridIsoMatcher} = routing;
336
-
337
- class PluridServer {
338
- constructor(configuration) {
339
- const {routes: routes, planes: planes, preserves: preserves, helmet: helmet, styles: styles, middleware: middleware, exterior: exterior, shell: shell, routerProperties: routerProperties, services: services, options: options, template: template, usePTTP: usePTTP, pttpHandler: pttpHandler, elementqlEndpoint: elementqlEndpoint} = configuration;
340
- this.routes = routes;
341
- this.planes = planes || [];
342
- this.preserves = preserves;
343
- this.helmet = helmet;
344
- this.styles = styles || [];
345
- this.middleware = middleware || [];
346
- this.exterior = exterior;
347
- this.shell = shell;
348
- this.routerProperties = routerProperties || {};
349
- this.services = services || [];
350
- this.options = this.handleOptions(options);
351
- this.template = template;
352
- this.usePTTP = usePTTP !== null && usePTTP !== void 0 ? usePTTP : false;
353
- this.pttpHandler = pttpHandler;
354
- this.elementqlEndpoint = elementqlEndpoint;
355
- this.serverApplication = express();
356
- this.port = DEFAULT_SERVER_PORT;
357
- this.isoMatcher = new PluridIsoMatcher({
358
- routes: this.routes,
359
- routePlanes: this.planes
360
- }, this.options.hostname);
361
- this.configureServer();
362
- this.handleEndpoints();
363
- process.addListener("SIGINT", (() => {
364
- this.stop();
365
- process.exit(0);
366
- }));
367
- }
368
- static analysis(pluridServer) {
369
- return {
370
- routes: pluridServer.routes,
371
- options: pluridServer.options
372
- };
373
- }
374
- start(port = this.port) {
375
- this.port = port;
376
- const serverlink = `http://localhost:${port}`;
377
- if (this.debugAllows("info")) {
378
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}\n`);
379
- }
380
- this.server = this.serverApplication.listen(port);
381
- this.open(serverlink);
382
- return this.server;
383
- }
384
- stop() {
385
- if (this.server) {
386
- if (this.debugAllows("info")) {
387
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}\n`);
388
- }
389
- this.server.close();
390
- } else {
391
- if (this.debugAllows("info")) {
392
- console.info(`\n\t[${time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}\n`);
393
- }
394
- }
395
- }
396
- handle() {
397
- return {
398
- post: (path, ...handlers) => {
399
- this.serverApplication.post(path, ...handlers);
400
- return this.serverApplication;
401
- },
402
- patch: (path, ...handlers) => {
403
- this.serverApplication.patch(path, ...handlers);
404
- return this.serverApplication;
405
- },
406
- put: (path, ...handlers) => {
407
- this.serverApplication.put(path, ...handlers);
408
- return this.serverApplication;
409
- },
410
- delete: (path, ...handlers) => {
411
- this.serverApplication.delete(path, ...handlers);
412
- return this.serverApplication;
413
- }
414
- };
415
- }
416
- instance() {
417
- return this.serverApplication;
418
- }
419
- handleEndpoints() {
420
- this.serverApplication.get(CATCH_ALL_ROUTE, ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
421
- this.handleGetRequest(request, response, next);
422
- }))));
423
- if (this.usePTTP) {
424
- this.serverApplication.post(PTTP_ROUTE, json(), ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
425
- this.handlePTTPRequest(request, response);
426
- }))));
427
- }
428
- }
429
- handleGetRequest(request, response, next) {
430
- return __awaiter(this, void 0, void 0, (function*() {
431
- const requestID = request.requestID || uuid.generate();
432
- try {
433
- if (this.debugAllows("info")) {
434
- console.info(`[${time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`);
435
- }
436
- const ignorable = this.ignoreGetRequest(request.path);
437
- if (ignorable) {
438
- if (this.debugAllows("info")) {
439
- const requestTime = this.computeRequestTime(request);
440
- console.info(`[${time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`);
441
- }
442
- next();
443
- return;
444
- }
445
- const {preserveResponded: preserveResponded, preserveResult: preserveResult, preserveAfterServe: preserveAfterServe} = yield this.resolvePreserve(request, response);
446
- if (preserveResponded) {
447
- if (this.debugAllows("info")) {
448
- const requestTime = this.computeRequestTime(request);
449
- console.info(`[${time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`);
450
- }
451
- return;
452
- }
453
- const {externalRedirect: externalRedirect, matchingPath: matchingPath} = this.resolveMatchingPath(preserveResult, request.originalUrl);
454
- if (externalRedirect) {
455
- if (this.debugAllows("info")) {
456
- const requestTime = this.computeRequestTime(request);
457
- console.info(`[${time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`);
458
- }
459
- response.status(302).redirect(matchingPath);
460
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
461
- return;
462
- }
463
- const isoMatch = this.isoMatcher.match(matchingPath, "route");
464
- if (!isoMatch) {
465
- const isoMatchNotFound = this.isoMatcher.match(NOT_FOUND_ROUTE, "route");
466
- if (!isoMatchNotFound) {
467
- if (this.debugAllows("info")) {
468
- const requestTime = this.computeRequestTime(request);
469
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
470
- }
471
- response.status(404).send(NOT_FOUND_TEMPLATE);
472
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
473
- return;
474
- }
475
- const renderer = yield this.renderApplication(isoMatchNotFound, preserveResult);
476
- if (this.debugAllows("info")) {
477
- const requestTime = this.computeRequestTime(request);
478
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
479
- }
480
- response.status(404).send(renderer.html());
481
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
482
- response.status(404).end();
483
- return;
484
- }
485
- const renderer = yield this.renderApplication(isoMatch, preserveResult);
486
- if (this.debugAllows("info")) {
487
- const requestTime = this.computeRequestTime(request);
488
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`);
489
- }
490
- response.send(renderer.html());
491
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
492
- return;
493
- } catch (error) {
494
- if (this.debugAllows("error")) {
495
- const requestTime = this.computeRequestTime(request);
496
- console.error(`[${time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`, error);
497
- }
498
- response.status(500).send(SERVER_ERROR_TEMPLATE);
499
- return;
500
- }
501
- }));
502
- }
503
- handlePTTPRequest(request, response) {
504
- return __awaiter(this, void 0, void 0, (function*() {
505
- const requestID = request.requestID || uuid.generate();
506
- try {
507
- if (this.debugAllows("info")) {
508
- console.info(`[${time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`);
509
- }
510
- response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
511
- response.setHeader("Access-Control-Allow-Credentials", "true");
512
- const data = request.body;
513
- if (!data && !data.path) {
514
- if (this.debugAllows("warn")) {
515
- const requestTime = this.computeRequestTime(request);
516
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
517
- }
518
- response.status(400).end();
519
- return;
520
- }
521
- if (this.pttpHandler) {
522
- const pttpHandled = yield this.pttpHandler(data.path);
523
- if (pttpHandled) {
524
- if (this.debugAllows("info")) {
525
- const requestTime = this.computeRequestTime(request);
526
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`);
527
- }
528
- return;
529
- }
530
- }
531
- const planeMatch = this.isoMatcher.match(data.path);
532
- if (!planeMatch) {
533
- if (this.debugAllows("warn")) {
534
- const requestTime = this.computeRequestTime(request);
535
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
536
- }
537
- response.status(400).end();
538
- return;
539
- }
540
- const elementMatch = resolveElementFromPlaneMatch(planeMatch, this.elementqlEndpoint);
541
- if (!elementMatch) {
542
- if (this.debugAllows("warn")) {
543
- const requestTime = this.computeRequestTime(request);
544
- console.info(`[${time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`);
545
- }
546
- response.status(404).end();
547
- return;
548
- }
549
- const elementURL = elementMatch.url;
550
- if (!elementURL) {
551
- if (this.debugAllows("warn")) {
552
- const requestTime = this.computeRequestTime(request);
553
- console.info(`[${time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
554
- }
555
- response.status(400).end();
556
- return;
557
- }
558
- if (this.debugAllows("info")) {
559
- const requestTime = this.computeRequestTime(request);
560
- console.info(`[${time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`);
561
- }
562
- const elementName = elementMatch.name;
563
- const linksTo = [];
564
- const element = {
565
- url: elementURL,
566
- name: elementName,
567
- json: {
568
- elements: [ {
569
- name: elementName
570
- } ]
571
- },
572
- linksTo: linksTo
573
- };
574
- response.json({
575
- element: element
576
- });
577
- } catch (error) {
578
- if (this.debugAllows("error")) {
579
- const requestTime = this.computeRequestTime(request);
580
- console.error(`[${time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`, error);
581
- }
582
- response.status(500).send(SERVER_ERROR_TEMPLATE);
583
- return;
584
- }
585
- }));
586
- }
587
- ignoreGetRequest(path) {
588
- for (const ignore of this.options.ignore) {
589
- const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
590
- if (path === normalizedIgnore) {
591
- return true;
592
- }
593
- if (normalizedIgnore.endsWith("/*")) {
594
- const curatedIgnore = normalizedIgnore.replace("/*", "");
595
- if (path.startsWith(curatedIgnore)) {
596
- return true;
597
- }
598
- }
599
- }
600
- return false;
601
- }
602
- resolveMatchingPath(preserveResult, path) {
603
- const redirect = preserveResult ? preserveResult.redirect : "";
604
- const externalRedirect = !!(redirect === null || redirect === void 0 ? void 0 : redirect.startsWith("http"));
605
- const matchingPath = redirect || path;
606
- return {
607
- externalRedirect: externalRedirect,
608
- matchingPath: matchingPath
609
- };
610
- }
611
- resolvePreserve(request, response) {
612
- return __awaiter(this, void 0, void 0, (function*() {
613
- const catchAll = this.preserves.find((preserve => preserve.serve === CATCH_ALL_ROUTE));
614
- const notFound = this.preserves.find((preserve => preserve.serve === NOT_FOUND_ROUTE));
615
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
616
- let preserveOnServe;
617
- let preserveAfterServe;
618
- let preserveOnError;
619
- if (isoMatch || catchAll || notFound) {
620
- const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find((preserve => preserve.serve === (isoMatch === null || isoMatch === void 0 ? void 0 : isoMatch.data.value)));
621
- if (preserve) {
622
- preserveOnServe = preserve.onServe;
623
- preserveAfterServe = preserve.afterServe;
624
- preserveOnError = preserve.onError;
625
- }
626
- }
627
- let preserveResult;
628
- if (preserveOnServe) {
629
- const transmission = {
630
- context: {
631
- route: request.originalUrl,
632
- match: isoMatch
633
- },
634
- request: request,
635
- response: response
636
- };
637
- try {
638
- preserveResult = yield preserveOnServe(transmission);
639
- if (preserveResult) {
640
- if (preserveResult.responded) {
641
- return {
642
- preserveResponded: true,
643
- preserveResult: preserveResult,
644
- preserveAfterServe: preserveAfterServe
645
- };
646
- }
647
- }
648
- } catch (error) {
649
- if (preserveOnError) {
650
- const onErrorResponse = yield preserveOnError(error, transmission);
651
- if (onErrorResponse) {
652
- if (onErrorResponse.responded) {
653
- return {
654
- preserveResponded: true,
655
- preserveResult: preserveResult,
656
- preserveAfterServe: preserveAfterServe
657
- };
658
- }
659
- if (!onErrorResponse.depreserve) {
660
- return {
661
- preserveResponded: false,
662
- preserveResult: preserveResult,
663
- preserveAfterServe: preserveAfterServe
664
- };
665
- }
666
- }
667
- }
668
- }
669
- }
670
- return {
671
- preserveResponded: false,
672
- preserveResult: preserveResult,
673
- preserveAfterServe: preserveAfterServe
674
- };
675
- }));
676
- }
677
- resolvePreserveAfterServe(preserveAfterServe, request, response) {
678
- return __awaiter(this, void 0, void 0, (function*() {
679
- if (preserveAfterServe) {
680
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
681
- const transmission = {
682
- context: {
683
- route: request.originalUrl,
684
- match: isoMatch
685
- },
686
- request: request,
687
- response: response
688
- };
689
- yield preserveAfterServe(transmission);
690
- }
691
- }));
692
- }
693
- handleGateway(path, request, preserveResult) {
694
- return __awaiter(this, void 0, void 0, (function*() {
695
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
696
- if (path !== gatewayEndpoint) {
697
- return;
698
- }
699
- ({
700
- path: {
701
- value: gatewayEndpoint
702
- },
703
- pathname: gatewayEndpoint,
704
- parameters: {},
705
- query: {
706
- __gatewayQuery: request.originalUrl
707
- },
708
- fragments: {
709
- texts: [],
710
- elements: []
711
- },
712
- route: gatewayEndpoint
713
- });
714
- return "";
715
- }));
716
- }
717
- renderApplication(isoMatch, preserveResult, matchedPlane) {
718
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
719
- return __awaiter(this, void 0, void 0, (function*() {
720
- const globals = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.globals;
721
- 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);
722
- const pluridMetastate = yield serverComputeMetastate(isoMatch, this.routes, globals, this.options.hostname);
723
- const {content: content, styles: styles} = yield this.getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane);
724
- const stringedStyles = this.styles.reduce(((accumulator, style) => accumulator + style), "");
725
- 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(" ")) || "";
726
- const mergedStyles = styles + stringedStyles + preserveStyles;
727
- const {helmet: helmet} = this.helmet;
728
- 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 ` : "";
729
- 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());
730
- const mergedHtmlAttributes = recordToString(htmlAttributes) + (((_f = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _f === void 0 ? void 0 : _f.htmlAttributes) || "");
731
- const bodyAttributes = (helmet === null || helmet === void 0 ? void 0 : helmet.bodyAttributes.toString()) || "";
732
- const preserveBodyAttributes = ((_g = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _g === void 0 ? void 0 : _g.bodyAttributes) || "";
733
- const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
734
- const headScripts = ((_h = this.template) === null || _h === void 0 ? void 0 : _h.headScripts) || [];
735
- const mergedHeadScripts = [ ...headScripts, ...((_j = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _j === void 0 ? void 0 : _j.headScripts) || [] ];
736
- const bodyScripts = ((_k = this.template) === null || _k === void 0 ? void 0 : _k.bodyScripts) || [];
737
- const mergedBodyScripts = [ ...bodyScripts, ...((_l = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _l === void 0 ? void 0 : _l.bodyScripts) || [] ];
738
- const renderer = new PluridRenderer({
739
- htmlLanguage: mergedHtmlLanguage,
740
- head: head,
741
- htmlAttributes: mergedHtmlAttributes,
742
- bodyAttributes: mergedBodyAttributes,
743
- defaultStyle: (_m = this.template) === null || _m === void 0 ? void 0 : _m.defaultStyle,
744
- styles: mergedStyles,
745
- headScripts: mergedHeadScripts,
746
- bodyScripts: mergedBodyScripts,
747
- vendorScriptSource: (_o = this.template) === null || _o === void 0 ? void 0 : _o.vendorScriptSource,
748
- mainScriptSource: (_p = this.template) === null || _p === void 0 ? void 0 : _p.mainScriptSource,
749
- root: (_q = this.template) === null || _q === void 0 ? void 0 : _q.root,
750
- content: content,
751
- defaultPreloadedPluridMetastate: (_r = this.template) === null || _r === void 0 ? void 0 : _r.defaultPreloadedPluridMetastate,
752
- pluridMetastate: JSON.stringify(pluridMetastate),
753
- globals: globals,
754
- minify: (_s = this.template) === null || _s === void 0 ? void 0 : _s.minify
755
- });
756
- return renderer;
757
- }));
758
- }
759
- getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
760
- return __awaiter(this, void 0, void 0, (function*() {
761
- const stylesheet = new ServerStyleSheet;
762
- let content = "";
763
- let styles = "";
764
- try {
765
- const gateway = false;
766
- const gatewayQuery = "";
767
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
768
- const contentHandler = new PluridContentGenerator({
769
- services: this.services,
770
- stylesheet: stylesheet,
771
- exterior: this.exterior,
772
- shell: this.shell,
773
- routerProperties: this.routerProperties,
774
- helmet: this.helmet,
775
- routes: this.routes,
776
- planes: this.planes,
777
- pluridMetastate: pluridMetastate,
778
- gateway: gateway,
779
- gatewayEndpoint: gatewayEndpoint,
780
- gatewayQuery: gatewayQuery,
781
- preserveResult: preserveResult,
782
- pathname: isoMatch.match.value,
783
- hostname: this.options.hostname,
784
- matchedPlane: isoMatch.kind === "RoutePlane" ? {
785
- value: isoMatch.match.value
786
- } : undefined
787
- });
788
- content = yield contentHandler.render();
789
- styles = stylesheet.getStyleTags();
790
- } catch (error) {
791
- if (this.options.debug !== "none" && !this.options.quiet) {
792
- const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
793
- if (this.debugAllows("error")) {
794
- console.error(errorText, error);
795
- }
796
- }
797
- return {
798
- content: "",
799
- styles: ""
800
- };
801
- } finally {
802
- stylesheet.seal();
803
- }
804
- return {
805
- content: content,
806
- styles: styles
807
- };
808
- }));
809
- }
810
- computeRequestTime(request) {
811
- const requestTime = request.requestTime;
812
- if (!requestTime) {
813
- return "";
814
- }
815
- const now = Date.now();
816
- const difference = now - requestTime;
817
- return ` in ${difference} ms`;
818
- }
819
- handleOptions(partialOptions) {
820
- var _a, _b;
821
- const options = {
822
- serverName: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.serverName) || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
823
- hostname: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.hostname) || DEFAULT_SERVER_OPTIONS.HOSTNAME,
824
- quiet: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.quiet) || DEFAULT_SERVER_OPTIONS.QUIET,
825
- debug: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug) ? partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug : environment.production ? "error" : "info",
826
- compression: (_a = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.compression) !== null && _a !== void 0 ? _a : DEFAULT_SERVER_OPTIONS.COMPRESSION,
827
- open: (_b = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.open) !== null && _b !== void 0 ? _b : DEFAULT_SERVER_OPTIONS.OPEN,
828
- buildDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.buildDirectory) || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
829
- assetsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.assetsDirectory) || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
830
- gatewayEndpoint: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.gatewayEndpoint) || DEFAULT_SERVER_OPTIONS.GATEWAY,
831
- staticCache: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.staticCache) || 0,
832
- ignore: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.ignore) || [],
833
- stillsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stillsDirectory) || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
834
- stiller: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stiller) || defaultStillerOptions
835
- };
836
- return options;
837
- }
838
- configureServer() {
839
- const clientPath = path.join(this.options.buildDirectory, "./client");
840
- this.serverApplication.disable("x-powered-by");
841
- this.serverApplication.use(((request, _, next) => {
842
- const requestID = uuid.generate();
843
- request.requestID = requestID;
844
- const requestTime = Date.now();
845
- request.requestTime = requestTime;
846
- next();
847
- }));
848
- if (this.options.compression) {
849
- this.serverApplication.use(compression());
850
- this.serverApplication.get("/vendor.js", ((request, response, next) => {
851
- response.setHeader("Content-Type", "application/javascript");
852
- const vendorBrotliExists = fs.existsSync(path.join(clientPath, "vendor.js.br"));
853
- const acceptEncoding = request.header("Accept-Encoding");
854
- if ((acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("br")) && vendorBrotliExists) {
855
- request.url += ".br";
856
- response.set("Content-Encoding", "br");
857
- next();
858
- return;
859
- }
860
- next();
861
- }));
862
- }
863
- this.serverApplication.use(express.static(clientPath, {
864
- maxAge: this.options.staticCache
865
- }));
866
- this.loadMiddleware();
867
- }
868
- loadMiddleware() {
869
- for (const middleware of this.middleware) {
870
- this.serverApplication.use(((req, res, next) => middleware(req, res, next)));
871
- }
872
- }
873
- open(serverlink) {
874
- try {
875
- const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
876
- if (processDoNotOpen) {
877
- return;
878
- }
879
- if (this.options.open) {
880
- open(serverlink);
881
- }
882
- } catch (error) {
883
- return;
884
- }
885
- }
886
- debugAllows(level) {
887
- if (this.options.quiet) {
888
- return false;
889
- }
890
- if (this.options.debug === "none") {
891
- return false;
892
- }
893
- switch (level) {
894
- case "error":
895
- return true;
896
-
897
- case "warn":
898
- if (this.options.debug === "error") {
899
- return false;
900
- }
901
- return true;
902
-
903
- case "info":
904
- if (this.options.debug === "error" || this.options.debug === "warn") {
905
- return false;
906
- }
907
- return true;
908
-
909
- default:
910
- return false;
911
- }
912
- }
913
- }
914
-
915
- class LiveServer {
916
- constructor(options) {
917
- this.sockets = [];
918
- this.resolveOptions = options => {
919
- const defaultServerPath = "./source/server/index.ts";
920
- const resolvedOptions = {
921
- server: (options === null || options === void 0 ? void 0 : options.server) || defaultServerPath
922
- };
923
- return resolvedOptions;
924
- };
925
- this.options = this.resolveOptions(options);
926
- this.expressServer = express();
927
- this.setupExpressServer();
928
- this.httpServer = http.createServer(this.expressServer);
929
- this.setupHttpServer();
930
- }
931
- setupExpressServer() {}
932
- setupHttpServer() {
933
- this.httpServer.on("connection", (socket => {
934
- this.sockets.push(socket);
935
- socket.once("close", (() => {
936
- this.sockets.splice(this.sockets.indexOf(socket), 1);
937
- }));
938
- }));
939
- this.httpServer.on("error", (error => {
940
- throw error;
941
- }));
942
- }
943
- start() {}
944
- }
945
-
946
- const replacePluridResolution = html => {
947
- const normalResolution = "width: 1366px; height: 768px;";
948
- const zeroResolution = "width: 0px; height: 0px;";
949
- return html.replace(normalResolution, zeroResolution);
950
- };
951
-
952
- const isCurrentUserRoot = () => process.getuid() == 0;
953
-
954
- const render = (puppeteer, host, route, configuration) => __awaiter(void 0, void 0, void 0, (function*() {
955
- const start = Date.now();
956
- const browser = yield puppeteer.launch({
957
- defaultViewport: {
958
- width: 1366,
959
- height: 768
960
- },
961
- headless: true,
962
- args: isCurrentUserRoot() ? [ "--no-sandbox" ] : undefined
963
- });
964
- const page = yield browser.newPage();
965
- try {
966
- const url = host + route;
967
- yield page.goto(url, {
968
- waitUntil: configuration.waitUntil,
969
- timeout: configuration.timeout
970
- });
971
- } catch (err) {
972
- throw new Error(`${route} timed out.`);
973
- }
974
- const pageContent = yield page.content();
975
- const html = replacePluridResolution(pageContent);
976
- yield browser.close();
977
- const stilltime = Date.now() - start;
978
- console.info(`\tStilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
979
- return {
980
- route: route,
981
- html: html,
982
- stilltime: stilltime
983
- };
984
- }));
985
-
986
- class Stiller {
987
- constructor(options) {
988
- try {
989
- this.puppeteer = require("puppeteer");
990
- } catch (error) {
991
- console.error("could not load puppeteer: check puppeteer is installed");
992
- }
993
- const {host: host, routes: routes, configuration: configuration} = options;
994
- this.host = host;
995
- this.routes = routes;
996
- this.configuration = configuration;
997
- }
998
- still() {
999
- return __asyncGenerator(this, arguments, (function* still_1() {
1000
- for (const route of this.routes) {
1001
- yield yield __await(yield __await(render(this.puppeteer, this.host, route, this.configuration)));
1002
- }
1003
- }));
1004
- }
1005
- }
1006
-
1007
- class StillsGenerator {
1008
- constructor(options) {
1009
- this.options = this.resolveOptions(options);
1010
- }
1011
- resolveOptions(options) {
1012
- var _a, _b;
1013
- const stillsGeneratorOptions = {
1014
- server: (_a = options === null || options === void 0 ? void 0 : options.server) !== null && _a !== void 0 ? _a : "./build/server.js",
1015
- build: (_b = options === null || options === void 0 ? void 0 : options.build) !== null && _b !== void 0 ? _b : "./build/"
1016
- };
1017
- return stillsGeneratorOptions;
1018
- }
1019
- initialize() {
1020
- return __awaiter(this, void 0, void 0, (function*() {
1021
- const serverPath = path.join(process.cwd(), this.options.server);
1022
- const buildPath = path.join(process.cwd(), this.options.build);
1023
- const pluridServer = require(serverPath);
1024
- const serverInformation = PluridServer.analysis(pluridServer);
1025
- const stillerOptions = serverInformation.options.stiller;
1026
- const serverPort = (yield detectPort(9900)) + "";
1027
- const child = fork(serverPath, [], {
1028
- stdio: "pipe",
1029
- env: {
1030
- PORT: serverPort,
1031
- PLURID_OPEN: "false"
1032
- }
1033
- });
1034
- const stillRoutes = [];
1035
- for (const route of serverInformation.routes) {
1036
- if (route.value.includes("/:")) {
1037
- continue;
1038
- }
1039
- if (stillerOptions.ignore.includes(route.value)) {
1040
- continue;
1041
- }
1042
- stillRoutes.push(route);
1043
- }
1044
- const stillRoutesPaths = stillRoutes.map((stillRoute => stillRoute.value));
1045
- console.info("\n\tParsed the following still routes:");
1046
- for (const stillRoutePath of stillRoutesPaths) {
1047
- console.info(`\t ${stillRoutePath}`);
1048
- }
1049
- yield new Promise((resolve => setTimeout(resolve, 1500)));
1050
- const startTime = Date.now();
1051
- const estimatedDuration = 3 * serverInformation.routes.length;
1052
- console.info(`\n\tStarting to generate stills... (this may take about ${estimatedDuration} seconds)\n`);
1053
- const stiller = new Stiller({
1054
- host: "http://localhost:" + serverPort,
1055
- routes: [ ...stillRoutesPaths ],
1056
- configuration: {
1057
- waitUntil: stillerOptions.waitUntil,
1058
- timeout: stillerOptions.timeout
1059
- }
1060
- });
1061
- const sequence = stiller.still();
1062
- const stills = [];
1063
- let next;
1064
- while (!(next = yield sequence.next()).done) {
1065
- stills.push(next.value);
1066
- }
1067
- const endTime = Date.now();
1068
- const duration = (endTime - startTime) / 1e3;
1069
- const plural = stills.length === 1 ? "" : "s";
1070
- console.info(`\n\tGenerated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.\n`);
1071
- const stillsPath = path.join(buildPath, "./stills");
1072
- yield promises.mkdir(stillsPath, {
1073
- recursive: true
1074
- });
1075
- const metadataFile = [];
1076
- for (const still of stills) {
1077
- if (!still) {
1078
- continue;
1079
- }
1080
- const stillName = uuid.generate() + ".json";
1081
- const metadataItem = {
1082
- route: still.route,
1083
- name: stillName
1084
- };
1085
- metadataFile.push(metadataItem);
1086
- const stillJSON = JSON.stringify(still, null, 4);
1087
- const stillFile = path.join(stillsPath, stillName);
1088
- yield promises.writeFile(stillFile, stillJSON);
1089
- }
1090
- const metadataFilePath = path.join(stillsPath, "metadata.json");
1091
- const metadataJSON = JSON.stringify(metadataFile, null, 4);
1092
- yield promises.writeFile(metadataFilePath, metadataJSON);
1093
- child.kill(2);
1094
- }));
1095
- }
1096
- }
1097
-
1098
- export { LiveServer as PluridLiveServer, StillsGenerator as PluridStillsGenerator, PluridServer as default };