@plurid/plurid-react-server 0.0.0-15 → 0.0.0-17

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 +296 -0
  3. package/distribution/index.d.ts +296 -6
  4. package/distribution/index.js +1644 -1058
  5. package/distribution/index.js.map +1 -0
  6. package/distribution/index.mjs +1714 -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,1130 +1,1716 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // source/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ PluridLiveServer: () => LiveServer_default,
34
+ PluridStillsGenerator: () => StillsGenerator_default,
35
+ default: () => index_default
5
36
  });
6
-
7
- var fs = require("fs");
8
-
9
- var path = require("path");
10
-
11
- var express = require("express");
12
-
13
- var compression = require("compression");
14
-
15
- var bodyParser = require("body-parser");
16
-
17
- var open = require("open");
18
-
19
- var styledComponents = require("styled-components");
20
-
21
- var pluridFunctions = require("@plurid/plurid-functions");
22
-
23
- var pluridEngine = require("@plurid/plurid-engine");
24
-
25
- var pluridReact = require("@plurid/plurid-react");
26
-
27
- var htmlMinifier = require("html-minifier");
28
-
29
- var React = require("react");
30
-
31
- var server = require("react-dom/server");
32
-
33
- var reactHelmetAsync = require("react-helmet-async");
34
-
35
- var http = require("http");
36
-
37
- var child_process = require("child_process");
38
-
39
- var detectPort = require("detect-port");
40
-
41
- function _interopDefaultLegacy(e) {
42
- return e && typeof e === "object" && "default" in e ? e : {
43
- default: e
44
- };
45
- }
46
-
47
- var fs__default = _interopDefaultLegacy(fs);
48
-
49
- var path__default = _interopDefaultLegacy(path);
50
-
51
- var express__default = _interopDefaultLegacy(express);
52
-
53
- var compression__default = _interopDefaultLegacy(compression);
54
-
55
- var open__default = _interopDefaultLegacy(open);
56
-
57
- var React__default = _interopDefaultLegacy(React);
58
-
59
- var http__default = _interopDefaultLegacy(http);
60
-
61
- var detectPort__default = _interopDefaultLegacy(detectPort);
62
-
63
- function __awaiter(thisArg, _arguments, P, generator) {
64
- function adopt(value) {
65
- return value instanceof P ? value : new P((function(resolve) {
66
- resolve(value);
67
- }));
68
- }
69
- return new (P || (P = Promise))((function(resolve, reject) {
70
- function fulfilled(value) {
71
- try {
72
- step(generator.next(value));
73
- } catch (e) {
74
- reject(e);
75
- }
76
- }
77
- function rejected(value) {
78
- try {
79
- step(generator["throw"](value));
80
- } catch (e) {
81
- reject(e);
82
- }
83
- }
84
- function step(result) {
85
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
86
- }
87
- step((generator = generator.apply(thisArg, _arguments || [])).next());
88
- }));
89
- }
90
-
91
- function __await(v) {
92
- return this instanceof __await ? (this.v = v, this) : new __await(v);
93
- }
94
-
95
- function __asyncGenerator(thisArg, _arguments, generator) {
96
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
97
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
98
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
99
- return this;
100
- }, i;
101
- function verb(n) {
102
- if (g[n]) i[n] = function(v) {
103
- return new Promise((function(a, b) {
104
- q.push([ n, v, a, b ]) > 1 || resume(n, v);
105
- }));
106
- };
107
- }
108
- function resume(n, v) {
109
- try {
110
- step(g[n](v));
111
- } catch (e) {
112
- settle(q[0][3], e);
113
- }
114
- }
115
- function step(r) {
116
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
117
- }
118
- function fulfill(value) {
119
- resume("next", value);
120
- }
121
- function reject(value) {
122
- resume("throw", value);
123
- }
124
- function settle(f, v) {
125
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
126
- }
127
- }
128
-
129
- const DEFAULT_SERVER_PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
130
-
131
- const DEFAULT_SERVER_OPTIONS_SERVER_NAME = "Plurid Server";
132
-
133
- const DEFAULT_SERVER_OPTIONS_HOSTNAME = "origin";
134
-
135
- const DEFAULT_SERVER_OPTIONS_QUIET = false;
136
-
137
- const DEFAULT_SERVER_OPTIONS_COMPRESSION = true;
138
-
139
- const DEFAULT_SERVER_OPTIONS_OPEN = false;
140
-
141
- const DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY = "build";
142
-
143
- const DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY = "assets";
144
-
145
- const DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY = "stills";
146
-
147
- const DEFAULT_SERVER_OPTIONS_GATEWAY = "/gateway";
148
-
149
- const DEFAULT_SERVER_OPTIONS = {
150
- SERVER_NAME: DEFAULT_SERVER_OPTIONS_SERVER_NAME,
151
- HOSTNAME: DEFAULT_SERVER_OPTIONS_HOSTNAME,
152
- QUIET: DEFAULT_SERVER_OPTIONS_QUIET,
153
- COMPRESSION: DEFAULT_SERVER_OPTIONS_COMPRESSION,
154
- OPEN: DEFAULT_SERVER_OPTIONS_OPEN,
155
- BUILD_DIRECTORY: DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY,
156
- ASSETS_DIRECTORY: DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY,
157
- STILLS_DIRECTORY: DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY,
158
- GATEWAY: DEFAULT_SERVER_OPTIONS_GATEWAY
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // source/objects/Server/index.ts
40
+ var import_fs2 = __toESM(require("fs"));
41
+ var import_path2 = __toESM(require("path"));
42
+ var import_express = __toESM(require("express"));
43
+ var import_compression = __toESM(require("compression"));
44
+ var import_open = __toESM(require("open"));
45
+ var import_styled_components2 = require("styled-components");
46
+ var import_plurid_functions = require("@plurid/plurid-functions");
47
+ var import_plurid_engine = require("@plurid/plurid-engine");
48
+ var import_plurid_react2 = require("@plurid/plurid-react");
49
+
50
+ // source/data/constants/general/index.ts
51
+ var DEFAULT_SERVER_PORT = process.env.PORT ? parseInt(process.env.PORT) : 8080;
52
+ var DEFAULT_SERVER_OPTIONS_SERVER_NAME = "Plurid Server";
53
+ var DEFAULT_SERVER_OPTIONS_HOSTNAME = "origin";
54
+ var DEFAULT_SERVER_OPTIONS_QUIET = false;
55
+ var DEFAULT_SERVER_OPTIONS_COMPRESSION = true;
56
+ var DEFAULT_SERVER_OPTIONS_OPEN = false;
57
+ var DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY = "build";
58
+ var DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY = "assets";
59
+ var DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY = "stills";
60
+ var DEFAULT_SERVER_OPTIONS_GATEWAY = "/gateway";
61
+ var DEFAULT_SERVER_OPTIONS = {
62
+ SERVER_NAME: DEFAULT_SERVER_OPTIONS_SERVER_NAME,
63
+ HOSTNAME: DEFAULT_SERVER_OPTIONS_HOSTNAME,
64
+ QUIET: DEFAULT_SERVER_OPTIONS_QUIET,
65
+ COMPRESSION: DEFAULT_SERVER_OPTIONS_COMPRESSION,
66
+ OPEN: DEFAULT_SERVER_OPTIONS_OPEN,
67
+ BUILD_DIRECTORY: DEFAULT_SERVER_OPTIONS_BUILD_DIRECTORY,
68
+ ASSETS_DIRECTORY: DEFAULT_SERVER_OPTIONS_ASSETS_DIRECTORY,
69
+ STILLS_DIRECTORY: DEFAULT_SERVER_OPTIONS_STILLS_DIRECTORY,
70
+ GATEWAY: DEFAULT_SERVER_OPTIONS_GATEWAY
159
71
  };
160
-
161
- const DEFAULT_RENDERER_LANGUAGE = "en";
162
-
163
- const DEFAULT_RENDERER_ROOT = "root";
164
-
165
- const DEFAULT_RENDERER_PLURID_STATE = "{}";
166
-
167
- const DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE = "/vendor.js";
168
-
169
- const DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE = "/index.js";
170
-
171
- const DEFAULT__PRELOADED_PLURID_METASTATE__ = "__PRELOADED_PLURID_METASTATE__";
172
-
173
- const CATCH_ALL_ROUTE = "*";
174
-
175
- const NOT_FOUND_ROUTE = process.env.PLURID_SERVER_NOT_FOUND_ROUTE || "/not-found";
176
-
177
- const PTTP_ROUTE = process.env.PLURID_SERVER_PTTP_ROUTE || "/pttp";
178
-
179
- const environment = {
180
- production: process.env.ENV_MODE === "production",
181
- development: process.env.ENV_MODE === "development"
72
+ var DEFAULT_RENDERER_LANGUAGE = "en";
73
+ var DEFAULT_RENDERER_ROOT = "root";
74
+ var DEFAULT_RENDERER_PLURID_STATE = "{}";
75
+ var DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE = "/vendor.js";
76
+ var DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE = "/index.js";
77
+ var DEFAULT__PRELOADED_PLURID_METASTATE__ = "__PRELOADED_PLURID_METASTATE__";
78
+ var CATCH_ALL_ROUTE = "*";
79
+ var CATCH_ALL_ROUTE_PATTERN = /.*/;
80
+ var NOT_FOUND_ROUTE = process.env.PLURID_SERVER_NOT_FOUND_ROUTE || "/not-found";
81
+ var PTTP_ROUTE = process.env.PLURID_SERVER_PTTP_ROUTE || "/pttp";
82
+ var environment = {
83
+ production: process.env.ENV_MODE === "production",
84
+ development: process.env.ENV_MODE === "development"
182
85
  };
183
86
 
184
- const defaultStillerOptions = {
185
- waitUntil: "networkidle0",
186
- timeout: 3e4,
187
- ignore: []
87
+ // source/data/constants/stiller/index.ts
88
+ var defaultStillerOptions = {
89
+ waitUntil: "networkidle0",
90
+ timeout: 3e4,
91
+ ignore: []
188
92
  };
189
93
 
190
- const cleanTemplate = template => htmlMinifier.minify(template, {
191
- collapseWhitespace: true,
192
- conservativeCollapse: true,
193
- collapseInlineTagWhitespace: false
194
- });
195
-
196
- const resolveBackgroundStyle = store => {
197
- var _a;
198
- const defaultBackground = {
199
- gradientBackground: "hsl(220, 10%, 32%)",
200
- gradientForeground: "hsl(220, 10%, 18%)"
201
- };
202
- try {
203
- const storeJSON = JSON.parse(store);
204
- const generalPluridTheme = (_a = storeJSON === null || storeJSON === void 0 ? void 0 : storeJSON.themes) === null || _a === void 0 ? void 0 : _a.general;
205
- if (!generalPluridTheme) {
206
- return defaultBackground;
207
- }
208
- const gradientBackground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorTertiary : generalPluridTheme.backgroundColorPrimary;
209
- const gradientForeground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorPrimary : generalPluridTheme.backgroundColorTertiary;
210
- return {
211
- gradientBackground: gradientBackground,
212
- gradientForeground: gradientForeground
213
- };
214
- } catch (error) {
215
- return defaultBackground;
94
+ // source/utilities/template/index.ts
95
+ var import_html_minifier_terser = require("html-minifier-terser");
96
+ var cleanTemplate = (template2) => {
97
+ return (0, import_html_minifier_terser.minify)(
98
+ template2,
99
+ {
100
+ collapseWhitespace: true,
101
+ conservativeCollapse: true,
102
+ collapseInlineTagWhitespace: false
216
103
  }
104
+ );
217
105
  };
218
-
219
- const recordToString = record => {
220
- if (!record) {
221
- return "";
106
+ var resolveBackgroundStyle = (store) => {
107
+ const defaultBackground = {
108
+ gradientBackground: "hsl(220, 10%, 32%)",
109
+ gradientForeground: "hsl(220, 10%, 18%)"
110
+ };
111
+ try {
112
+ const storeJSON = JSON.parse(store);
113
+ const generalPluridTheme = storeJSON?.themes?.general;
114
+ if (!generalPluridTheme) {
115
+ return defaultBackground;
222
116
  }
223
- let recordString = "";
224
- for (const [key, value] of Object.entries(record)) {
225
- recordString += `${key}="${value}"`;
226
- }
227
- return recordString;
117
+ const gradientBackground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorTertiary : generalPluridTheme.backgroundColorPrimary;
118
+ const gradientForeground = generalPluridTheme.type === "dark" ? generalPluridTheme.backgroundColorPrimary : generalPluridTheme.backgroundColorTertiary;
119
+ return {
120
+ gradientBackground,
121
+ gradientForeground
122
+ };
123
+ } catch (error) {
124
+ return defaultBackground;
125
+ }
228
126
  };
229
-
230
- const assetsPathRewrite = content => content.replace(/="client\//g, '="/');
231
-
232
- const globalsInjector = globals => {
233
- let globalsScript = "";
234
- for (const [key, value] of Object.entries(globals)) {
235
- const globalScript = `window.${key} = ${value};\n`;
236
- globalsScript += globalScript;
237
- }
238
- return globalsScript;
127
+ var escapeAttribute = (value) => {
128
+ return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
129
+ };
130
+ var recordToString = (record) => {
131
+ if (!record) {
132
+ return "";
133
+ }
134
+ return Object.entries(record).map(([key, value]) => `${key}="${escapeAttribute(value)}"`).join(" ");
135
+ };
136
+ var assetsPathRewrite = (content) => {
137
+ return content.replace(
138
+ /="client\//g,
139
+ '="/'
140
+ );
141
+ };
142
+ var safeStore = (store) => {
143
+ return store.replace(
144
+ /</g,
145
+ "\\u003c"
146
+ );
147
+ };
148
+ var globalsInjector = (globals) => {
149
+ let globalsScript = "";
150
+ for (const [key, value] of Object.entries(globals)) {
151
+ const globalScript = `window.${key} = ${value};
152
+ `;
153
+ globalsScript += globalScript;
154
+ }
155
+ return globalsScript;
239
156
  };
240
157
 
241
- 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`);
158
+ // source/data/templates/index.ts
159
+ var NOT_FOUND_TEMPLATE = cleanTemplate(`
160
+ <!DOCTYPE html>
161
+ <html>
162
+ <head>
163
+ <title>[404] Not Found</title>
164
+ <style>
165
+ html, body {
166
+ margin: 0;
167
+ background: #242b33;
168
+ color: #ddd;
169
+ user-select: none;
170
+ }
242
171
 
243
- 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`);
172
+ .not-found {
173
+ position: absolute;
174
+ top: 50%;
175
+ left: 50%;
176
+ transform: translate(-50%, -50%);
177
+ font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;
178
+ }
179
+ </style>
180
+ </head>
181
+
182
+ <body>
183
+ <div class="not-found">[404] Not Found</div>
184
+ </body>
185
+ </html>
186
+ `);
187
+ var SERVER_ERROR_TEMPLATE = cleanTemplate(`
188
+ <!DOCTYPE html>
189
+ <html>
190
+ <head>
191
+ <title>[500] Server Error</title>
192
+ <style>
193
+ html, body {
194
+ margin: 0;
195
+ background: #242b33;
196
+ color: #ddd;
197
+ user-select: none;
198
+ }
244
199
 
245
- const template = data => {
246
- 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;
247
- const injectedGlobals = globalsInjector(globals);
248
- 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 `;
249
- if (!minify) {
250
- return templateString;
251
- }
252
- return cleanTemplate(templateString);
200
+ .error {
201
+ position: absolute;
202
+ top: 50%;
203
+ left: 50%;
204
+ transform: translate(-50%, -50%);
205
+ font-family: 'Ubuntu', -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto;
206
+ }
207
+ </style>
208
+ </head>
209
+
210
+ <body>
211
+ <div class="error">[500] Server Error</div>
212
+ </body>
213
+ </html>
214
+ `);
215
+
216
+ // source/objects/Renderer/template/index.ts
217
+ var template = async (data) => {
218
+ const {
219
+ htmlLanguage,
220
+ head,
221
+ htmlAttributes,
222
+ bodyAttributes,
223
+ defaultStyle,
224
+ styles,
225
+ headScripts,
226
+ bodyScripts,
227
+ vendorScriptSource,
228
+ mainScriptSource,
229
+ root,
230
+ content,
231
+ defaultPreloadedPluridMetastate,
232
+ pluridMetastate,
233
+ globals,
234
+ minify: minify2
235
+ } = data;
236
+ const injectedGlobals = globalsInjector(globals);
237
+ const templateString = `
238
+ <!DOCTYPE html>
239
+ <html lang="${htmlLanguage}" ${htmlAttributes}>
240
+ <head>
241
+ ${head}
242
+
243
+ ${defaultStyle && `<style>
244
+ ${defaultStyle}
245
+ </style>`}
246
+
247
+ ${styles}
248
+
249
+ ${headScripts.join("\n")}
250
+
251
+ ${vendorScriptSource ? `<script src="${vendorScriptSource}"></script>` : ""}
252
+ <script defer src="${mainScriptSource}"></script>
253
+ </head>
254
+ <body ${bodyAttributes}>
255
+ <div id="${root}">${content}</div>
256
+
257
+ <script>
258
+ ${injectedGlobals}
259
+ window.${defaultPreloadedPluridMetastate} = ${safeStore(pluridMetastate)};
260
+ </script>
261
+
262
+ ${bodyScripts.join("\n")}
263
+ </body>
264
+ </html>
265
+ `;
266
+ if (!minify2) {
267
+ return templateString;
268
+ }
269
+ return cleanTemplate(templateString);
253
270
  };
254
-
255
- class PluridRenderer {
256
- constructor(configuration) {
257
- 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;
258
- const {gradientBackground: gradientBackground, gradientForeground: gradientForeground} = resolveBackgroundStyle("");
259
- const defaultStyleBasic = `\n body {\n background: radial-gradient(ellipse at center, ${gradientBackground} 0%, ${gradientForeground} 100%);\n height: 100%;\n margin: 0;\n }\n `;
260
- this.htmlLanguage = htmlLanguage || DEFAULT_RENDERER_LANGUAGE;
261
- this.head = head || "";
262
- this.htmlAttributes = htmlAttributes;
263
- this.bodyAttributes = bodyAttributes || "";
264
- this.defaultStyle = defaultStyle !== null && defaultStyle !== void 0 ? defaultStyle : defaultStyleBasic;
265
- this.styles = styles;
266
- this.headScripts = headScripts;
267
- this.bodyScripts = bodyScripts;
268
- this.vendorScriptSource = vendorScriptSource || DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE;
269
- this.mainScriptSource = mainScriptSource || DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE;
270
- this.root = root || DEFAULT_RENDERER_ROOT;
271
- this.content = assetsPathRewrite(content) || "";
272
- this.defaultPreloadedPluridMetastate = defaultPreloadedPluridMetastate || DEFAULT__PRELOADED_PLURID_METASTATE__;
273
- this.pluridMetastate = pluridMetastate || DEFAULT_RENDERER_PLURID_STATE;
274
- this.globals = globals !== null && globals !== void 0 ? globals : {};
275
- this.minify = minify !== null && minify !== void 0 ? minify : true;
276
- }
277
- html() {
278
- const data = {
279
- htmlLanguage: this.htmlLanguage,
280
- head: this.head,
281
- htmlAttributes: this.htmlAttributes,
282
- bodyAttributes: this.bodyAttributes,
283
- defaultStyle: this.defaultStyle,
284
- styles: this.styles,
285
- headScripts: this.headScripts,
286
- bodyScripts: this.bodyScripts,
287
- vendorScriptSource: this.vendorScriptSource,
288
- mainScriptSource: this.mainScriptSource,
289
- root: this.root,
290
- content: this.content,
291
- defaultPreloadedPluridMetastate: this.defaultPreloadedPluridMetastate,
292
- pluridMetastate: this.pluridMetastate,
293
- globals: this.globals,
294
- minify: this.minify
295
- };
296
- return template(data);
297
- }
298
- }
299
-
300
- const wrapping = (WrappedComponent, WrappeeComponent, properties) => class extends React__default["default"].Component {
271
+ var template_default = template;
272
+
273
+ // source/objects/Renderer/index.ts
274
+ var PluridRenderer = class {
275
+ htmlLanguage;
276
+ head;
277
+ htmlAttributes;
278
+ bodyAttributes;
279
+ defaultStyle;
280
+ styles;
281
+ headScripts;
282
+ bodyScripts;
283
+ vendorScriptSource;
284
+ mainScriptSource;
285
+ root;
286
+ content;
287
+ defaultPreloadedPluridMetastate;
288
+ pluridMetastate;
289
+ globals;
290
+ minify;
291
+ constructor(configuration) {
292
+ const {
293
+ htmlLanguage,
294
+ head,
295
+ htmlAttributes,
296
+ bodyAttributes,
297
+ defaultStyle,
298
+ styles,
299
+ headScripts,
300
+ bodyScripts,
301
+ vendorScriptSource,
302
+ mainScriptSource,
303
+ content,
304
+ root,
305
+ defaultPreloadedPluridMetastate,
306
+ pluridMetastate,
307
+ globals,
308
+ minify: minify2
309
+ } = configuration;
310
+ const {
311
+ gradientBackground,
312
+ gradientForeground
313
+ // The metastate carries `themes.general` (see `serverComputeMetastate`), so the SSR'd background
314
+ // gradient matches the active theme; `resolveBackgroundStyle` falls back to a default if it can't parse.
315
+ } = resolveBackgroundStyle(pluridMetastate || "");
316
+ const defaultStyleBasic = `
317
+ body {
318
+ background: radial-gradient(ellipse at center, ${gradientBackground} 0%, ${gradientForeground} 100%);
319
+ height: 100%;
320
+ margin: 0;
321
+ }
322
+ `;
323
+ this.htmlLanguage = htmlLanguage || DEFAULT_RENDERER_LANGUAGE;
324
+ this.head = head || "";
325
+ this.htmlAttributes = htmlAttributes;
326
+ this.bodyAttributes = bodyAttributes || "";
327
+ this.defaultStyle = defaultStyle ?? defaultStyleBasic;
328
+ this.styles = styles;
329
+ this.headScripts = headScripts;
330
+ this.bodyScripts = bodyScripts;
331
+ this.vendorScriptSource = vendorScriptSource ?? DEFAULT_RENDERER_VENDOR_SCRIPT_SOURCE;
332
+ this.mainScriptSource = mainScriptSource || DEFAULT_RENDERER_MAIN_SCRIPT_SOURCE;
333
+ this.root = root || DEFAULT_RENDERER_ROOT;
334
+ this.content = assetsPathRewrite(content) || "";
335
+ this.defaultPreloadedPluridMetastate = defaultPreloadedPluridMetastate || DEFAULT__PRELOADED_PLURID_METASTATE__;
336
+ this.pluridMetastate = pluridMetastate || DEFAULT_RENDERER_PLURID_STATE;
337
+ this.globals = globals ?? {};
338
+ this.minify = minify2 ?? true;
339
+ }
340
+ async html() {
341
+ const data = {
342
+ htmlLanguage: this.htmlLanguage,
343
+ head: this.head,
344
+ htmlAttributes: this.htmlAttributes,
345
+ bodyAttributes: this.bodyAttributes,
346
+ defaultStyle: this.defaultStyle,
347
+ styles: this.styles,
348
+ headScripts: this.headScripts,
349
+ bodyScripts: this.bodyScripts,
350
+ vendorScriptSource: this.vendorScriptSource,
351
+ mainScriptSource: this.mainScriptSource,
352
+ root: this.root,
353
+ content: this.content,
354
+ defaultPreloadedPluridMetastate: this.defaultPreloadedPluridMetastate,
355
+ pluridMetastate: this.pluridMetastate,
356
+ globals: this.globals,
357
+ minify: this.minify
358
+ };
359
+ return template_default(data);
360
+ }
361
+ };
362
+ var Renderer_default = PluridRenderer;
363
+
364
+ // source/objects/ContentGenerator/index.tsx
365
+ var import_react2 = __toESM(require("react"));
366
+ var import_server = require("react-dom/server");
367
+ var import_styled_components = require("styled-components");
368
+ var import_react_helmet_async = require("react-helmet-async");
369
+ var import_plurid_react = require("@plurid/plurid-react");
370
+
371
+ // source/utilities/wrapping/index.tsx
372
+ var import_react = __toESM(require("react"));
373
+ var wrapping = (WrappedComponent, WrappeeComponent, properties) => {
374
+ return class extends import_react.default.Component {
301
375
  constructor(props) {
302
- super(props);
376
+ super(props);
303
377
  }
304
378
  render() {
305
- return React__default["default"].createElement(WrappedComponent, Object.assign({}, properties), React__default["default"].createElement(WrappeeComponent, null));
379
+ return /* @__PURE__ */ import_react.default.createElement(
380
+ WrappedComponent,
381
+ {
382
+ ...properties
383
+ },
384
+ /* @__PURE__ */ import_react.default.createElement(WrappeeComponent, null)
385
+ );
306
386
  }
387
+ };
307
388
  };
308
-
309
- class PluridContentGenerator {
310
- constructor(data) {
311
- this.data = data;
389
+ var wrapping_default = wrapping;
390
+
391
+ // source/objects/ContentGenerator/index.tsx
392
+ var PluridContentGenerator = class {
393
+ data;
394
+ constructor(data) {
395
+ this.data = data;
396
+ }
397
+ async render() {
398
+ const {
399
+ pluridMetastate,
400
+ routes,
401
+ planes,
402
+ exterior,
403
+ shell,
404
+ routerProperties,
405
+ gateway,
406
+ gatewayEndpoint,
407
+ gatewayQuery,
408
+ helmet,
409
+ services,
410
+ stylesheet,
411
+ preserveResult,
412
+ matchedPlane,
413
+ pathname,
414
+ hostname
415
+ } = this.data;
416
+ const RoutedApplication = () => /* @__PURE__ */ import_react2.default.createElement(
417
+ import_plurid_react.PluridProvider,
418
+ {
419
+ metastate: pluridMetastate
420
+ },
421
+ /* @__PURE__ */ import_react2.default.createElement(
422
+ import_plurid_react.PluridRouterStatic,
423
+ {
424
+ path: pathname,
425
+ directPlane: matchedPlane?.value,
426
+ routes,
427
+ planes,
428
+ exterior,
429
+ shell,
430
+ gateway,
431
+ gatewayEndpoint,
432
+ gatewayQuery,
433
+ hostname,
434
+ routerProperties
435
+ }
436
+ )
437
+ );
438
+ let Wrap = wrapping_default(
439
+ import_react_helmet_async.HelmetProvider,
440
+ RoutedApplication,
441
+ {
442
+ context: helmet
443
+ }
444
+ );
445
+ for (const service of services) {
446
+ const preserveProperties = preserveResult?.providers?.[service.name];
447
+ Wrap = wrapping_default(
448
+ service.Provider,
449
+ Wrap,
450
+ {
451
+ ...service.properties,
452
+ ...preserveProperties
453
+ }
454
+ );
312
455
  }
313
- render() {
314
- var _a;
315
- return __awaiter(this, void 0, void 0, (function*() {
316
- 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;
317
- const RoutedApplication = () => React__default["default"].createElement(pluridReact.PluridProvider, {
318
- metastate: pluridMetastate
319
- }, React__default["default"].createElement(pluridReact.PluridRouterStatic, {
320
- path: pathname,
321
- directPlane: matchedPlane === null || matchedPlane === void 0 ? void 0 : matchedPlane.value,
322
- routes: routes,
323
- planes: planes,
324
- exterior: exterior,
325
- shell: shell,
326
- gateway: gateway,
327
- gatewayEndpoint: gatewayEndpoint,
328
- gatewayQuery: gatewayQuery,
329
- hostname: hostname,
330
- routerProperties: routerProperties
331
- }));
332
- let Wrap = wrapping(reactHelmetAsync.HelmetProvider, RoutedApplication, {
333
- context: helmet
334
- });
335
- for (const service of services) {
336
- const preserveProperties = (_a = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.providers) === null || _a === void 0 ? void 0 : _a[service.name];
337
- Wrap = wrapping(service.Provider, Wrap, Object.assign(Object.assign({}, service.properties), preserveProperties));
338
- }
339
- const content = server.renderToString(React__default["default"].createElement(styledComponents.StyleSheetManager, {
340
- sheet: stylesheet.instance
341
- }, React__default["default"].createElement(Wrap, null)));
342
- return content;
343
- }));
456
+ const content = (0, import_server.renderToString)(
457
+ /* @__PURE__ */ import_react2.default.createElement(
458
+ import_styled_components.StyleSheetManager,
459
+ {
460
+ sheet: stylesheet.instance
461
+ },
462
+ /* @__PURE__ */ import_react2.default.createElement(Wrap, null)
463
+ )
464
+ );
465
+ return content;
466
+ }
467
+ };
468
+ var ContentGenerator_default = PluridContentGenerator;
469
+
470
+ // source/objects/StillsManager/index.ts
471
+ var import_path = __toESM(require("path"));
472
+ var import_fs = require("fs");
473
+ var StillsManager = class {
474
+ options;
475
+ stills = /* @__PURE__ */ new Map();
476
+ constructor(options) {
477
+ this.options = options;
478
+ this.findStills();
479
+ }
480
+ get(url) {
481
+ const still = this.stills.get(url);
482
+ if (!still) {
483
+ return;
344
484
  }
345
- }
346
-
347
- const resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
348
- if (typeof planeMatch.data.component === "function") {
349
- return;
485
+ return still.html;
486
+ }
487
+ async findStills() {
488
+ const {
489
+ buildDirectory,
490
+ stillsDirectory
491
+ } = this.options;
492
+ const stillsLocation = `${buildDirectory}/${stillsDirectory}`;
493
+ const stillsPath = import_path.default.join(process.cwd(), stillsLocation);
494
+ if (!(0, import_fs.existsSync)(stillsPath)) {
495
+ return;
350
496
  }
351
- if (typeof planeMatch.data.component === "string") {
352
- return {
353
- name: planeMatch.data.component,
354
- url: elementqlEndpoint
355
- };
497
+ try {
498
+ const stillsMetadata = import_path.default.join(stillsPath, "metadata.json");
499
+ const stillsMetadataFile = await import_fs.promises.readFile(stillsMetadata, "utf-8");
500
+ const stillsMetadataJSON = JSON.parse(stillsMetadataFile);
501
+ if (!Array.isArray(stillsMetadataJSON)) {
502
+ return;
503
+ }
504
+ for (const still of stillsMetadataJSON) {
505
+ const stillFilePath = import_path.default.join(stillsPath, still.name);
506
+ const stillFileData = await import_fs.promises.readFile(stillFilePath, "utf-8");
507
+ const stillFileJSON = JSON.parse(stillFileData);
508
+ if (!stillFileJSON) {
509
+ continue;
510
+ }
511
+ this.stills.set(stillFileJSON.route, stillFileJSON);
512
+ }
513
+ } catch (error) {
514
+ if (this.options.debug !== "none" && !this.options.quiet) {
515
+ const errorText = "Plurid Server Error: Could not read stills.";
516
+ if (this.options.debug === "error") {
517
+ console.error(errorText, error);
518
+ } else {
519
+ console.log(errorText);
520
+ }
521
+ }
522
+ return;
356
523
  }
524
+ }
525
+ };
526
+ var StillsManager_default = StillsManager;
527
+
528
+ // source/utilities/pttp/index.ts
529
+ var resolveElementFromPlaneMatch = (planeMatch, elementqlEndpoint) => {
530
+ if (typeof planeMatch.data.component === "function") {
531
+ return;
532
+ }
533
+ if (typeof planeMatch.data.component === "string") {
357
534
  return {
358
- name: planeMatch.data.component.name,
359
- url: planeMatch.data.component.url || elementqlEndpoint
535
+ name: planeMatch.data.component,
536
+ url: elementqlEndpoint
360
537
  };
538
+ }
539
+ return {
540
+ name: planeMatch.data.component.name,
541
+ url: planeMatch.data.component.url || elementqlEndpoint
542
+ };
361
543
  };
362
544
 
363
- const {IsoMatcher: PluridIsoMatcher} = pluridEngine.routing;
364
-
365
- class PluridServer {
366
- constructor(configuration) {
367
- 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;
368
- this.routes = routes;
369
- this.planes = planes || [];
370
- this.preserves = preserves;
371
- this.helmet = helmet;
372
- this.styles = styles || [];
373
- this.middleware = middleware || [];
374
- this.exterior = exterior;
375
- this.shell = shell;
376
- this.routerProperties = routerProperties || {};
377
- this.services = services || [];
378
- this.options = this.handleOptions(options);
379
- this.template = template;
380
- this.usePTTP = usePTTP !== null && usePTTP !== void 0 ? usePTTP : false;
381
- this.pttpHandler = pttpHandler;
382
- this.elementqlEndpoint = elementqlEndpoint;
383
- this.serverApplication = express__default["default"]();
384
- this.port = DEFAULT_SERVER_PORT;
385
- this.isoMatcher = new PluridIsoMatcher({
386
- routes: this.routes,
387
- routePlanes: this.planes
388
- }, this.options.hostname);
389
- this.configureServer();
390
- this.handleEndpoints();
391
- process.addListener("SIGINT", (() => {
392
- this.stop();
393
- process.exit(0);
394
- }));
545
+ // source/objects/Server/index.ts
546
+ var {
547
+ IsoMatcher: PluridIsoMatcher
548
+ } = import_plurid_engine.routing;
549
+ var PluridServer = class {
550
+ routes;
551
+ planes;
552
+ preserves;
553
+ helmet;
554
+ styles;
555
+ middleware;
556
+ exterior;
557
+ shell;
558
+ routerProperties;
559
+ services;
560
+ options;
561
+ template;
562
+ usePTTP;
563
+ pttpHandler;
564
+ elementqlEndpoint;
565
+ serverApplication;
566
+ server;
567
+ port;
568
+ stills;
569
+ isoMatcher;
570
+ constructor(configuration) {
571
+ const {
572
+ routes,
573
+ planes,
574
+ preserves,
575
+ helmet,
576
+ styles,
577
+ middleware,
578
+ exterior,
579
+ shell,
580
+ routerProperties,
581
+ services,
582
+ options,
583
+ template: template2,
584
+ usePTTP,
585
+ pttpHandler,
586
+ elementqlEndpoint
587
+ } = configuration;
588
+ this.routes = routes;
589
+ this.planes = planes || [];
590
+ this.preserves = preserves;
591
+ this.helmet = helmet;
592
+ this.styles = styles || [];
593
+ this.middleware = middleware || [];
594
+ this.exterior = exterior;
595
+ this.shell = shell;
596
+ this.routerProperties = routerProperties || {};
597
+ this.services = services || [];
598
+ this.options = this.handleOptions(options);
599
+ this.template = template2;
600
+ this.usePTTP = usePTTP ?? false;
601
+ this.pttpHandler = pttpHandler;
602
+ this.elementqlEndpoint = elementqlEndpoint;
603
+ this.serverApplication = (0, import_express.default)();
604
+ this.port = DEFAULT_SERVER_PORT;
605
+ this.stills = new StillsManager_default(this.options);
606
+ this.isoMatcher = new PluridIsoMatcher(
607
+ {
608
+ routes: this.routes,
609
+ routePlanes: this.planes
610
+ },
611
+ this.options.hostname
612
+ );
613
+ this.configureServer();
614
+ this.handleEndpoints();
615
+ if (this.options.attachSignalHandlers) {
616
+ this.attachSignalHandlers();
395
617
  }
396
- static analysis(pluridServer) {
397
- return {
398
- routes: pluridServer.routes,
399
- options: pluridServer.options
400
- };
401
- }
402
- start(port = this.port) {
403
- this.port = port;
404
- const serverlink = `http://localhost:${port}`;
405
- if (this.debugAllows("info")) {
406
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}\n`);
407
- }
408
- this.server = this.serverApplication.listen(port);
409
- this.open(serverlink);
410
- return this.server;
618
+ }
619
+ handleProcessSignal = () => {
620
+ this.stop();
621
+ process.exit(0);
622
+ };
623
+ signalHandlersAttached = false;
624
+ attachSignalHandlers() {
625
+ if (this.signalHandlersAttached) {
626
+ return;
411
627
  }
412
- stop() {
413
- if (this.server) {
414
- if (this.debugAllows("info")) {
415
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}\n`);
416
- }
417
- this.server.close();
418
- } else {
419
- if (this.debugAllows("info")) {
420
- console.info(`\n\t[${pluridFunctions.time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}\n`);
421
- }
422
- }
628
+ process.on("SIGINT", this.handleProcessSignal);
629
+ process.on("SIGTERM", this.handleProcessSignal);
630
+ this.signalHandlersAttached = true;
631
+ }
632
+ detachSignalHandlers() {
633
+ process.removeListener("SIGINT", this.handleProcessSignal);
634
+ process.removeListener("SIGTERM", this.handleProcessSignal);
635
+ this.signalHandlersAttached = false;
636
+ }
637
+ static analysis(pluridServer) {
638
+ return {
639
+ routes: pluridServer.routes,
640
+ options: pluridServer.options
641
+ };
642
+ }
643
+ start(port = this.port) {
644
+ this.port = port;
645
+ const serverlink = `http://localhost:${port}`;
646
+ if (this.debugAllows("info")) {
647
+ console.info(
648
+ `
649
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Started on Port ${port}: ${serverlink}
650
+ `
651
+ );
423
652
  }
424
- handle() {
425
- return {
426
- post: (path, ...handlers) => {
427
- this.serverApplication.post(path, ...handlers);
428
- return this.serverApplication;
429
- },
430
- patch: (path, ...handlers) => {
431
- this.serverApplication.patch(path, ...handlers);
432
- return this.serverApplication;
433
- },
434
- put: (path, ...handlers) => {
435
- this.serverApplication.put(path, ...handlers);
436
- return this.serverApplication;
437
- },
438
- delete: (path, ...handlers) => {
439
- this.serverApplication.delete(path, ...handlers);
440
- return this.serverApplication;
441
- }
442
- };
653
+ this.server = this.serverApplication.listen(port);
654
+ this.open(serverlink);
655
+ return this.server;
656
+ }
657
+ stop() {
658
+ this.detachSignalHandlers();
659
+ if (this.server) {
660
+ if (this.debugAllows("info")) {
661
+ console.info(
662
+ `
663
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Stopped on Port ${this.port}
664
+ `
665
+ );
666
+ }
667
+ this.server.close();
668
+ } else {
669
+ if (this.debugAllows("info")) {
670
+ console.info(
671
+ `
672
+ [${import_plurid_functions.time.stamp()}] ${this.options.serverName} Could not be Stopped on Port ${this.port}
673
+ `
674
+ );
675
+ }
443
676
  }
444
- instance() {
677
+ }
678
+ handle() {
679
+ return {
680
+ post: (path4, ...handlers) => {
681
+ this.serverApplication.post(path4, ...handlers);
445
682
  return this.serverApplication;
446
- }
447
- handleEndpoints() {
448
- this.serverApplication.get(CATCH_ALL_ROUTE, ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
449
- this.handleGetRequest(request, response, next);
450
- }))));
451
- if (this.usePTTP) {
452
- this.serverApplication.post(PTTP_ROUTE, bodyParser.json(), ((request, response, next) => __awaiter(this, void 0, void 0, (function*() {
453
- this.handlePTTPRequest(request, response);
454
- }))));
683
+ },
684
+ patch: (path4, ...handlers) => {
685
+ this.serverApplication.patch(path4, ...handlers);
686
+ return this.serverApplication;
687
+ },
688
+ put: (path4, ...handlers) => {
689
+ this.serverApplication.put(path4, ...handlers);
690
+ return this.serverApplication;
691
+ },
692
+ delete: (path4, ...handlers) => {
693
+ this.serverApplication.delete(path4, ...handlers);
694
+ return this.serverApplication;
695
+ }
696
+ };
697
+ }
698
+ instance() {
699
+ return this.serverApplication;
700
+ }
701
+ handleEndpoints() {
702
+ this.serverApplication.get(
703
+ CATCH_ALL_ROUTE_PATTERN,
704
+ async (request, response, next) => {
705
+ this.handleGetRequest(
706
+ request,
707
+ response,
708
+ next
709
+ );
710
+ }
711
+ );
712
+ if (this.usePTTP) {
713
+ this.serverApplication.post(
714
+ PTTP_ROUTE,
715
+ import_express.default.json(),
716
+ // body parsing is built into Express 5
717
+ async (request, response, next) => {
718
+ this.handlePTTPRequest(
719
+ request,
720
+ response
721
+ );
455
722
  }
723
+ );
456
724
  }
457
- handleGetRequest(request, response, next) {
458
- return __awaiter(this, void 0, void 0, (function*() {
459
- const requestID = request.requestID || pluridFunctions.uuid.generate();
460
- try {
461
- if (this.debugAllows("info")) {
462
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`);
463
- }
464
- const ignorable = this.ignoreGetRequest(request.path);
465
- if (ignorable) {
466
- if (this.debugAllows("info")) {
467
- const requestTime = this.computeRequestTime(request);
468
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`);
469
- }
470
- next();
471
- return;
472
- }
473
- const {preserveResponded: preserveResponded, preserveResult: preserveResult, preserveAfterServe: preserveAfterServe} = yield this.resolvePreserve(request, response);
474
- if (preserveResponded) {
475
- if (this.debugAllows("info")) {
476
- const requestTime = this.computeRequestTime(request);
477
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`);
478
- }
479
- return;
480
- }
481
- const {externalRedirect: externalRedirect, matchingPath: matchingPath} = this.resolveMatchingPath(preserveResult, request.originalUrl);
482
- if (externalRedirect) {
483
- if (this.debugAllows("info")) {
484
- const requestTime = this.computeRequestTime(request);
485
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`);
486
- }
487
- response.status(302).redirect(matchingPath);
488
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
489
- return;
490
- }
491
- const isoMatch = this.isoMatcher.match(matchingPath, "route");
492
- if (!isoMatch) {
493
- const isoMatchNotFound = this.isoMatcher.match(NOT_FOUND_ROUTE, "route");
494
- if (!isoMatchNotFound) {
495
- if (this.debugAllows("info")) {
496
- const requestTime = this.computeRequestTime(request);
497
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
498
- }
499
- response.status(404).send(NOT_FOUND_TEMPLATE);
500
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
501
- return;
502
- }
503
- const renderer = yield this.renderApplication(isoMatchNotFound, preserveResult);
504
- if (this.debugAllows("info")) {
505
- const requestTime = this.computeRequestTime(request);
506
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`);
507
- }
508
- response.status(404).send(renderer.html());
509
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
510
- response.status(404).end();
511
- return;
512
- }
513
- const renderer = yield this.renderApplication(isoMatch, preserveResult);
514
- if (this.debugAllows("info")) {
515
- const requestTime = this.computeRequestTime(request);
516
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`);
517
- }
518
- response.send(renderer.html());
519
- this.resolvePreserveAfterServe(preserveAfterServe, request, response);
520
- return;
521
- } catch (error) {
522
- if (this.debugAllows("error")) {
523
- const requestTime = this.computeRequestTime(request);
524
- console.error(`[${pluridFunctions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`, error);
525
- }
526
- response.status(500).send(SERVER_ERROR_TEMPLATE);
527
- return;
528
- }
529
- }));
725
+ }
726
+ async handleGetRequest(request, response, next) {
727
+ const requestID = request.requestID || import_plurid_functions.uuid.generate();
728
+ try {
729
+ if (this.debugAllows("info")) {
730
+ console.info(
731
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (000 Start) Handling GET ${request.path}`
732
+ );
733
+ }
734
+ const ignorable = this.ignoreGetRequest(
735
+ request.path
736
+ );
737
+ if (ignorable) {
738
+ if (this.debugAllows("info")) {
739
+ const requestTime = this.computeRequestTime(request);
740
+ console.info(
741
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (204 No Content) Ignored GET ${request.path}${requestTime}`
742
+ );
743
+ }
744
+ next();
745
+ return;
746
+ }
747
+ const {
748
+ preserveResponded,
749
+ preserveResult,
750
+ preserveAfterServe
751
+ } = await this.resolvePreserve(
752
+ request,
753
+ response
754
+ );
755
+ if (preserveResponded) {
756
+ if (this.debugAllows("info")) {
757
+ const requestTime = this.computeRequestTime(request);
758
+ console.info(
759
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (204 No Content) Preserve handled GET ${request.path}${requestTime}`
760
+ );
761
+ }
762
+ return;
763
+ }
764
+ const {
765
+ externalRedirect,
766
+ matchingPath
767
+ } = this.resolveMatchingPath(
768
+ preserveResult,
769
+ request.originalUrl
770
+ );
771
+ if (externalRedirect) {
772
+ if (this.debugAllows("info")) {
773
+ const requestTime = this.computeRequestTime(request);
774
+ console.info(
775
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (302 Redirect) Handled GET ${request.path} redirect to ${matchingPath}${requestTime}`
776
+ );
777
+ }
778
+ response.status(302).redirect(matchingPath);
779
+ this.resolvePreserveAfterServe(
780
+ preserveAfterServe,
781
+ request,
782
+ response
783
+ );
784
+ return;
785
+ }
786
+ const still = this.stills.get(matchingPath);
787
+ if (still) {
788
+ if (this.debugAllows("info")) {
789
+ const requestTime = this.computeRequestTime(request);
790
+ console.info(
791
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Still Handled GET ${matchingPath}${requestTime}`
792
+ );
793
+ }
794
+ response.send(still);
795
+ this.resolvePreserveAfterServe(
796
+ preserveAfterServe,
797
+ request,
798
+ response
799
+ );
800
+ return;
801
+ }
802
+ const isoMatch = this.isoMatcher.match(
803
+ matchingPath,
804
+ "route"
805
+ );
806
+ if (!isoMatch) {
807
+ const notFoundStill = this.stills.get(NOT_FOUND_ROUTE);
808
+ if (notFoundStill) {
809
+ if (this.debugAllows("info")) {
810
+ const requestTime = this.computeRequestTime(request);
811
+ console.info(
812
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
813
+ );
814
+ }
815
+ response.status(404).send(notFoundStill);
816
+ this.resolvePreserveAfterServe(
817
+ preserveAfterServe,
818
+ request,
819
+ response
820
+ );
821
+ return;
822
+ }
823
+ const isoMatchNotFound = this.isoMatcher.match(
824
+ NOT_FOUND_ROUTE,
825
+ "route"
826
+ );
827
+ if (!isoMatchNotFound) {
828
+ if (this.debugAllows("info")) {
829
+ const requestTime = this.computeRequestTime(request);
830
+ console.info(
831
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
832
+ );
833
+ }
834
+ response.status(404).send(NOT_FOUND_TEMPLATE);
835
+ this.resolvePreserveAfterServe(
836
+ preserveAfterServe,
837
+ request,
838
+ response
839
+ );
840
+ return;
841
+ }
842
+ const renderer2 = await this.renderApplication(
843
+ isoMatchNotFound,
844
+ preserveResult
845
+ );
846
+ if (this.debugAllows("info")) {
847
+ const requestTime = this.computeRequestTime(request);
848
+ console.info(
849
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Handled GET ${matchingPath}${requestTime}`
850
+ );
851
+ }
852
+ response.status(404).send(await renderer2.html());
853
+ this.resolvePreserveAfterServe(
854
+ preserveAfterServe,
855
+ request,
856
+ response
857
+ );
858
+ response.status(404).end();
859
+ return;
860
+ }
861
+ const renderer = await this.renderApplication(
862
+ isoMatch,
863
+ preserveResult
864
+ );
865
+ if (this.debugAllows("info")) {
866
+ const requestTime = this.computeRequestTime(request);
867
+ console.info(
868
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled GET ${matchingPath}${requestTime}`
869
+ );
870
+ }
871
+ response.send(await renderer.html());
872
+ this.resolvePreserveAfterServe(
873
+ preserveAfterServe,
874
+ request,
875
+ response
876
+ );
877
+ return;
878
+ } catch (error) {
879
+ if (this.debugAllows("error")) {
880
+ const requestTime = this.computeRequestTime(request);
881
+ console.error(
882
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle GET ${request.path}${requestTime}`,
883
+ error
884
+ );
885
+ }
886
+ response.status(500).send(this.template?.errorHtml || SERVER_ERROR_TEMPLATE);
887
+ return;
530
888
  }
531
- handlePTTPRequest(request, response) {
532
- return __awaiter(this, void 0, void 0, (function*() {
533
- const requestID = request.requestID || pluridFunctions.uuid.generate();
534
- try {
535
- if (this.debugAllows("info")) {
536
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`);
537
- }
538
- response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
539
- response.setHeader("Access-Control-Allow-Credentials", "true");
540
- const data = request.body;
541
- if (!data && !data.path) {
542
- if (this.debugAllows("warn")) {
543
- const requestTime = this.computeRequestTime(request);
544
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
545
- }
546
- response.status(400).end();
547
- return;
548
- }
549
- if (this.pttpHandler) {
550
- const pttpHandled = yield this.pttpHandler(data.path);
551
- if (pttpHandled) {
552
- if (this.debugAllows("info")) {
553
- const requestTime = this.computeRequestTime(request);
554
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`);
555
- }
556
- return;
557
- }
558
- }
559
- const planeMatch = this.isoMatcher.match(data.path);
560
- if (!planeMatch) {
561
- if (this.debugAllows("warn")) {
562
- const requestTime = this.computeRequestTime(request);
563
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
564
- }
565
- response.status(400).end();
566
- return;
567
- }
568
- const elementMatch = resolveElementFromPlaneMatch(planeMatch, this.elementqlEndpoint);
569
- if (!elementMatch) {
570
- if (this.debugAllows("warn")) {
571
- const requestTime = this.computeRequestTime(request);
572
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`);
573
- }
574
- response.status(404).end();
575
- return;
576
- }
577
- const elementURL = elementMatch.url;
578
- if (!elementURL) {
579
- if (this.debugAllows("warn")) {
580
- const requestTime = this.computeRequestTime(request);
581
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`);
582
- }
583
- response.status(400).end();
584
- return;
585
- }
586
- if (this.debugAllows("info")) {
587
- const requestTime = this.computeRequestTime(request);
588
- console.info(`[${pluridFunctions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`);
589
- }
590
- const elementName = elementMatch.name;
591
- const linksTo = [];
592
- const element = {
593
- url: elementURL,
594
- name: elementName,
595
- json: {
596
- elements: [ {
597
- name: elementName
598
- } ]
599
- },
600
- linksTo: linksTo
601
- };
602
- response.json({
603
- element: element
604
- });
605
- } catch (error) {
606
- if (this.debugAllows("error")) {
607
- const requestTime = this.computeRequestTime(request);
608
- console.error(`[${pluridFunctions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`, error);
609
- }
610
- response.status(500).send(SERVER_ERROR_TEMPLATE);
611
- return;
889
+ }
890
+ async handlePTTPRequest(request, response) {
891
+ const requestID = request.requestID || import_plurid_functions.uuid.generate();
892
+ try {
893
+ if (this.debugAllows("info")) {
894
+ console.info(
895
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (000 Start) Handling POST ${request.path}`
896
+ );
897
+ }
898
+ response.setHeader("Access-Control-Allow-Origin", request.headers.origin || "");
899
+ response.setHeader("Access-Control-Allow-Credentials", "true");
900
+ const data = request.body;
901
+ if (!data || !data.path) {
902
+ if (this.debugAllows("warn")) {
903
+ const requestTime = this.computeRequestTime(request);
904
+ console.info(
905
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
906
+ );
907
+ }
908
+ response.status(400).end();
909
+ return;
910
+ }
911
+ if (this.pttpHandler) {
912
+ const pttpHandled = await this.pttpHandler(
913
+ data.path
914
+ );
915
+ if (pttpHandled) {
916
+ if (this.debugAllows("info")) {
917
+ const requestTime = this.computeRequestTime(request);
918
+ console.info(
919
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime} in custom handler`
920
+ );
921
+ }
922
+ return;
923
+ }
924
+ }
925
+ const planeMatch = this.isoMatcher.match(
926
+ data.path
927
+ );
928
+ if (!planeMatch) {
929
+ if (this.debugAllows("warn")) {
930
+ const requestTime = this.computeRequestTime(request);
931
+ console.info(
932
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
933
+ );
934
+ }
935
+ response.status(400).end();
936
+ return;
937
+ }
938
+ const elementMatch = resolveElementFromPlaneMatch(
939
+ planeMatch,
940
+ this.elementqlEndpoint
941
+ );
942
+ if (!elementMatch) {
943
+ if (this.debugAllows("warn")) {
944
+ const requestTime = this.computeRequestTime(request);
945
+ console.info(
946
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (404 Not Found) Could not handle POST ${request.path}${requestTime}`
947
+ );
948
+ }
949
+ response.status(404).end();
950
+ return;
951
+ }
952
+ const elementURL = elementMatch.url;
953
+ if (!elementURL) {
954
+ if (this.debugAllows("warn")) {
955
+ const requestTime = this.computeRequestTime(request);
956
+ console.info(
957
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (400 Bad Request) Could not handle POST ${request.path}${requestTime}`
958
+ );
959
+ }
960
+ response.status(400).end();
961
+ return;
962
+ }
963
+ if (this.debugAllows("info")) {
964
+ const requestTime = this.computeRequestTime(request);
965
+ console.info(
966
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (200 OK) Handled POST ${request.path}${requestTime}`
967
+ );
968
+ }
969
+ const elementName = elementMatch.name;
970
+ const linksTo = [];
971
+ const element = {
972
+ url: elementURL,
973
+ name: elementName,
974
+ json: {
975
+ elements: [
976
+ {
977
+ name: elementName
612
978
  }
613
- }));
979
+ ]
980
+ },
981
+ linksTo
982
+ };
983
+ response.json({
984
+ element
985
+ });
986
+ } catch (error) {
987
+ if (this.debugAllows("error")) {
988
+ const requestTime = this.computeRequestTime(request);
989
+ console.error(
990
+ `[${import_plurid_functions.time.stamp()} :: ${requestID}] (500 Server Error) Could not handle POST ${request.path}${requestTime}`,
991
+ error
992
+ );
993
+ }
994
+ response.status(500).send(this.template?.errorHtml || SERVER_ERROR_TEMPLATE);
995
+ return;
614
996
  }
615
- ignoreGetRequest(path) {
616
- for (const ignore of this.options.ignore) {
617
- const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
618
- if (path === normalizedIgnore) {
619
- return true;
620
- }
621
- if (normalizedIgnore.endsWith("/*")) {
622
- const curatedIgnore = normalizedIgnore.replace("/*", "");
623
- if (path.startsWith(curatedIgnore)) {
624
- return true;
625
- }
626
- }
997
+ }
998
+ ignoreGetRequest(path4) {
999
+ for (const ignore of this.options.ignore) {
1000
+ const normalizedIgnore = ignore.endsWith("/") && ignore.length > 1 ? ignore.slice(0, ignore.length - 1) : ignore;
1001
+ if (path4 === normalizedIgnore) {
1002
+ return true;
1003
+ }
1004
+ if (normalizedIgnore.endsWith("/*")) {
1005
+ const curatedIgnore = normalizedIgnore.replace("/*", "");
1006
+ if (path4.startsWith(curatedIgnore)) {
1007
+ return true;
627
1008
  }
628
- return false;
1009
+ }
629
1010
  }
630
- resolveMatchingPath(preserveResult, path) {
631
- const redirect = preserveResult ? preserveResult.redirect : "";
632
- const externalRedirect = !!(redirect === null || redirect === void 0 ? void 0 : redirect.startsWith("http"));
633
- const matchingPath = redirect || path;
634
- return {
635
- externalRedirect: externalRedirect,
636
- matchingPath: matchingPath
637
- };
1011
+ return false;
1012
+ }
1013
+ resolveMatchingPath(preserveResult, path4) {
1014
+ const redirect = preserveResult ? preserveResult.redirect : "";
1015
+ const externalRedirect = !!redirect?.startsWith("http");
1016
+ const matchingPath = redirect || path4;
1017
+ return {
1018
+ externalRedirect,
1019
+ matchingPath
1020
+ };
1021
+ }
1022
+ async resolvePreserve(request, response) {
1023
+ const catchAll = this.preserves.find(
1024
+ (preserve) => preserve.serve === CATCH_ALL_ROUTE
1025
+ );
1026
+ const notFound = this.preserves.find(
1027
+ (preserve) => preserve.serve === NOT_FOUND_ROUTE
1028
+ );
1029
+ const isoMatch = this.isoMatcher.match(
1030
+ request.originalUrl,
1031
+ "route"
1032
+ );
1033
+ let preserveOnServe;
1034
+ let preserveAfterServe;
1035
+ let preserveOnError;
1036
+ if (isoMatch || catchAll || notFound) {
1037
+ const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find(
1038
+ (preserve2) => preserve2.serve === isoMatch?.data.value
1039
+ );
1040
+ if (preserve) {
1041
+ preserveOnServe = preserve.onServe;
1042
+ preserveAfterServe = preserve.afterServe;
1043
+ preserveOnError = preserve.onError;
1044
+ }
638
1045
  }
639
- resolvePreserve(request, response) {
640
- return __awaiter(this, void 0, void 0, (function*() {
641
- const catchAll = this.preserves.find((preserve => preserve.serve === CATCH_ALL_ROUTE));
642
- const notFound = this.preserves.find((preserve => preserve.serve === NOT_FOUND_ROUTE));
643
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
644
- let preserveOnServe;
645
- let preserveAfterServe;
646
- let preserveOnError;
647
- if (isoMatch || catchAll || notFound) {
648
- const preserve = catchAll ? catchAll : notFound && !isoMatch ? notFound : this.preserves.find((preserve => preserve.serve === (isoMatch === null || isoMatch === void 0 ? void 0 : isoMatch.data.value)));
649
- if (preserve) {
650
- preserveOnServe = preserve.onServe;
651
- preserveAfterServe = preserve.afterServe;
652
- preserveOnError = preserve.onError;
653
- }
654
- }
655
- let preserveResult;
656
- if (preserveOnServe) {
657
- const transmission = {
658
- context: {
659
- route: request.originalUrl,
660
- match: isoMatch
661
- },
662
- request: request,
663
- response: response
664
- };
665
- try {
666
- preserveResult = yield preserveOnServe(transmission);
667
- if (preserveResult) {
668
- if (preserveResult.responded) {
669
- return {
670
- preserveResponded: true,
671
- preserveResult: preserveResult,
672
- preserveAfterServe: preserveAfterServe
673
- };
674
- }
675
- }
676
- } catch (error) {
677
- if (preserveOnError) {
678
- const onErrorResponse = yield preserveOnError(error, transmission);
679
- if (onErrorResponse) {
680
- if (onErrorResponse.responded) {
681
- return {
682
- preserveResponded: true,
683
- preserveResult: preserveResult,
684
- preserveAfterServe: preserveAfterServe
685
- };
686
- }
687
- if (!onErrorResponse.depreserve) {
688
- return {
689
- preserveResponded: false,
690
- preserveResult: preserveResult,
691
- preserveAfterServe: preserveAfterServe
692
- };
693
- }
694
- }
695
- }
696
- }
697
- }
1046
+ let preserveResult;
1047
+ if (preserveOnServe) {
1048
+ const transmission = {
1049
+ context: {
1050
+ route: request.originalUrl,
1051
+ match: isoMatch
1052
+ },
1053
+ request,
1054
+ response
1055
+ };
1056
+ try {
1057
+ preserveResult = await preserveOnServe(transmission);
1058
+ if (preserveResult) {
1059
+ if (preserveResult.responded) {
698
1060
  return {
699
- preserveResponded: false,
700
- preserveResult: preserveResult,
701
- preserveAfterServe: preserveAfterServe
1061
+ preserveResponded: true,
1062
+ preserveResult,
1063
+ preserveAfterServe
702
1064
  };
703
- }));
704
- }
705
- resolvePreserveAfterServe(preserveAfterServe, request, response) {
706
- return __awaiter(this, void 0, void 0, (function*() {
707
- if (preserveAfterServe) {
708
- const isoMatch = this.isoMatcher.match(request.originalUrl, "route");
709
- const transmission = {
710
- context: {
711
- route: request.originalUrl,
712
- match: isoMatch
713
- },
714
- request: request,
715
- response: response
716
- };
717
- yield preserveAfterServe(transmission);
1065
+ }
1066
+ }
1067
+ } catch (error) {
1068
+ if (preserveOnError) {
1069
+ const onErrorResponse = await preserveOnError(
1070
+ error,
1071
+ transmission
1072
+ );
1073
+ if (onErrorResponse) {
1074
+ if (onErrorResponse.responded) {
1075
+ return {
1076
+ preserveResponded: true,
1077
+ preserveResult,
1078
+ preserveAfterServe
1079
+ };
718
1080
  }
719
- }));
720
- }
721
- handleGateway(path, request, preserveResult) {
722
- return __awaiter(this, void 0, void 0, (function*() {
723
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
724
- if (path !== gatewayEndpoint) {
725
- return;
1081
+ if (!onErrorResponse.depreserve) {
1082
+ return {
1083
+ preserveResponded: false,
1084
+ preserveResult,
1085
+ preserveAfterServe
1086
+ };
726
1087
  }
727
- ({
728
- path: {
729
- value: gatewayEndpoint
730
- },
731
- pathname: gatewayEndpoint,
732
- parameters: {},
733
- query: {
734
- __gatewayQuery: request.originalUrl
735
- },
736
- fragments: {
737
- texts: [],
738
- elements: []
739
- },
740
- route: gatewayEndpoint
741
- });
742
- return "";
743
- }));
1088
+ }
1089
+ }
1090
+ }
744
1091
  }
745
- renderApplication(isoMatch, preserveResult, matchedPlane) {
746
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
747
- return __awaiter(this, void 0, void 0, (function*() {
748
- const globals = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.globals;
749
- 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);
750
- const pluridMetastate = yield pluridReact.serverComputeMetastate(isoMatch, this.routes, globals, this.options.hostname);
751
- const {content: content, styles: styles} = yield this.getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane);
752
- const stringedStyles = this.styles.reduce(((accumulator, style) => accumulator + style), "");
753
- 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(" ")) || "";
754
- const mergedStyles = styles + stringedStyles + preserveStyles;
755
- const {helmet: helmet} = this.helmet;
756
- 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 ` : "";
757
- 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());
758
- const mergedHtmlAttributes = recordToString(htmlAttributes) + (((_f = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _f === void 0 ? void 0 : _f.htmlAttributes) || "");
759
- const bodyAttributes = (helmet === null || helmet === void 0 ? void 0 : helmet.bodyAttributes.toString()) || "";
760
- const preserveBodyAttributes = ((_g = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _g === void 0 ? void 0 : _g.bodyAttributes) || "";
761
- const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
762
- const headScripts = ((_h = this.template) === null || _h === void 0 ? void 0 : _h.headScripts) || [];
763
- const mergedHeadScripts = [ ...headScripts, ...((_j = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _j === void 0 ? void 0 : _j.headScripts) || [] ];
764
- const bodyScripts = ((_k = this.template) === null || _k === void 0 ? void 0 : _k.bodyScripts) || [];
765
- const mergedBodyScripts = [ ...bodyScripts, ...((_l = preserveResult === null || preserveResult === void 0 ? void 0 : preserveResult.template) === null || _l === void 0 ? void 0 : _l.bodyScripts) || [] ];
766
- const renderer = new PluridRenderer({
767
- htmlLanguage: mergedHtmlLanguage,
768
- head: head,
769
- htmlAttributes: mergedHtmlAttributes,
770
- bodyAttributes: mergedBodyAttributes,
771
- defaultStyle: (_m = this.template) === null || _m === void 0 ? void 0 : _m.defaultStyle,
772
- styles: mergedStyles,
773
- headScripts: mergedHeadScripts,
774
- bodyScripts: mergedBodyScripts,
775
- vendorScriptSource: (_o = this.template) === null || _o === void 0 ? void 0 : _o.vendorScriptSource,
776
- mainScriptSource: (_p = this.template) === null || _p === void 0 ? void 0 : _p.mainScriptSource,
777
- root: (_q = this.template) === null || _q === void 0 ? void 0 : _q.root,
778
- content: content,
779
- defaultPreloadedPluridMetastate: (_r = this.template) === null || _r === void 0 ? void 0 : _r.defaultPreloadedPluridMetastate,
780
- pluridMetastate: JSON.stringify(pluridMetastate),
781
- globals: globals,
782
- minify: (_s = this.template) === null || _s === void 0 ? void 0 : _s.minify
783
- });
784
- return renderer;
785
- }));
1092
+ return {
1093
+ preserveResponded: false,
1094
+ preserveResult,
1095
+ preserveAfterServe
1096
+ };
1097
+ }
1098
+ async resolvePreserveAfterServe(preserveAfterServe, request, response) {
1099
+ if (preserveAfterServe) {
1100
+ const isoMatch = this.isoMatcher.match(
1101
+ request.originalUrl,
1102
+ "route"
1103
+ );
1104
+ const transmission = {
1105
+ context: {
1106
+ route: request.originalUrl,
1107
+ match: isoMatch
1108
+ },
1109
+ request,
1110
+ response
1111
+ };
1112
+ await preserveAfterServe(transmission);
786
1113
  }
787
- getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
788
- return __awaiter(this, void 0, void 0, (function*() {
789
- const stylesheet = new styledComponents.ServerStyleSheet;
790
- let content = "";
791
- let styles = "";
792
- try {
793
- const gateway = false;
794
- const gatewayQuery = "";
795
- const {gatewayEndpoint: gatewayEndpoint} = this.options;
796
- const contentHandler = new PluridContentGenerator({
797
- services: this.services,
798
- stylesheet: stylesheet,
799
- exterior: this.exterior,
800
- shell: this.shell,
801
- routerProperties: this.routerProperties,
802
- helmet: this.helmet,
803
- routes: this.routes,
804
- planes: this.planes,
805
- pluridMetastate: pluridMetastate,
806
- gateway: gateway,
807
- gatewayEndpoint: gatewayEndpoint,
808
- gatewayQuery: gatewayQuery,
809
- preserveResult: preserveResult,
810
- pathname: isoMatch.match.value,
811
- hostname: this.options.hostname,
812
- matchedPlane: isoMatch.kind === "RoutePlane" ? {
813
- value: isoMatch.match.value
814
- } : undefined
815
- });
816
- content = yield contentHandler.render();
817
- styles = stylesheet.getStyleTags();
818
- } catch (error) {
819
- if (this.options.debug !== "none" && !this.options.quiet) {
820
- const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
821
- if (this.debugAllows("error")) {
822
- console.error(errorText, error);
823
- }
824
- }
825
- return {
826
- content: "",
827
- styles: ""
828
- };
829
- } finally {
830
- stylesheet.seal();
831
- }
832
- return {
833
- content: content,
834
- styles: styles
835
- };
836
- }));
1114
+ }
1115
+ async handleGateway(path4, request, preserveResult) {
1116
+ const {
1117
+ gatewayEndpoint
1118
+ } = this.options;
1119
+ if (path4 !== gatewayEndpoint) {
1120
+ return;
837
1121
  }
838
- computeRequestTime(request) {
839
- const requestTime = request.requestTime;
840
- if (!requestTime) {
841
- return "";
842
- }
843
- const now = Date.now();
844
- const difference = now - requestTime;
845
- return ` in ${difference} ms`;
1122
+ const gatewayRoute = {
1123
+ path: {
1124
+ value: gatewayEndpoint
1125
+ },
1126
+ pathname: gatewayEndpoint,
1127
+ parameters: {},
1128
+ query: {
1129
+ __gatewayQuery: request.originalUrl
1130
+ },
1131
+ fragments: {
1132
+ texts: [],
1133
+ elements: []
1134
+ },
1135
+ route: gatewayEndpoint
1136
+ };
1137
+ return "";
1138
+ }
1139
+ async renderApplication(isoMatch, preserveResult, matchedPlane) {
1140
+ const globals = preserveResult?.globals;
1141
+ const mergedHtmlLanguage = preserveResult?.template?.htmlLanguage || this.template?.htmlLanguage;
1142
+ const pluridMetastate = await (0, import_plurid_react2.serverComputeMetastate)(
1143
+ isoMatch,
1144
+ this.routes,
1145
+ globals,
1146
+ this.options.hostname
1147
+ );
1148
+ const {
1149
+ content,
1150
+ styles
1151
+ } = await this.getContentAndStyles(
1152
+ isoMatch,
1153
+ pluridMetastate,
1154
+ preserveResult,
1155
+ matchedPlane
1156
+ );
1157
+ const stringedStyles = this.styles.reduce(
1158
+ (accumulator, style) => accumulator + style,
1159
+ ""
1160
+ );
1161
+ const preserveStyles = preserveResult?.template?.styles?.join(" ") || "";
1162
+ const mergedStyles = styles + stringedStyles + preserveStyles;
1163
+ const {
1164
+ helmet
1165
+ } = this.helmet;
1166
+ const helmetHead = helmet ? `
1167
+ ${helmet.meta.toString()}
1168
+ ${helmet.title.toString()}
1169
+ ${helmet.base.toString()}
1170
+ ${helmet.link.toString()}
1171
+ ${helmet.style.toString()}
1172
+ ${helmet.noscript.toString()}
1173
+ ${helmet.script.toString()}
1174
+ ` : "";
1175
+ const head = helmetHead + this.buildStaticHead();
1176
+ const htmlAttributes = {
1177
+ ...this.template?.htmlAttributes,
1178
+ ...helmet?.htmlAttributes.toComponent()
1179
+ };
1180
+ const mergedHtmlAttributes = recordToString(htmlAttributes) + (preserveResult?.template?.htmlAttributes || "");
1181
+ const bodyAttributes = helmet?.bodyAttributes.toString() || "";
1182
+ const preserveBodyAttributes = preserveResult?.template?.bodyAttributes || "";
1183
+ const mergedBodyAttributes = bodyAttributes + preserveBodyAttributes;
1184
+ const headScripts = this.template?.headScripts || [];
1185
+ const mergedHeadScripts = [
1186
+ ...headScripts,
1187
+ ...preserveResult?.template?.headScripts || []
1188
+ ];
1189
+ const bodyScripts = this.template?.bodyScripts || [];
1190
+ const mergedBodyScripts = [
1191
+ ...bodyScripts,
1192
+ ...preserveResult?.template?.bodyScripts || []
1193
+ ];
1194
+ const renderer = new Renderer_default({
1195
+ htmlLanguage: mergedHtmlLanguage,
1196
+ head,
1197
+ htmlAttributes: mergedHtmlAttributes,
1198
+ bodyAttributes: mergedBodyAttributes,
1199
+ defaultStyle: this.template?.defaultStyle,
1200
+ styles: mergedStyles,
1201
+ headScripts: mergedHeadScripts,
1202
+ bodyScripts: mergedBodyScripts,
1203
+ vendorScriptSource: this.template?.vendorScriptSource,
1204
+ mainScriptSource: this.template?.mainScriptSource,
1205
+ root: this.template?.root,
1206
+ content,
1207
+ defaultPreloadedPluridMetastate: this.template?.defaultPreloadedPluridMetastate,
1208
+ pluridMetastate: JSON.stringify(pluridMetastate),
1209
+ globals,
1210
+ minify: this.template?.minify
1211
+ });
1212
+ return renderer;
1213
+ }
1214
+ /**
1215
+ * Build the static `<head>` markup from the template config (favicon set,
1216
+ * manifest, default title / meta / links). Returns an empty string when none
1217
+ * are configured, so the head is byte-identical to before for existing apps.
1218
+ */
1219
+ buildStaticHead() {
1220
+ const template2 = this.template;
1221
+ if (!template2) {
1222
+ return "";
846
1223
  }
847
- handleOptions(partialOptions) {
848
- var _a, _b;
849
- const options = {
850
- serverName: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.serverName) || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
851
- hostname: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.hostname) || DEFAULT_SERVER_OPTIONS.HOSTNAME,
852
- quiet: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.quiet) || DEFAULT_SERVER_OPTIONS.QUIET,
853
- debug: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug) ? partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.debug : environment.production ? "error" : "info",
854
- compression: (_a = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.compression) !== null && _a !== void 0 ? _a : DEFAULT_SERVER_OPTIONS.COMPRESSION,
855
- open: (_b = partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.open) !== null && _b !== void 0 ? _b : DEFAULT_SERVER_OPTIONS.OPEN,
856
- buildDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.buildDirectory) || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
857
- assetsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.assetsDirectory) || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
858
- gatewayEndpoint: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.gatewayEndpoint) || DEFAULT_SERVER_OPTIONS.GATEWAY,
859
- staticCache: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.staticCache) || 0,
860
- ignore: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.ignore) || [],
861
- stillsDirectory: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stillsDirectory) || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
862
- stiller: (partialOptions === null || partialOptions === void 0 ? void 0 : partialOptions.stiller) || defaultStillerOptions
863
- };
864
- return options;
1224
+ const escapeAttribute2 = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
1225
+ const escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1226
+ const parts = [];
1227
+ const favicon = template2.favicon;
1228
+ if (typeof favicon === "string") {
1229
+ parts.push(`<link rel="icon" href="${escapeAttribute2(favicon)}">`);
1230
+ } else if (favicon) {
1231
+ if (favicon.icon) {
1232
+ parts.push(`<link rel="icon" href="${escapeAttribute2(favicon.icon)}">`);
1233
+ }
1234
+ if (favicon.apple) {
1235
+ parts.push(`<link rel="apple-touch-icon" href="${escapeAttribute2(favicon.apple)}">`);
1236
+ }
1237
+ for (const [size, href] of Object.entries(favicon.sizes || {})) {
1238
+ parts.push(`<link rel="icon" sizes="${escapeAttribute2(size)}" href="${escapeAttribute2(href)}">`);
1239
+ }
1240
+ if (favicon.maskIcon) {
1241
+ const color = favicon.themeColor ? ` color="${escapeAttribute2(favicon.themeColor)}"` : "";
1242
+ parts.push(`<link rel="mask-icon" href="${escapeAttribute2(favicon.maskIcon)}"${color}>`);
1243
+ }
1244
+ if (favicon.themeColor) {
1245
+ parts.push(`<meta name="theme-color" content="${escapeAttribute2(favicon.themeColor)}">`);
1246
+ }
865
1247
  }
866
- configureServer() {
867
- const clientPath = path__default["default"].join(this.options.buildDirectory, "./client");
868
- this.serverApplication.disable("x-powered-by");
869
- this.serverApplication.use(((request, _, next) => {
870
- const requestID = pluridFunctions.uuid.generate();
871
- request.requestID = requestID;
872
- const requestTime = Date.now();
873
- request.requestTime = requestTime;
874
- next();
875
- }));
876
- if (this.options.compression) {
877
- this.serverApplication.use(compression__default["default"]());
878
- this.serverApplication.get("/vendor.js", ((request, response, next) => {
879
- response.setHeader("Content-Type", "application/javascript");
880
- const vendorBrotliExists = fs__default["default"].existsSync(path__default["default"].join(clientPath, "vendor.js.br"));
881
- const acceptEncoding = request.header("Accept-Encoding");
882
- if ((acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("br")) && vendorBrotliExists) {
883
- request.url += ".br";
884
- response.set("Content-Encoding", "br");
885
- next();
886
- return;
887
- }
888
- next();
889
- }));
1248
+ if (template2.manifest) {
1249
+ parts.push(`<link rel="manifest" href="${escapeAttribute2(template2.manifest)}">`);
1250
+ }
1251
+ const head = template2.head;
1252
+ if (head) {
1253
+ if (head.title) {
1254
+ parts.push(`<title>${escapeText(head.title)}</title>`);
1255
+ }
1256
+ if (head.description) {
1257
+ parts.push(`<meta name="description" content="${escapeAttribute2(head.description)}">`);
1258
+ }
1259
+ for (const meta of head.meta || []) {
1260
+ const selector = meta.name ? `name="${escapeAttribute2(meta.name)}"` : meta.property ? `property="${escapeAttribute2(meta.property)}"` : "";
1261
+ if (!selector) {
1262
+ continue;
890
1263
  }
891
- this.serverApplication.use(express__default["default"].static(clientPath, {
892
- maxAge: this.options.staticCache
893
- }));
894
- this.loadMiddleware();
1264
+ parts.push(`<meta ${selector} content="${escapeAttribute2(meta.content)}">`);
1265
+ }
1266
+ for (const link of head.links || []) {
1267
+ parts.push(`<link rel="${escapeAttribute2(link.rel)}" href="${escapeAttribute2(link.href)}">`);
1268
+ }
1269
+ }
1270
+ if (parts.length === 0) {
1271
+ return "";
895
1272
  }
896
- loadMiddleware() {
897
- for (const middleware of this.middleware) {
898
- this.serverApplication.use(((req, res, next) => middleware(req, res, next)));
1273
+ return "\n " + parts.join("\n ");
1274
+ }
1275
+ async getContentAndStyles(isoMatch, pluridMetastate, preserveResult, matchedPlane) {
1276
+ const stylesheet = new import_styled_components2.ServerStyleSheet();
1277
+ let content = "";
1278
+ let styles = "";
1279
+ try {
1280
+ const gateway = false;
1281
+ const gatewayQuery = "";
1282
+ const {
1283
+ gatewayEndpoint
1284
+ } = this.options;
1285
+ const contentHandler = new ContentGenerator_default({
1286
+ services: this.services,
1287
+ stylesheet,
1288
+ exterior: this.exterior,
1289
+ shell: this.shell,
1290
+ routerProperties: this.routerProperties,
1291
+ helmet: this.helmet,
1292
+ routes: this.routes,
1293
+ planes: this.planes,
1294
+ pluridMetastate,
1295
+ gateway,
1296
+ gatewayEndpoint,
1297
+ gatewayQuery,
1298
+ preserveResult,
1299
+ pathname: isoMatch.match.value,
1300
+ hostname: this.options.hostname,
1301
+ matchedPlane: isoMatch.kind === "RoutePlane" ? {
1302
+ value: isoMatch.match.value
1303
+ } : void 0
1304
+ });
1305
+ content = await contentHandler.render();
1306
+ styles = stylesheet.getStyleTags();
1307
+ } catch (error) {
1308
+ if (this.options.debug !== "none" && !this.options.quiet) {
1309
+ const errorText = `${this.options.serverName} Error: Something went wrong in getContentAndStyles().`;
1310
+ if (this.debugAllows("error")) {
1311
+ console.error(
1312
+ errorText,
1313
+ error
1314
+ );
899
1315
  }
1316
+ }
1317
+ return {
1318
+ content: "",
1319
+ styles: ""
1320
+ };
1321
+ } finally {
1322
+ stylesheet.seal();
900
1323
  }
901
- open(serverlink) {
902
- try {
903
- const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
904
- if (processDoNotOpen) {
905
- return;
906
- }
907
- if (this.options.open) {
908
- open__default["default"](serverlink);
909
- }
910
- } catch (error) {
1324
+ return {
1325
+ content,
1326
+ styles
1327
+ };
1328
+ }
1329
+ computeRequestTime(request) {
1330
+ const requestTime = request.requestTime;
1331
+ if (!requestTime) {
1332
+ return "";
1333
+ }
1334
+ const now = Date.now();
1335
+ const difference = now - requestTime;
1336
+ return ` in ${difference} ms`;
1337
+ }
1338
+ handleOptions(partialOptions) {
1339
+ const options = {
1340
+ serverName: partialOptions?.serverName || DEFAULT_SERVER_OPTIONS.SERVER_NAME,
1341
+ hostname: partialOptions?.hostname || DEFAULT_SERVER_OPTIONS.HOSTNAME,
1342
+ quiet: partialOptions?.quiet || DEFAULT_SERVER_OPTIONS.QUIET,
1343
+ debug: partialOptions?.debug ? partialOptions?.debug : environment.production ? "error" : "info",
1344
+ compression: partialOptions?.compression ?? DEFAULT_SERVER_OPTIONS.COMPRESSION,
1345
+ open: partialOptions?.open ?? DEFAULT_SERVER_OPTIONS.OPEN,
1346
+ buildDirectory: partialOptions?.buildDirectory || DEFAULT_SERVER_OPTIONS.BUILD_DIRECTORY,
1347
+ assetsDirectory: partialOptions?.assetsDirectory || DEFAULT_SERVER_OPTIONS.ASSETS_DIRECTORY,
1348
+ publicDirectory: partialOptions?.publicDirectory || "",
1349
+ gatewayEndpoint: partialOptions?.gatewayEndpoint || DEFAULT_SERVER_OPTIONS.GATEWAY,
1350
+ staticCache: partialOptions?.staticCache || 0,
1351
+ ignore: partialOptions?.ignore || [],
1352
+ stillsDirectory: partialOptions?.stillsDirectory || DEFAULT_SERVER_OPTIONS.STILLS_DIRECTORY,
1353
+ stiller: partialOptions?.stiller || defaultStillerOptions,
1354
+ attachSignalHandlers: partialOptions?.attachSignalHandlers ?? true
1355
+ };
1356
+ return options;
1357
+ }
1358
+ configureServer() {
1359
+ const clientPath = import_path2.default.join(this.options.buildDirectory, "./client");
1360
+ this.serverApplication.disable("x-powered-by");
1361
+ this.serverApplication.use(
1362
+ (request, _, next) => {
1363
+ const requestID = import_plurid_functions.uuid.generate();
1364
+ request.requestID = requestID;
1365
+ const requestTime = Date.now();
1366
+ request.requestTime = requestTime;
1367
+ next();
1368
+ }
1369
+ );
1370
+ if (this.options.compression) {
1371
+ this.serverApplication.use(
1372
+ (0, import_compression.default)()
1373
+ // @types/compression targets Express 4's handler type
1374
+ );
1375
+ this.serverApplication.get(
1376
+ "/vendor.js",
1377
+ (request, response, next) => {
1378
+ response.setHeader(
1379
+ "Content-Type",
1380
+ "application/javascript"
1381
+ );
1382
+ const vendorBrotliExists = import_fs2.default.existsSync(
1383
+ import_path2.default.join(clientPath, "vendor.js.br")
1384
+ );
1385
+ const acceptEncoding = request.header("Accept-Encoding");
1386
+ if (acceptEncoding?.includes("br") && vendorBrotliExists) {
1387
+ request.url += ".br";
1388
+ response.set("Content-Encoding", "br");
1389
+ next();
911
1390
  return;
1391
+ }
1392
+ next();
912
1393
  }
1394
+ );
913
1395
  }
914
- debugAllows(level) {
915
- if (this.options.quiet) {
916
- return false;
917
- }
918
- if (this.options.debug === "none") {
919
- return false;
920
- }
921
- switch (level) {
922
- case "error":
923
- return true;
924
-
925
- case "warn":
926
- if (this.options.debug === "error") {
927
- return false;
928
- }
929
- return true;
930
-
931
- case "info":
932
- if (this.options.debug === "error" || this.options.debug === "warn") {
933
- return false;
934
- }
935
- return true;
936
-
937
- default:
938
- return false;
939
- }
1396
+ this.serverApplication.use(
1397
+ import_express.default.static(clientPath, {
1398
+ maxAge: this.options.staticCache
1399
+ })
1400
+ );
1401
+ const publicPath = this.options.publicDirectory || import_path2.default.join(this.options.buildDirectory, "public");
1402
+ if (import_fs2.default.existsSync(publicPath)) {
1403
+ this.serverApplication.use(
1404
+ import_express.default.static(publicPath, {
1405
+ index: false,
1406
+ maxAge: this.options.staticCache
1407
+ })
1408
+ );
940
1409
  }
941
- }
942
-
943
- class LiveServer {
944
- constructor(options) {
945
- this.sockets = [];
946
- this.resolveOptions = options => {
947
- const defaultServerPath = "./source/server/index.ts";
948
- const resolvedOptions = {
949
- server: (options === null || options === void 0 ? void 0 : options.server) || defaultServerPath
950
- };
951
- return resolvedOptions;
952
- };
953
- this.options = this.resolveOptions(options);
954
- this.expressServer = express__default["default"]();
955
- this.setupExpressServer();
956
- this.httpServer = http__default["default"].createServer(this.expressServer);
957
- this.setupHttpServer();
1410
+ this.loadMiddleware();
1411
+ }
1412
+ loadMiddleware() {
1413
+ for (const middleware of this.middleware) {
1414
+ this.serverApplication.use(
1415
+ (req, res, next) => middleware(req, res, next)
1416
+ );
958
1417
  }
959
- setupExpressServer() {}
960
- setupHttpServer() {
961
- this.httpServer.on("connection", (socket => {
962
- this.sockets.push(socket);
963
- socket.once("close", (() => {
964
- this.sockets.splice(this.sockets.indexOf(socket), 1);
965
- }));
966
- }));
967
- this.httpServer.on("error", (error => {
968
- throw error;
969
- }));
1418
+ }
1419
+ open(serverlink) {
1420
+ try {
1421
+ const processDoNotOpen = process.env.PLURID_OPEN === "false" ? true : false;
1422
+ if (processDoNotOpen) {
1423
+ return;
1424
+ }
1425
+ if (this.options.open) {
1426
+ (0, import_open.default)(serverlink);
1427
+ }
1428
+ } catch (error) {
1429
+ return;
970
1430
  }
971
- start() {}
972
- }
973
-
974
- const replacePluridResolution = html => {
975
- const normalResolution = "width: 1366px; height: 768px;";
976
- const zeroResolution = "width: 0px; height: 0px;";
977
- return html.replace(normalResolution, zeroResolution);
1431
+ }
1432
+ debugAllows(level) {
1433
+ if (this.options.quiet) {
1434
+ return false;
1435
+ }
1436
+ if (this.options.debug === "none") {
1437
+ return false;
1438
+ }
1439
+ switch (level) {
1440
+ case "error":
1441
+ return true;
1442
+ case "warn":
1443
+ if (this.options.debug === "error") {
1444
+ return false;
1445
+ }
1446
+ return true;
1447
+ case "info":
1448
+ if (this.options.debug === "error" || this.options.debug === "warn") {
1449
+ return false;
1450
+ }
1451
+ return true;
1452
+ default:
1453
+ return false;
1454
+ }
1455
+ }
978
1456
  };
979
-
980
- const isCurrentUserRoot = () => process.getuid() == 0;
981
-
982
- const render = (puppeteer, host, route, configuration) => __awaiter(void 0, void 0, void 0, (function*() {
983
- const start = Date.now();
984
- const browser = yield puppeteer.launch({
985
- defaultViewport: {
986
- width: 1366,
987
- height: 768
988
- },
989
- headless: true,
990
- args: isCurrentUserRoot() ? [ "--no-sandbox" ] : undefined
1457
+ var Server_default = PluridServer;
1458
+
1459
+ // source/objects/LiveServer/index.ts
1460
+ var import_http = __toESM(require("http"));
1461
+ var import_express2 = __toESM(require("express"));
1462
+ var LiveServer = class {
1463
+ options;
1464
+ expressServer;
1465
+ httpServer;
1466
+ sockets = [];
1467
+ constructor(options) {
1468
+ this.options = this.resolveOptions(options);
1469
+ this.expressServer = (0, import_express2.default)();
1470
+ this.setupExpressServer();
1471
+ this.httpServer = import_http.default.createServer(this.expressServer);
1472
+ this.setupHttpServer();
1473
+ }
1474
+ resolveOptions = (options) => {
1475
+ const defaultServerPath = "./source/server/index.ts";
1476
+ const resolvedOptions = {
1477
+ server: options?.server || defaultServerPath
1478
+ };
1479
+ return resolvedOptions;
1480
+ };
1481
+ setupExpressServer() {
1482
+ }
1483
+ setupHttpServer() {
1484
+ this.httpServer.on("connection", (socket) => {
1485
+ this.sockets.push(socket);
1486
+ socket.once("close", () => {
1487
+ this.sockets.splice(this.sockets.indexOf(socket), 1);
1488
+ });
991
1489
  });
992
- const page = yield browser.newPage();
993
- try {
994
- const url = host + route;
995
- yield page.goto(url, {
996
- waitUntil: configuration.waitUntil,
997
- timeout: configuration.timeout
998
- });
999
- } catch (err) {
1000
- throw new Error(`${route} timed out.`);
1001
- }
1002
- const pageContent = yield page.content();
1490
+ this.httpServer.on("error", (error) => {
1491
+ throw error;
1492
+ });
1493
+ }
1494
+ start() {
1495
+ throw new Error(
1496
+ "PluridLiveServer is not implemented yet. Use `PluridServer` (production) or a bundler dev server (tsx/Vite) for live reload."
1497
+ );
1498
+ }
1499
+ };
1500
+ var LiveServer_default = LiveServer;
1501
+
1502
+ // source/objects/StillsGenerator/index.ts
1503
+ var import_path3 = __toESM(require("path"));
1504
+ var import_fs3 = require("fs");
1505
+ var import_child_process = require("child_process");
1506
+ var import_detect_port = __toESM(require("detect-port"));
1507
+ var import_plurid_functions2 = require("@plurid/plurid-functions");
1508
+
1509
+ // source/objects/Stiller/index.ts
1510
+ var replacePluridResolution = (html) => {
1511
+ const normalResolution = "width: 1366px; height: 768px;";
1512
+ const zeroResolution = "width: 0px; height: 0px;";
1513
+ return html.replace(normalResolution, zeroResolution);
1514
+ };
1515
+ var isCurrentUserRoot = () => {
1516
+ return typeof process.getuid === "function" && process.getuid() === 0;
1517
+ };
1518
+ var render = async (browser, host, route, configuration) => {
1519
+ const start = Date.now();
1520
+ const page = await browser.newPage();
1521
+ try {
1522
+ const url = host + route;
1523
+ await page.goto(
1524
+ url,
1525
+ {
1526
+ waitUntil: configuration.waitUntil,
1527
+ timeout: configuration.timeout
1528
+ }
1529
+ );
1530
+ const pageContent = await page.content();
1003
1531
  const html = replacePluridResolution(pageContent);
1004
- yield browser.close();
1005
1532
  const stilltime = Date.now() - start;
1006
- console.info(`\tStilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
1533
+ console.info(` Stilled '${route}' in ${(stilltime / 1e3).toFixed(2)} seconds.`);
1007
1534
  return {
1008
- route: route,
1009
- html: html,
1010
- stilltime: stilltime
1535
+ route,
1536
+ html,
1537
+ stilltime
1011
1538
  };
1012
- }));
1013
-
1014
- class Stiller {
1015
- constructor(options) {
1016
- try {
1017
- this.puppeteer = require("puppeteer");
1018
- } catch (error) {
1019
- console.error("could not load puppeteer: check puppeteer is installed");
1020
- }
1021
- const {host: host, routes: routes, configuration: configuration} = options;
1022
- this.host = host;
1023
- this.routes = routes;
1024
- this.configuration = configuration;
1539
+ } catch (error) {
1540
+ const reason = error instanceof Error ? error.message : String(error);
1541
+ throw new Error(`Could not still '${route}': ${reason}`, { cause: error });
1542
+ } finally {
1543
+ await page.close();
1544
+ }
1545
+ };
1546
+ var Stiller = class {
1547
+ puppeteer = null;
1548
+ host;
1549
+ routes;
1550
+ configuration;
1551
+ constructor(options) {
1552
+ try {
1553
+ this.puppeteer = require("puppeteer");
1554
+ } catch (_error) {
1555
+ this.puppeteer = null;
1025
1556
  }
1026
- still() {
1027
- return __asyncGenerator(this, arguments, (function* still_1() {
1028
- for (const route of this.routes) {
1029
- yield yield __await(yield __await(render(this.puppeteer, this.host, route, this.configuration)));
1030
- }
1031
- }));
1557
+ const {
1558
+ host,
1559
+ routes,
1560
+ configuration
1561
+ } = options;
1562
+ this.host = host;
1563
+ this.routes = routes;
1564
+ this.configuration = configuration;
1565
+ }
1566
+ async *still() {
1567
+ if (!this.puppeteer) {
1568
+ throw new Error(
1569
+ "Plurid Stiller: the optional 'puppeteer' dependency is not installed. Install it to generate stills (npm install puppeteer)."
1570
+ );
1032
1571
  }
1033
- }
1034
-
1035
- class StillsGenerator {
1036
- constructor(options) {
1037
- this.options = this.resolveOptions(options);
1572
+ const browser = await this.puppeteer.launch({
1573
+ defaultViewport: {
1574
+ width: 1366,
1575
+ height: 768
1576
+ },
1577
+ headless: true,
1578
+ args: isCurrentUserRoot() ? ["--no-sandbox"] : void 0
1579
+ });
1580
+ try {
1581
+ for (const route of this.routes) {
1582
+ yield await render(
1583
+ browser,
1584
+ this.host,
1585
+ route,
1586
+ this.configuration
1587
+ );
1588
+ }
1589
+ } finally {
1590
+ await browser.close();
1038
1591
  }
1039
- resolveOptions(options) {
1040
- var _a, _b;
1041
- const stillsGeneratorOptions = {
1042
- server: (_a = options === null || options === void 0 ? void 0 : options.server) !== null && _a !== void 0 ? _a : "./build/server.js",
1043
- build: (_b = options === null || options === void 0 ? void 0 : options.build) !== null && _b !== void 0 ? _b : "./build/"
1044
- };
1045
- return stillsGeneratorOptions;
1592
+ }
1593
+ };
1594
+ var Stiller_default = Stiller;
1595
+
1596
+ // source/objects/StillsGenerator/index.ts
1597
+ var StillsGenerator = class {
1598
+ options;
1599
+ constructor(options) {
1600
+ this.options = this.resolveOptions(options);
1601
+ }
1602
+ resolveOptions(options) {
1603
+ const stillsGeneratorOptions = {
1604
+ server: options?.server ?? "./build/server.js",
1605
+ build: options?.build ?? "./build/"
1606
+ };
1607
+ return stillsGeneratorOptions;
1608
+ }
1609
+ async initialize() {
1610
+ const serverPath = import_path3.default.join(process.cwd(), this.options.server);
1611
+ const buildPath = import_path3.default.join(process.cwd(), this.options.build);
1612
+ let serverModule;
1613
+ try {
1614
+ serverModule = require(serverPath);
1615
+ } catch (error) {
1616
+ const reason = error instanceof Error ? error.message : String(error);
1617
+ throw new Error(
1618
+ `Plurid StillsGenerator: could not load the built server at '${serverPath}'. Build the server first so the generator can read its routes. (${reason})`,
1619
+ { cause: error }
1620
+ );
1046
1621
  }
1047
- initialize() {
1048
- return __awaiter(this, void 0, void 0, (function*() {
1049
- const serverPath = path__default["default"].join(process.cwd(), this.options.server);
1050
- const buildPath = path__default["default"].join(process.cwd(), this.options.build);
1051
- const pluridServer = require(serverPath);
1052
- const serverInformation = PluridServer.analysis(pluridServer);
1053
- const stillerOptions = serverInformation.options.stiller;
1054
- const serverPort = (yield detectPort__default["default"](9900)) + "";
1055
- const child = child_process.fork(serverPath, [], {
1056
- stdio: "pipe",
1057
- env: {
1058
- PORT: serverPort,
1059
- PLURID_OPEN: "false"
1060
- }
1061
- });
1062
- const stillRoutes = [];
1063
- for (const route of serverInformation.routes) {
1064
- if (route.value.includes("/:")) {
1065
- continue;
1066
- }
1067
- if (stillerOptions.ignore.includes(route.value)) {
1068
- continue;
1069
- }
1070
- stillRoutes.push(route);
1071
- }
1072
- const stillRoutesPaths = stillRoutes.map((stillRoute => stillRoute.value));
1073
- console.info("\n\tParsed the following still routes:");
1074
- for (const stillRoutePath of stillRoutesPaths) {
1075
- console.info(`\t ${stillRoutePath}`);
1076
- }
1077
- yield new Promise((resolve => setTimeout(resolve, 1500)));
1078
- const startTime = Date.now();
1079
- const estimatedDuration = 3 * serverInformation.routes.length;
1080
- console.info(`\n\tStarting to generate stills... (this may take about ${estimatedDuration} seconds)\n`);
1081
- const stiller = new Stiller({
1082
- host: "http://localhost:" + serverPort,
1083
- routes: [ ...stillRoutesPaths ],
1084
- configuration: {
1085
- waitUntil: stillerOptions.waitUntil,
1086
- timeout: stillerOptions.timeout
1087
- }
1088
- });
1089
- const sequence = stiller.still();
1090
- const stills = [];
1091
- let next;
1092
- while (!(next = yield sequence.next()).done) {
1093
- stills.push(next.value);
1094
- }
1095
- const endTime = Date.now();
1096
- const duration = (endTime - startTime) / 1e3;
1097
- const plural = stills.length === 1 ? "" : "s";
1098
- console.info(`\n\tGenerated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.\n`);
1099
- const stillsPath = path__default["default"].join(buildPath, "./stills");
1100
- yield fs.promises.mkdir(stillsPath, {
1101
- recursive: true
1102
- });
1103
- const metadataFile = [];
1104
- for (const still of stills) {
1105
- if (!still) {
1106
- continue;
1107
- }
1108
- const stillName = pluridFunctions.uuid.generate() + ".json";
1109
- const metadataItem = {
1110
- route: still.route,
1111
- name: stillName
1112
- };
1113
- metadataFile.push(metadataItem);
1114
- const stillJSON = JSON.stringify(still, null, 4);
1115
- const stillFile = path__default["default"].join(stillsPath, stillName);
1116
- yield fs.promises.writeFile(stillFile, stillJSON);
1117
- }
1118
- const metadataFilePath = path__default["default"].join(stillsPath, "metadata.json");
1119
- const metadataJSON = JSON.stringify(metadataFile, null, 4);
1120
- yield fs.promises.writeFile(metadataFilePath, metadataJSON);
1121
- child.kill(2);
1122
- }));
1622
+ const pluridServer = serverModule?.default ?? serverModule;
1623
+ const serverInformation = Server_default.analysis(pluridServer);
1624
+ const stillerOptions = serverInformation.options.stiller;
1625
+ const serverPort = await (0, import_detect_port.default)(9900) + "";
1626
+ const child = (0, import_child_process.fork)(serverPath, [], {
1627
+ stdio: "pipe",
1628
+ env: {
1629
+ PORT: serverPort,
1630
+ PLURID_OPEN: "false"
1631
+ }
1632
+ });
1633
+ try {
1634
+ const stillRoutes = [];
1635
+ for (const route of serverInformation.routes) {
1636
+ if (route.value.includes("/:")) {
1637
+ continue;
1638
+ }
1639
+ if (stillerOptions.ignore.includes(route.value)) {
1640
+ continue;
1641
+ }
1642
+ stillRoutes.push(route);
1643
+ }
1644
+ const stillRoutesPaths = stillRoutes.map((stillRoute) => stillRoute.value);
1645
+ console.info("\n Parsed the following still routes:");
1646
+ for (const stillRoutePath of stillRoutesPaths) {
1647
+ console.info(` ${stillRoutePath}`);
1648
+ }
1649
+ await new Promise((resolve) => setTimeout(resolve, 1500));
1650
+ const startTime = Date.now();
1651
+ const estimatedDuration = 3 * serverInformation.routes.length;
1652
+ console.info(`
1653
+ Starting to generate stills... (this may take about ${estimatedDuration} seconds)
1654
+ `);
1655
+ const stiller = new Stiller_default({
1656
+ host: "http://localhost:" + serverPort,
1657
+ routes: [
1658
+ ...stillRoutesPaths
1659
+ ],
1660
+ configuration: {
1661
+ waitUntil: stillerOptions.waitUntil,
1662
+ timeout: stillerOptions.timeout
1663
+ }
1664
+ });
1665
+ const sequence = stiller.still();
1666
+ const stills = [];
1667
+ let next;
1668
+ while (!(next = await sequence.next()).done) {
1669
+ stills.push(next.value);
1670
+ }
1671
+ const endTime = Date.now();
1672
+ const duration = (endTime - startTime) / 1e3;
1673
+ const plural = stills.length === 1 ? "" : "s";
1674
+ console.info(`
1675
+ Generated ${stills.length} still${plural} in ${duration.toFixed(2)} seconds.
1676
+ `);
1677
+ const stillsPath = import_path3.default.join(buildPath, "./stills");
1678
+ await import_fs3.promises.mkdir(
1679
+ stillsPath,
1680
+ {
1681
+ recursive: true
1682
+ }
1683
+ );
1684
+ const metadataFile = [];
1685
+ for (const still of stills) {
1686
+ if (!still) {
1687
+ continue;
1688
+ }
1689
+ const stillName = import_plurid_functions2.uuid.generate() + ".json";
1690
+ const metadataItem = {
1691
+ route: still.route,
1692
+ name: stillName
1693
+ };
1694
+ metadataFile.push(metadataItem);
1695
+ const stillJSON = JSON.stringify(still, null, 4);
1696
+ const stillFile = import_path3.default.join(stillsPath, stillName);
1697
+ await import_fs3.promises.writeFile(stillFile, stillJSON);
1698
+ }
1699
+ const metadataFilePath = import_path3.default.join(stillsPath, "metadata.json");
1700
+ const metadataJSON = JSON.stringify(metadataFile, null, 4);
1701
+ await import_fs3.promises.writeFile(metadataFilePath, metadataJSON);
1702
+ } finally {
1703
+ child.kill("SIGTERM");
1123
1704
  }
1124
- }
1125
-
1126
- exports.PluridLiveServer = LiveServer;
1127
-
1128
- exports.PluridStillsGenerator = StillsGenerator;
1129
-
1130
- exports["default"] = PluridServer;
1705
+ }
1706
+ };
1707
+ var StillsGenerator_default = StillsGenerator;
1708
+
1709
+ // source/index.ts
1710
+ var index_default = Server_default;
1711
+ // Annotate the CommonJS export names for ESM import in node:
1712
+ 0 && (module.exports = {
1713
+ PluridLiveServer,
1714
+ PluridStillsGenerator
1715
+ });
1716
+ //# sourceMappingURL=index.js.map