@ms-cloudpack/app-server 0.20.0 → 0.20.2

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 (60) hide show
  1. package/lib/renderRoute/getErrorResponse.d.ts +20 -0
  2. package/lib/renderRoute/getErrorResponse.d.ts.map +1 -0
  3. package/lib/renderRoute/getErrorResponse.js +44 -0
  4. package/lib/renderRoute/getErrorResponse.js.map +1 -0
  5. package/lib/renderRoute/injectScripts.d.ts +8 -0
  6. package/lib/renderRoute/injectScripts.d.ts.map +1 -0
  7. package/lib/renderRoute/injectScripts.js +81 -0
  8. package/lib/renderRoute/injectScripts.js.map +1 -0
  9. package/lib/renderRoute/isHtmlAcceptable.d.ts +11 -0
  10. package/lib/renderRoute/isHtmlAcceptable.d.ts.map +1 -0
  11. package/lib/renderRoute/isHtmlAcceptable.js +26 -0
  12. package/lib/renderRoute/isHtmlAcceptable.js.map +1 -0
  13. package/lib/renderRoute/renderRoute.d.ts +1 -1
  14. package/lib/renderRoute/renderRoute.d.ts.map +1 -1
  15. package/lib/renderRoute/renderRoute.js +17 -174
  16. package/lib/renderRoute/renderRoute.js.map +1 -1
  17. package/lib/renderRoute/ssr/bundleServerEntry.d.ts +7 -0
  18. package/lib/renderRoute/ssr/bundleServerEntry.d.ts.map +1 -0
  19. package/lib/renderRoute/ssr/bundleServerEntry.js +54 -0
  20. package/lib/renderRoute/ssr/bundleServerEntry.js.map +1 -0
  21. package/lib/renderRoute/{renderCustomScript.d.ts → ssr/renderCustomScript.d.ts} +1 -0
  22. package/lib/renderRoute/ssr/renderCustomScript.d.ts.map +1 -0
  23. package/lib/renderRoute/{renderCustomScript.js → ssr/renderCustomScript.js} +19 -16
  24. package/lib/renderRoute/ssr/renderCustomScript.js.map +1 -0
  25. package/lib/renderRoute/ssr/runServerEntryInWorker.d.ts +1 -1
  26. package/lib/renderRoute/ssr/runServerEntryInWorker.d.ts.map +1 -1
  27. package/lib/renderRoute/ssr/runServerEntryInWorker.js +8 -18
  28. package/lib/renderRoute/ssr/runServerEntryInWorker.js.map +1 -1
  29. package/lib/renderRoute/ssr/types/RunServerEntryOptions.d.ts +7 -2
  30. package/lib/renderRoute/ssr/types/RunServerEntryOptions.d.ts.map +1 -1
  31. package/lib/renderRoute/ssr/types/RunServerEntryOptions.js.map +1 -1
  32. package/lib/renderRoute/ssr/worker/importMapLoader.d.ts +36 -0
  33. package/lib/renderRoute/ssr/worker/importMapLoader.d.ts.map +1 -0
  34. package/lib/renderRoute/ssr/worker/importMapLoader.js +64 -0
  35. package/lib/renderRoute/ssr/worker/importMapLoader.js.map +1 -0
  36. package/lib/renderRoute/ssr/worker/runServerEntry.d.ts +13 -0
  37. package/lib/renderRoute/ssr/worker/runServerEntry.d.ts.map +1 -0
  38. package/lib/renderRoute/ssr/{runServerEntry.js → worker/runServerEntry.js} +18 -8
  39. package/lib/renderRoute/ssr/worker/runServerEntry.js.map +1 -0
  40. package/lib/renderRoute/ssr/worker/ssrWorkerEntry.d.ts +2 -0
  41. package/lib/renderRoute/ssr/worker/ssrWorkerEntry.d.ts.map +1 -0
  42. package/lib/renderRoute/ssr/worker/{workerEntry.js → ssrWorkerEntry.js} +4 -4
  43. package/lib/renderRoute/ssr/worker/ssrWorkerEntry.js.map +1 -0
  44. package/package.json +4 -4
  45. package/lib/renderRoute/getHtmlErrorResponse.d.ts +0 -6
  46. package/lib/renderRoute/getHtmlErrorResponse.d.ts.map +0 -1
  47. package/lib/renderRoute/getHtmlErrorResponse.js +0 -22
  48. package/lib/renderRoute/getHtmlErrorResponse.js.map +0 -1
  49. package/lib/renderRoute/renderCustomScript.d.ts.map +0 -1
  50. package/lib/renderRoute/renderCustomScript.js.map +0 -1
  51. package/lib/renderRoute/ssr/importMapLoader.d.ts +0 -13
  52. package/lib/renderRoute/ssr/importMapLoader.d.ts.map +0 -1
  53. package/lib/renderRoute/ssr/importMapLoader.js +0 -37
  54. package/lib/renderRoute/ssr/importMapLoader.js.map +0 -1
  55. package/lib/renderRoute/ssr/runServerEntry.d.ts +0 -4
  56. package/lib/renderRoute/ssr/runServerEntry.d.ts.map +0 -1
  57. package/lib/renderRoute/ssr/runServerEntry.js.map +0 -1
  58. package/lib/renderRoute/ssr/worker/workerEntry.d.ts +0 -2
  59. package/lib/renderRoute/ssr/worker/workerEntry.d.ts.map +0 -1
  60. package/lib/renderRoute/ssr/worker/workerEntry.js.map +0 -1
@@ -0,0 +1,20 @@
1
+ import type { ExpandedRenderFunctionResult, RenderFunctionOptions } from '@ms-cloudpack/common-types';
2
+ /**
3
+ * Log the error to the console and return an error response (500 status code).
4
+ *
5
+ * If it appears that the given request accepts HTML, it returns an HTML page,
6
+ * or plain text otherwise.
7
+ */
8
+ export declare function getErrorResponse(params: Pick<RenderFunctionOptions, 'req'> & {
9
+ message: string;
10
+ }): ExpandedRenderFunctionResult;
11
+ /**
12
+ * Fill in details of the message, log to console.error, and return an error response.
13
+ * `Route ${route.match} with (renderScript|serverEntry) "${scriptPath}" ${message}`
14
+ */
15
+ export declare function getCustomRenderErrorResponse(params: Pick<RenderFunctionOptions, 'req' | 'route'> & {
16
+ /** Error details (NOTE the format in the main function comment) */
17
+ message: string;
18
+ scriptPath: string | undefined;
19
+ }): ExpandedRenderFunctionResult;
20
+ //# sourceMappingURL=getErrorResponse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getErrorResponse.d.ts","sourceRoot":"","sources":["../../src/renderRoute/getErrorResponse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAKtG;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,IAAI,CAAC,qBAAqB,EAAE,KAAK,CAAC,GAAG;IAC3C,OAAO,EAAE,MAAM,CAAC;CACjB,GACA,4BAA4B,CA0B9B;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,IAAI,CAAC,qBAAqB,EAAE,KAAK,GAAG,OAAO,CAAC,GAAG;IACrD,mEAAmE;IACnE,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC,GACA,4BAA4B,CAO9B"}
@@ -0,0 +1,44 @@
1
+ import { isHtmlAcceptable } from './isHtmlAcceptable.js';
2
+ const statusCode = 500;
3
+ /**
4
+ * Log the error to the console and return an error response (500 status code).
5
+ *
6
+ * If it appears that the given request accepts HTML, it returns an HTML page,
7
+ * or plain text otherwise.
8
+ */
9
+ export function getErrorResponse(params) {
10
+ const { message, req } = params;
11
+ console.error(`App server: request ${req.url} - ${message}`);
12
+ if (!isHtmlAcceptable(req)) {
13
+ // If HTML is not acceptable, return a plain text response
14
+ return {
15
+ content: message,
16
+ statusCode,
17
+ contentType: 'text/plain',
18
+ };
19
+ }
20
+ return {
21
+ content: `<!DOCTYPE html>
22
+ <html lang="en">
23
+ <head><title>Error</title></head>
24
+ <body>
25
+ <h1>Error</h1>
26
+ <pre>${message}</pre>
27
+ </body>
28
+ </html>`,
29
+ statusCode,
30
+ contentType: 'text/html',
31
+ };
32
+ }
33
+ /**
34
+ * Fill in details of the message, log to console.error, and return an error response.
35
+ * `Route ${route.match} with (renderScript|serverEntry) "${scriptPath}" ${message}`
36
+ */
37
+ export function getCustomRenderErrorResponse(params) {
38
+ const { message, req, route, scriptPath } = params;
39
+ const scriptType = route.serverEntry ? 'serverEntry' : 'renderScript';
40
+ const renderer = scriptPath ? `${scriptType} "${scriptPath}"` : 'the default renderer';
41
+ const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;
42
+ return getErrorResponse({ req, message: content });
43
+ }
44
+ //# sourceMappingURL=getErrorResponse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getErrorResponse.js","sourceRoot":"","sources":["../../src/renderRoute/getErrorResponse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAC9B,MAEC;IAED,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;IAEhC,OAAO,CAAC,KAAK,CAAC,uBAAuB,GAAG,CAAC,GAAG,MAAM,OAAO,EAAE,CAAC,CAAC;IAE7D,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3B,0DAA0D;QAC1D,OAAO;YACL,OAAO,EAAE,OAAO;YAChB,UAAU;YACV,WAAW,EAAE,YAAY;SAC1B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO,EAAE;;;;;SAKJ,OAAO;;QAER;QACJ,UAAU;QACV,WAAW,EAAE,WAAW;KACzB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,4BAA4B,CAC1C,MAIC;IAED,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IACnD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,cAAc,CAAC;IACtE,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,KAAK,UAAU,GAAG,CAAC,CAAC,CAAC,sBAAsB,CAAC;IACvF,MAAM,OAAO,GAAG,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,QAAQ,IAAI,OAAO,EAAE,CAAC;IAEnF,OAAO,gBAAgB,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { ExpandedRenderFunctionResult, RenderFunctionOptions } from '@ms-cloudpack/common-types';\nimport { isHtmlAcceptable } from './isHtmlAcceptable.js';\n\nconst statusCode = 500;\n\n/**\n * Log the error to the console and return an error response (500 status code).\n *\n * If it appears that the given request accepts HTML, it returns an HTML page,\n * or plain text otherwise.\n */\nexport function getErrorResponse(\n params: Pick<RenderFunctionOptions, 'req'> & {\n message: string;\n },\n): ExpandedRenderFunctionResult {\n const { message, req } = params;\n\n console.error(`App server: request ${req.url} - ${message}`);\n\n if (!isHtmlAcceptable(req)) {\n // If HTML is not acceptable, return a plain text response\n return {\n content: message,\n statusCode,\n contentType: 'text/plain',\n };\n }\n\n return {\n content: `<!DOCTYPE html>\n<html lang=\"en\">\n<head><title>Error</title></head>\n<body>\n <h1>Error</h1>\n <pre>${message}</pre>\n</body>\n</html>`,\n statusCode,\n contentType: 'text/html',\n };\n}\n\n/**\n * Fill in details of the message, log to console.error, and return an error response.\n * `Route ${route.match} with (renderScript|serverEntry) \"${scriptPath}\" ${message}`\n */\nexport function getCustomRenderErrorResponse(\n params: Pick<RenderFunctionOptions, 'req' | 'route'> & {\n /** Error details (NOTE the format in the main function comment) */\n message: string;\n scriptPath: string | undefined;\n },\n): ExpandedRenderFunctionResult {\n const { message, req, route, scriptPath } = params;\n const scriptType = route.serverEntry ? 'serverEntry' : 'renderScript';\n const renderer = scriptPath ? `${scriptType} \"${scriptPath}\"` : 'the default renderer';\n const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;\n\n return getErrorResponse({ req, message: content });\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { RenderFunctionOptions, ExpandedRenderFunctionResult } from '@ms-cloudpack/common-types';
2
+ /**
3
+ * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.
4
+ *
5
+ * Note that this just logs an error rather than returning an error response if something fails, for now.
6
+ */
7
+ export declare function injectScripts(options: RenderFunctionOptions, result: ExpandedRenderFunctionResult): Promise<void>;
8
+ //# sourceMappingURL=injectScripts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"injectScripts.d.ts","sourceRoot":"","sources":["../../src/renderRoute/injectScripts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAItG;;;;GAIG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,qBAAqB,EAC9B,MAAM,EAAE,4BAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,CAsDf"}
@@ -0,0 +1,81 @@
1
+ import { Window } from 'happy-dom';
2
+ import HTMLSerializer from 'happy-dom/lib/html-serializer/HTMLSerializer.js';
3
+ /**
4
+ * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.
5
+ *
6
+ * Note that this just logs an error rather than returning an error response if something fails, for now.
7
+ */
8
+ export async function injectScripts(options, result) {
9
+ const { route, overlayScript, entryScripts, inlineScripts, importMap, baseUrl } = options;
10
+ const window = new Window({
11
+ url: baseUrl,
12
+ settings: {
13
+ disableJavaScriptFileLoading: true,
14
+ disableJavaScriptEvaluation: true,
15
+ disableCSSFileLoading: true,
16
+ disableIframePageLoading: true,
17
+ },
18
+ });
19
+ try {
20
+ // TODO: happy-dom is overkill for what we're doing here--a full browser-like environment isn't
21
+ // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since
22
+ // HTML page rendering is probably just done once per page load), we could switch to
23
+ // a pure parser like parse5 or htmlparser2.
24
+ window.document.write(result.content);
25
+ }
26
+ catch (e) {
27
+ // Trying to write a test for the above, it seemed very permissive, but catch just in case
28
+ console.error(`Error parsing html response for rendering route "${JSON.stringify(route.match)}":\n${e.stack || e}`);
29
+ return;
30
+ }
31
+ try {
32
+ const document = window.document;
33
+ if (entryScripts || overlayScript) {
34
+ // Inject the import map at the top of the head, in case other scripts use it
35
+ addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });
36
+ }
37
+ if (inlineScripts) {
38
+ for (const inlineScript of inlineScripts) {
39
+ addScript({ document, content: inlineScript });
40
+ }
41
+ }
42
+ // inject the overlay and entry scripts
43
+ addScript({ document, url: overlayScript });
44
+ if (entryScripts) {
45
+ for (const entryScript of entryScripts) {
46
+ addScript({ document, url: entryScript });
47
+ }
48
+ }
49
+ const serializer = new HTMLSerializer();
50
+ result.content = serializer.serializeToString(document);
51
+ await window.happyDOM.close();
52
+ }
53
+ catch (e) {
54
+ console.error(`Error injecting scripts for route "${JSON.stringify(route.match)}":\n${e.stack || e}`);
55
+ }
56
+ }
57
+ /**
58
+ * Helper function to add a script to the document.
59
+ * No-op if neither `url` nor `content` is provided.
60
+ */
61
+ function addScript(params) {
62
+ const { document, type = 'module', prepend, url, content } = params;
63
+ if (!url && !content) {
64
+ return;
65
+ }
66
+ const script = document.createElement('script');
67
+ script.type = type;
68
+ if (url) {
69
+ script.src = url;
70
+ }
71
+ else if (content) {
72
+ script.innerHTML = content;
73
+ }
74
+ if (prepend) {
75
+ document.head.prepend(script);
76
+ }
77
+ else {
78
+ document.head.appendChild(script);
79
+ }
80
+ }
81
+ //# sourceMappingURL=injectScripts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"injectScripts.js","sourceRoot":"","sources":["../../src/renderRoute/injectScripts.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAiB,MAAM,WAAW,CAAC;AAClD,OAAO,cAAc,MAAM,iDAAiD,CAAC;AAE7E;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,OAA8B,EAC9B,MAAoC;IAEpC,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAC1F,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC;QACxB,GAAG,EAAE,OAAO;QACZ,QAAQ,EAAE;YACR,4BAA4B,EAAE,IAAI;YAClC,2BAA2B,EAAE,IAAI;YACjC,qBAAqB,EAAE,IAAI;YAC3B,wBAAwB,EAAE,IAAI;SAC/B;KACF,CAAC,CAAC;IACH,IAAI,CAAC;QACH,+FAA+F;QAC/F,4FAA4F;QAC5F,oFAAoF;QACpF,4CAA4C;QAC5C,MAAM,CAAC,QAAQ,CAAC,KAAK,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OAAO,CAAC,KAAK,CAAC,sCAAsC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,OAAQ,CAAW,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC,CAAC;IACnH,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAS,SAAS,CAAC,MAMlB;IACC,MAAM,EAAE,QAAQ,EAAE,IAAI,GAAG,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IACpE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QACrB,OAAO;IACT,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;SAAM,IAAI,OAAO,EAAE,CAAC;QACnB,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { RenderFunctionOptions, ExpandedRenderFunctionResult } from '@ms-cloudpack/common-types';\nimport { Window, type Document } from 'happy-dom';\nimport HTMLSerializer from 'happy-dom/lib/html-serializer/HTMLSerializer.js';\n\n/**\n * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.\n *\n * Note that this just logs an error rather than returning an error response if something fails, for now.\n */\nexport async function injectScripts(\n options: RenderFunctionOptions,\n result: ExpandedRenderFunctionResult,\n): Promise<void> {\n const { route, overlayScript, entryScripts, inlineScripts, importMap, baseUrl } = options;\n const window = new Window({\n url: baseUrl,\n settings: {\n disableJavaScriptFileLoading: true,\n disableJavaScriptEvaluation: true,\n disableCSSFileLoading: true,\n disableIframePageLoading: true,\n },\n });\n try {\n // TODO: happy-dom is overkill for what we're doing here--a full browser-like environment isn't\n // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since\n // HTML page rendering is probably just done once per page load), we could switch to\n // a pure parser like parse5 or htmlparser2.\n window.document.write(result.content);\n } catch (e) {\n // Trying to write a test for the above, it seemed very permissive, but catch just in case\n console.error(\n `Error parsing html response for rendering route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`,\n );\n return;\n }\n\n try {\n const document = window.document;\n\n if (entryScripts || overlayScript) {\n // Inject the import map at the top of the head, in case other scripts use it\n addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });\n }\n\n if (inlineScripts) {\n for (const inlineScript of inlineScripts) {\n addScript({ document, content: inlineScript });\n }\n }\n\n // inject the overlay and entry scripts\n addScript({ document, url: overlayScript });\n\n if (entryScripts) {\n for (const entryScript of entryScripts) {\n addScript({ document, url: entryScript });\n }\n }\n\n const serializer = new HTMLSerializer();\n result.content = serializer.serializeToString(document);\n await window.happyDOM.close();\n } catch (e) {\n console.error(`Error injecting scripts for route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`);\n }\n}\n\n/**\n * Helper function to add a script to the document.\n * No-op if neither `url` nor `content` is provided.\n */\nfunction addScript(params: {\n document: Document;\n type?: string;\n prepend?: boolean;\n url?: string;\n content?: string;\n}): void {\n const { document, type = 'module', prepend, url, content } = params;\n if (!url && !content) {\n return;\n }\n\n const script = document.createElement('script');\n script.type = type;\n if (url) {\n script.src = url;\n } else if (content) {\n script.innerHTML = content;\n }\n\n if (prepend) {\n document.head.prepend(script);\n } else {\n document.head.appendChild(script);\n }\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { Request } from '@ms-cloudpack/common-types';
2
+ /**
3
+ * Determine whether HTML is (probably) an acceptable response type based on the request extension
4
+ * and/or headers. (We can't rely on `req.accepts()` because not all requests set that header.)
5
+ */
6
+ export declare function isHtmlAcceptable(req: Request): boolean;
7
+ /**
8
+ * Determine whether the given `Accept` or `Content-Type` header allows HTML.
9
+ */
10
+ export declare function isHtmlType(acceptOrContentType: string): boolean;
11
+ //# sourceMappingURL=isHtmlAcceptable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isHtmlAcceptable.d.ts","sourceRoot":"","sources":["../../src/renderRoute/isHtmlAcceptable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAI1D;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAMtD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,mBAAmB,EAAE,MAAM,GAAG,OAAO,CAS/D"}
@@ -0,0 +1,26 @@
1
+ import { makeUrl } from '@ms-cloudpack/path-string-parsing';
2
+ import path from 'path';
3
+ /**
4
+ * Determine whether HTML is (probably) an acceptable response type based on the request extension
5
+ * and/or headers. (We can't rely on `req.accepts()` because not all requests set that header.)
6
+ */
7
+ export function isHtmlAcceptable(req) {
8
+ // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)
9
+ const requestPath = makeUrl(req.url, 'http://example.com').pathname;
10
+ const requestExt = path.extname(requestPath);
11
+ return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');
12
+ }
13
+ /**
14
+ * Determine whether the given `Accept` or `Content-Type` header allows HTML.
15
+ */
16
+ export function isHtmlType(acceptOrContentType) {
17
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
18
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values
19
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
20
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
21
+ return acceptOrContentType
22
+ .split(',')
23
+ .map((s) => s.split(';')[0].trim())
24
+ .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\/\*$/.test(mime));
25
+ }
26
+ //# sourceMappingURL=isHtmlAcceptable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isHtmlAcceptable.js","sourceRoot":"","sources":["../../src/renderRoute/isHtmlAcceptable.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAY;IAC3C,iGAAiG;IACjG,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC;IACpE,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IAE7C,OAAO,CAAC,CAAC,UAAU,IAAI,UAAU,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC;AAC/G,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,mBAA2B;IACpD,mEAAmE;IACnE,sGAAsG;IACtG,yEAAyE;IACzE,2FAA2F;IAC3F,OAAO,mBAAmB;SACvB,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SAClC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,KAAK,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACzG,CAAC","sourcesContent":["import type { Request } from '@ms-cloudpack/common-types';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport path from 'path';\n\n/**\n * Determine whether HTML is (probably) an acceptable response type based on the request extension\n * and/or headers. (We can't rely on `req.accepts()` because not all requests set that header.)\n */\nexport function isHtmlAcceptable(req: Request): boolean {\n // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)\n const requestPath = makeUrl(req.url, 'http://example.com').pathname;\n const requestExt = path.extname(requestPath);\n\n return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');\n}\n\n/**\n * Determine whether the given `Accept` or `Content-Type` header allows HTML.\n */\nexport function isHtmlType(acceptOrContentType: string): boolean {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n return acceptOrContentType\n .split(',')\n .map((s) => s.split(';')[0].trim())\n .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\\/\\*$/.test(mime));\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { RenderFunctionOptions, ExpandedRenderFunctionResult } from '@ms-cloudpack/common-types';
2
1
  import { type EnsurePackageBundledContext } from '@ms-cloudpack/api-server';
2
+ import type { ExpandedRenderFunctionResult, RenderFunctionOptions } from '@ms-cloudpack/common-types';
3
3
  /**
4
4
  * Get the response for the given route. If the route has a custom render script, use that.
5
5
  * Returns an error response if the file referenced by the script doesn't exist or throws an error.
@@ -1 +1 @@
1
- {"version":3,"file":"renderRoute.d.ts","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EAErB,4BAA4B,EAG7B,MAAM,4BAA4B,CAAC;AAcpC,OAAO,EAAwB,KAAK,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAKlG;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,4BAA4B,GAAG,IAAI,CAAC,CAwG9C"}
1
+ {"version":3,"file":"renderRoute.d.ts","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAC5E,OAAO,KAAK,EACV,4BAA4B,EAC5B,qBAAqB,EAEtB,MAAM,4BAA4B,CAAC;AAWpC;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,4BAA4B,GAAG,IAAI,CAAC,CAwG9C"}
@@ -1,15 +1,12 @@
1
- import { makeUrl } from '@ms-cloudpack/path-string-parsing';
1
+ import { javascriptExtensions, sourceExtensions, typescriptExtensions } from '@ms-cloudpack/path-utilities';
2
2
  import fsPromises from 'fs/promises';
3
- import { Window } from 'happy-dom';
4
3
  import path from 'path';
5
4
  import { getDefaultHtmlResponse } from './getDefaultHtmlResponse.js';
6
- import { getHtmlErrorResponse } from './getHtmlErrorResponse.js';
7
- import HTMLSerializer from 'happy-dom/lib/html-serializer/HTMLSerializer.js';
8
- import { javascriptExtensions, sourceExtensions, sourceToIntermediatePath, typescriptExtensions, } from '@ms-cloudpack/path-utilities';
9
- import { ensurePackageBundled } from '@ms-cloudpack/api-server';
10
- import { bulletedList } from '@ms-cloudpack/task-reporter';
11
- import { environmentInfo } from '@ms-cloudpack/environment';
12
- import { renderCustomScript } from './renderCustomScript.js';
5
+ import { getCustomRenderErrorResponse, getErrorResponse } from './getErrorResponse.js';
6
+ import { injectScripts } from './injectScripts.js';
7
+ import { isHtmlAcceptable, isHtmlType } from './isHtmlAcceptable.js';
8
+ import { bundleServerEntry } from './ssr/bundleServerEntry.js';
9
+ import { renderCustomScript } from './ssr/renderCustomScript.js';
13
10
  /**
14
11
  * Get the response for the given route. If the route has a custom render script, use that.
15
12
  * Returns an error response if the file referenced by the script doesn't exist or throws an error.
@@ -44,7 +41,7 @@ export async function renderRoute(options, context) {
44
41
  const scriptExt = path.extname(renderScriptPath).toLowerCase();
45
42
  if (scriptExt === '.html' || scriptExt === '.htm') {
46
43
  // HTML file: just read it
47
- rawResult = await readStaticHtml(renderScriptPath);
44
+ rawResult = await readStaticHtml({ renderScriptPath, req: options.req });
48
45
  }
49
46
  else if (javascriptExtensions.includes(scriptExt)) {
50
47
  // JS file: run its function
@@ -64,7 +61,7 @@ export async function renderRoute(options, context) {
64
61
  'If you want to serve a static non-HTML file, use a route with `staticPath`, or a `serverEntry` ' +
65
62
  'which returns the file content for advanced scenarios.';
66
63
  }
67
- return makeErrorResponse({
64
+ return getCustomRenderErrorResponse({
68
65
  message,
69
66
  route,
70
67
  req: options.req,
@@ -80,7 +77,7 @@ export async function renderRoute(options, context) {
80
77
  return null;
81
78
  }
82
79
  if (rawResult === undefined) {
83
- return makeErrorResponse({
80
+ return getCustomRenderErrorResponse({
84
81
  message: `returned undefined. If the script fully handled the request (sent a response), ` +
85
82
  `return null instead. Otherwise ensure that the function returns the content to be rendered.`,
86
83
  route,
@@ -95,14 +92,14 @@ export async function renderRoute(options, context) {
95
92
  };
96
93
  // If it's HTML and a success statusCode, inject the import map and appropriate scripts.
97
94
  if (result.statusCode === 200 && isHtmlType(result.contentType)) {
98
- if (isHtmlAcceptable(options)) {
95
+ if (isHtmlAcceptable(options.req)) {
99
96
  // Inject the import map and scripts.
100
97
  await injectScripts(options, result);
101
98
  }
102
99
  else {
103
100
  // It appears we're accidentally returning HTML when a different file type was requested.
104
101
  // This could happen for overly broad route matches such as '*', or if no routes are configured.
105
- return makeErrorResponse({
102
+ return getCustomRenderErrorResponse({
106
103
  message: 'returned HTML, but this appears to be a non-HTML request. This is likely due to an ' +
107
104
  'overly broad match or other misconfiguration of server.routes in the cloudpack config.',
108
105
  route,
@@ -113,173 +110,19 @@ export async function renderRoute(options, context) {
113
110
  }
114
111
  return result;
115
112
  }
116
- async function bundleServerEntry(options, context) {
117
- const { definition, route, req, serverEntryPath } = options;
118
- const { name, version } = definition;
119
- // targetEnvironment: node currently bundles all node or agnostic entries, and implicitly does
120
- // production bundling. This seems like it could get expensive, but it's probably okay because
121
- // createPackageSettingsTransform overwrites the package's actual exports with the ones generated
122
- // from routes, and those will always have environment conditions.
123
- const response = await ensurePackageBundled({
124
- name,
125
- version,
126
- targetEnvironment: 'node',
127
- // TODO: This will only watch for changes in the given package, not dependencies.
128
- // File watching is disabled in production mode for performance.
129
- shouldWatch: !environmentInfo.isJest && context.session.config.mode !== 'production',
130
- // Irrelevant with implicit production bundling
131
- enqueueDependencies: false,
132
- }, context);
133
- const { errors, outputPath = '', outputFiles = [] } = response.result;
134
- if (errors?.length) {
135
- return makeErrorResponse({
136
- message: `failed to bundle: ${JSON.stringify(response.result.errors, null, 2)}`,
137
- route,
138
- req,
139
- scriptPath: serverEntryPath,
140
- });
141
- }
142
- let serverEntryOutput = outputFiles.find((f) => f.entryPoint === serverEntryPath)?.outputPath;
143
- if (!serverEntryOutput) {
144
- // No literal match, so try the intermediate path without extension.
145
- const intermediateServerEntryPath = sourceToIntermediatePath(serverEntryPath).replace(/\.\w+$/, '');
146
- serverEntryOutput =
147
- outputFiles.find((f) => f.entryPoint === serverEntryPath)?.outputPath ||
148
- outputFiles.find((f) => f.outputPath.replace(/\.\w+$/, '') === intermediateServerEntryPath)?.outputPath;
149
- }
150
- if (!serverEntryOutput) {
151
- return makeErrorResponse({
152
- message: `did not produce a bundle output file corresponding to the serverEntry script (${serverEntryPath}). Produced files:\n${outputFiles.length
153
- ? bulletedList(outputFiles.map((f) => `${f.outputPath} (entry: ${f.entryPoint || 'unknown'})`))
154
- : 'none'}`,
155
- route,
156
- req: options.req,
157
- scriptPath: serverEntryPath,
158
- });
159
- }
160
- // Translate relative-to-output path into an absolute path.
161
- return path.resolve(outputPath, serverEntryOutput);
162
- }
163
- /**
164
- * Fill in details of the message, log to console.error, and return an error response.
165
- * `Route ${route.match} with (renderScript|serverEntry) "${scriptPath}" ${message}`
166
- */
167
- function makeErrorResponse(params) {
168
- const { message, route, scriptPath, req } = params;
169
- const scriptType = route.serverEntry ? 'serverEntry' : 'renderScript';
170
- const renderer = scriptPath ? `${scriptType} "${scriptPath}"` : 'the default renderer';
171
- const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;
172
- console.error(`App server: request ${req.url} - ${content}`);
173
- return { statusCode: 500, contentType: 'text/plain', content };
174
- }
175
- function isHtmlAcceptable(options) {
176
- const { req, baseUrl } = options;
177
- // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)
178
- const requestPath = makeUrl(req.url, baseUrl).pathname;
179
- const requestExt = path.extname(requestPath);
180
- // Determine whether HTML is (probably) an acceptable response type (can be refined later if needed).
181
- // In theory we should be able to use req.accepts() but not all requests set the accept header.
182
- return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');
183
- }
184
- function isHtmlType(acceptOrContentType) {
185
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
186
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values
187
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
188
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
189
- return acceptOrContentType
190
- .split(',')
191
- .map((s) => s.split(';')[0].trim())
192
- .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\/\*$/.test(mime));
193
- }
194
- /**
195
- * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.
196
- *
197
- * Note that this just logs an error rather than returning an error response if something fails, for now.
198
- */
199
- async function injectScripts(options, result) {
200
- const { route, overlayScript, entryScripts, inlineScripts, importMap, baseUrl } = options;
201
- const window = new Window({
202
- url: baseUrl,
203
- settings: {
204
- disableJavaScriptFileLoading: true,
205
- disableJavaScriptEvaluation: true,
206
- disableCSSFileLoading: true,
207
- disableIframePageLoading: true,
208
- },
209
- });
210
- try {
211
- // TODO: happy-dom is overkill for what we're doing here--a full browser-like environment isn't
212
- // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since
213
- // HTML page rendering is probably just done once per page load), we could switch to
214
- // a pure parser like parse5 or htmlparser2.
215
- window.document.write(result.content);
216
- }
217
- catch (e) {
218
- // Trying to write a test for the above, it seemed very permissive, but catch just in case
219
- console.error(`Error parsing html response for rendering route "${JSON.stringify(route.match)}":\n${e.stack || e}`);
220
- return;
221
- }
222
- try {
223
- const document = window.document;
224
- if (entryScripts || overlayScript) {
225
- // Inject the import map at the top of the head, in case other scripts use it
226
- addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });
227
- }
228
- if (inlineScripts) {
229
- for (const inlineScript of inlineScripts) {
230
- addScript({ document, content: inlineScript });
231
- }
232
- }
233
- // inject the overlay and entry scripts
234
- addScript({ document, url: overlayScript });
235
- if (entryScripts) {
236
- for (const entryScript of entryScripts) {
237
- addScript({ document, url: entryScript });
238
- }
239
- }
240
- const serializer = new HTMLSerializer();
241
- result.content = serializer.serializeToString(document);
242
- await window.happyDOM.close();
243
- }
244
- catch (e) {
245
- console.error(`Error injecting scripts for route "${JSON.stringify(route.match)}":\n${e.stack || e}`);
246
- }
247
- }
248
- /**
249
- * Helper function to add a script to the document.
250
- * No-op if neither `url` nor `content` is provided.
251
- */
252
- function addScript(params) {
253
- const { document, type = 'module', prepend, url, content } = params;
254
- if (!url && !content) {
255
- return;
256
- }
257
- const script = document.createElement('script');
258
- script.type = type;
259
- if (url) {
260
- script.src = url;
261
- }
262
- else if (content) {
263
- script.innerHTML = content;
264
- }
265
- if (prepend) {
266
- document.head.prepend(script);
267
- }
268
- else {
269
- document.head.appendChild(script);
270
- }
271
- }
272
113
  /**
273
114
  * Read a static HTML file, or return an error response if the file can't be read.
274
115
  */
275
- async function readStaticHtml(renderScriptPath) {
116
+ async function readStaticHtml(params) {
117
+ const { renderScriptPath, req } = params;
276
118
  try {
277
119
  return (await fsPromises.readFile(renderScriptPath, 'utf8')) || '';
278
120
  }
279
121
  catch (e) {
280
- const message = `Error reading HTML file at "${renderScriptPath}":\n${e.stack || e}`;
281
- console.error(message);
282
- return getHtmlErrorResponse(message);
122
+ return getErrorResponse({
123
+ req,
124
+ message: `Error reading HTML file at "${renderScriptPath}":\n${e.stack || e}`,
125
+ });
283
126
  }
284
127
  }
285
128
  //# sourceMappingURL=renderRoute.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"renderRoute.js","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAiB,MAAM,WAAW,CAAC;AAClD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,cAAc,MAAM,iDAAiD,CAAC;AAC7E,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAoC,MAAM,0BAA0B,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,OAAoC;IAEpC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,EAAE,QAAQ,EAAE,IAAI,GAAG,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IACpE,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QACrB,OAAO;IACT,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,CAAC,GAAG,GAAG,GAAG,CAAC;IACnB,CAAC;SAAM,IAAI,OAAO,EAAE,CAAC;QACnB,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC;IAC7B,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IACpC,CAAC;AACH,CAAC;AAED;;GAEG;AACH,KAAK,UAAU,cAAc,CAAC,gBAAwB;IACpD,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,UAAU,CAAC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACrE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,OAAO,GAAG,+BAA+B,gBAAgB,OAAQ,CAAW,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACvB,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import type {\n RenderFunctionOptions,\n RenderFunctionResult,\n ExpandedRenderFunctionResult,\n RenderedRoute,\n Request,\n} from '@ms-cloudpack/common-types';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport fsPromises from 'fs/promises';\nimport { Window, type Document } from 'happy-dom';\nimport path from 'path';\nimport { getDefaultHtmlResponse } from './getDefaultHtmlResponse.js';\nimport { getHtmlErrorResponse } from './getHtmlErrorResponse.js';\nimport HTMLSerializer from 'happy-dom/lib/html-serializer/HTMLSerializer.js';\nimport {\n javascriptExtensions,\n sourceExtensions,\n sourceToIntermediatePath,\n typescriptExtensions,\n} from '@ms-cloudpack/path-utilities';\nimport { ensurePackageBundled, type EnsurePackageBundledContext } from '@ms-cloudpack/api-server';\nimport { bulletedList } from '@ms-cloudpack/task-reporter';\nimport { environmentInfo } from '@ms-cloudpack/environment';\nimport { renderCustomScript } from './renderCustomScript.js';\n\n/**\n * Get the response for the given route. If the route has a custom render script, use that.\n * Returns an error response if the file referenced by the script doesn't exist or throws an error.\n */\nexport async function renderRoute(\n options: RenderFunctionOptions,\n context: EnsurePackageBundledContext,\n): Promise<ExpandedRenderFunctionResult | null> {\n const { route, session } = options;\n const { appPath } = session.config;\n\n // Get the script to render (if any). Prefer serverEntry if provided.\n // eslint-disable-next-line etc/no-deprecated\n let renderScriptPath = route.renderScript && path.resolve(appPath, route.renderScript);\n\n if (route.serverEntry) {\n const serverEntryExt = path.extname(route.serverEntry.sourcePath).toLowerCase();\n if (sourceExtensions.includes(serverEntryExt)) {\n // Server entry is a source file, so bundle it\n const serverEntryResult = await bundleServerEntry(\n { ...options, serverEntryPath: route.serverEntry.sourcePath },\n context,\n );\n if (typeof serverEntryResult === 'string') {\n renderScriptPath = serverEntryResult;\n } else {\n // This means there was an error\n return serverEntryResult;\n }\n } else {\n // HTML or something, so use it as-is\n renderScriptPath = path.resolve(appPath, route.serverEntry.sourcePath);\n }\n }\n\n // Get an initial result from either the renderScript/serverEntry or default handler.\n let rawResult: RenderFunctionResult;\n if (renderScriptPath) {\n const scriptExt = path.extname(renderScriptPath).toLowerCase();\n if (scriptExt === '.html' || scriptExt === '.htm') {\n // HTML file: just read it\n rawResult = await readStaticHtml(renderScriptPath);\n } else if (javascriptExtensions.includes(scriptExt)) {\n // JS file: run its function\n rawResult = await renderCustomScript({ ...options, renderScriptPath });\n } else {\n // Other file type: error. Technically we could just serve it as-is following the non-HTML\n // content type logic, but this probably indicates there's been a misunderstanding and we\n // should direct them to use a more appropriate type of route instead.\n let message = 'is not a supported file type. ';\n if (typescriptExtensions.includes(scriptExt)) {\n message += 'Use `serverEntry` for TS files.';\n } else {\n message +=\n `Supported file types are ${route.serverEntry ? 'TS, JS, or HTML' : 'JS or HTML (use `serverEntry` for TS)'}. ` +\n 'If you want to serve a static non-HTML file, use a route with `staticPath`, or a `serverEntry` ' +\n 'which returns the file content for advanced scenarios.';\n }\n return makeErrorResponse({\n message,\n route,\n req: options.req,\n scriptPath: renderScriptPath,\n });\n }\n } else {\n rawResult = await getDefaultHtmlResponse(options);\n }\n\n if (rawResult === null) {\n // This means the custom renderScript fully handled the request.\n return null;\n }\n\n if (rawResult === undefined) {\n return makeErrorResponse({\n message:\n `returned undefined. If the script fully handled the request (sent a response), ` +\n `return null instead. Otherwise ensure that the function returns the content to be rendered.`,\n route,\n req: options.req,\n scriptPath: renderScriptPath,\n });\n }\n\n const result: ExpandedRenderFunctionResult = {\n contentType: 'text/html',\n statusCode: 200,\n ...(typeof rawResult === 'string' ? { content: rawResult } : rawResult),\n };\n\n // If it's HTML and a success statusCode, inject the import map and appropriate scripts.\n if (result.statusCode === 200 && isHtmlType(result.contentType)) {\n if (isHtmlAcceptable(options)) {\n // Inject the import map and scripts.\n await injectScripts(options, result);\n } else {\n // It appears we're accidentally returning HTML when a different file type was requested.\n // This could happen for overly broad route matches such as '*', or if no routes are configured.\n return makeErrorResponse({\n message:\n 'returned HTML, but this appears to be a non-HTML request. This is likely due to an ' +\n 'overly broad match or other misconfiguration of server.routes in the cloudpack config.',\n route,\n scriptPath: renderScriptPath,\n req: options.req,\n });\n }\n }\n\n return result;\n}\n\nasync function bundleServerEntry(\n options: Pick<RenderFunctionOptions, 'definition' | 'route' | 'req'> & {\n /** Relative serverEntry source path from the route */\n serverEntryPath: string;\n },\n context: EnsurePackageBundledContext,\n): Promise<string | ExpandedRenderFunctionResult> {\n const { definition, route, req, serverEntryPath } = options;\n const { name, version } = definition;\n\n // targetEnvironment: node currently bundles all node or agnostic entries, and implicitly does\n // production bundling. This seems like it could get expensive, but it's probably okay because\n // createPackageSettingsTransform overwrites the package's actual exports with the ones generated\n // from routes, and those will always have environment conditions.\n const response = await ensurePackageBundled(\n {\n name,\n version,\n targetEnvironment: 'node',\n // TODO: This will only watch for changes in the given package, not dependencies.\n // File watching is disabled in production mode for performance.\n shouldWatch: !environmentInfo.isJest && context.session.config.mode !== 'production',\n // Irrelevant with implicit production bundling\n enqueueDependencies: false,\n },\n context,\n );\n const { errors, outputPath = '', outputFiles = [] } = response.result;\n\n if (errors?.length) {\n return makeErrorResponse({\n message: `failed to bundle: ${JSON.stringify(response.result.errors, null, 2)}`,\n route,\n req,\n scriptPath: serverEntryPath,\n });\n }\n\n let serverEntryOutput = outputFiles.find((f) => f.entryPoint === serverEntryPath)?.outputPath;\n if (!serverEntryOutput) {\n // No literal match, so try the intermediate path without extension.\n const intermediateServerEntryPath = sourceToIntermediatePath(serverEntryPath).replace(/\\.\\w+$/, '');\n serverEntryOutput =\n outputFiles.find((f) => f.entryPoint === serverEntryPath)?.outputPath ||\n outputFiles.find((f) => f.outputPath.replace(/\\.\\w+$/, '') === intermediateServerEntryPath)?.outputPath;\n }\n\n if (!serverEntryOutput) {\n return makeErrorResponse({\n message: `did not produce a bundle output file corresponding to the serverEntry script (${serverEntryPath}). Produced files:\\n${\n outputFiles.length\n ? bulletedList(outputFiles.map((f) => `${f.outputPath} (entry: ${f.entryPoint || 'unknown'})`))\n : 'none'\n }`,\n route,\n req: options.req,\n scriptPath: serverEntryPath,\n });\n }\n\n // Translate relative-to-output path into an absolute path.\n return path.resolve(outputPath, serverEntryOutput);\n}\n\n/**\n * Fill in details of the message, log to console.error, and return an error response.\n * `Route ${route.match} with (renderScript|serverEntry) \"${scriptPath}\" ${message}`\n */\nfunction makeErrorResponse(params: {\n message: string;\n route: RenderedRoute;\n scriptPath: string | undefined;\n req: Request;\n}): ExpandedRenderFunctionResult {\n const { message, route, scriptPath, req } = params;\n const scriptType = route.serverEntry ? 'serverEntry' : 'renderScript';\n const renderer = scriptPath ? `${scriptType} \"${scriptPath}\"` : 'the default renderer';\n const content = `Route ${JSON.stringify(route.match)} with ${renderer} ${message}`;\n console.error(`App server: request ${req.url} - ${content}`);\n\n return { statusCode: 500, contentType: 'text/plain', content };\n}\n\nfunction isHtmlAcceptable(options: Pick<RenderFunctionOptions, 'req' | 'baseUrl'>): boolean {\n const { req, baseUrl } = options;\n // Get the request path and extension (the URL.pathname conversion gets rid of any query or hash)\n const requestPath = makeUrl(req.url, baseUrl).pathname;\n const requestExt = path.extname(requestPath);\n // Determine whether HTML is (probably) an acceptable response type (can be refined later if needed).\n // In theory we should be able to use req.accepts() but not all requests set the accept header.\n return (!requestExt || requestExt.startsWith('.htm')) && !req.xhr && isHtmlType(req.headers.accept || '*/*');\n}\n\nfunction isHtmlType(acceptOrContentType: string): boolean {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n return acceptOrContentType\n .split(',')\n .map((s) => s.split(';')[0].trim())\n .some((mime) => mime === '*/*' || /xml|x?html/i.test(mime) || /^(text|application)\\/\\*$/.test(mime));\n}\n\n/**\n * Modify the HTML response by injecting the import map, inline scripts, and entry/overlay scripts.\n *\n * Note that this just logs an error rather than returning an error response if something fails, for now.\n */\nasync function injectScripts(options: RenderFunctionOptions, result: ExpandedRenderFunctionResult): Promise<void> {\n const { route, overlayScript, entryScripts, inlineScripts, importMap, baseUrl } = options;\n const window = new Window({\n url: baseUrl,\n settings: {\n disableJavaScriptFileLoading: true,\n disableJavaScriptEvaluation: true,\n disableCSSFileLoading: true,\n disableIframePageLoading: true,\n },\n });\n try {\n // TODO: happy-dom is overkill for what we're doing here--a full browser-like environment isn't\n // needed to just parse and modify the HTML. If it becomes a perf concern (less likely since\n // HTML page rendering is probably just done once per page load), we could switch to\n // a pure parser like parse5 or htmlparser2.\n window.document.write(result.content);\n } catch (e) {\n // Trying to write a test for the above, it seemed very permissive, but catch just in case\n console.error(\n `Error parsing html response for rendering route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`,\n );\n return;\n }\n\n try {\n const document = window.document;\n\n if (entryScripts || overlayScript) {\n // Inject the import map at the top of the head, in case other scripts use it\n addScript({ document, type: 'importmap', prepend: true, content: JSON.stringify(importMap, null, 2) });\n }\n\n if (inlineScripts) {\n for (const inlineScript of inlineScripts) {\n addScript({ document, content: inlineScript });\n }\n }\n\n // inject the overlay and entry scripts\n addScript({ document, url: overlayScript });\n\n if (entryScripts) {\n for (const entryScript of entryScripts) {\n addScript({ document, url: entryScript });\n }\n }\n\n const serializer = new HTMLSerializer();\n result.content = serializer.serializeToString(document);\n await window.happyDOM.close();\n } catch (e) {\n console.error(`Error injecting scripts for route \"${JSON.stringify(route.match)}\":\\n${(e as Error).stack || e}`);\n }\n}\n\n/**\n * Helper function to add a script to the document.\n * No-op if neither `url` nor `content` is provided.\n */\nfunction addScript(params: {\n document: Document;\n type?: string;\n prepend?: boolean;\n url?: string;\n content?: string;\n}): void {\n const { document, type = 'module', prepend, url, content } = params;\n if (!url && !content) {\n return;\n }\n\n const script = document.createElement('script');\n script.type = type;\n if (url) {\n script.src = url;\n } else if (content) {\n script.innerHTML = content;\n }\n\n if (prepend) {\n document.head.prepend(script);\n } else {\n document.head.appendChild(script);\n }\n}\n\n/**\n * Read a static HTML file, or return an error response if the file can't be read.\n */\nasync function readStaticHtml(renderScriptPath: string): Promise<RenderFunctionResult> {\n try {\n return (await fsPromises.readFile(renderScriptPath, 'utf8')) || '';\n } catch (e) {\n const message = `Error reading HTML file at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`;\n console.error(message);\n return getHtmlErrorResponse(message);\n }\n}\n"]}
1
+ {"version":3,"file":"renderRoute.js","sourceRoot":"","sources":["../../src/renderRoute/renderRoute.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACvF,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,OAAoC;IAEpC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACnC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAEnC,qEAAqE;IACrE,6CAA6C;IAC7C,IAAI,gBAAgB,GAAG,KAAK,CAAC,YAAY,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC;IAEvF,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QACtB,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,WAAW,EAAE,CAAC;QAChF,IAAI,gBAAgB,CAAC,QAAQ,CAAC,cAAc,CAA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O,4BAA4B,CAAC;gBAClC,OAAO,EACL,qFAAqF;oBACrF,wFAAwF;gBAC1F,KAAK;gBACL,UAAU,EAAE,gBAAgB;gBAC5B,GAAG,EAAE,OAAO,CAAC,GAAG;aACjB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,KAAK,UAAU,cAAc,CAC3B,MAEC;IAED,MAAM,EAAE,gBAAgB,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC;IACzC,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,UAAU,CAAC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACrE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,gBAAgB,CAAC;YACtB,GAAG;YACH,OAAO,EAAE,+BAA+B,gBAAgB,OAAQ,CAAW,CAAC,KAAK,IAAI,CAAC,EAAE;SACzF,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { type EnsurePackageBundledContext } from '@ms-cloudpack/api-server';\nimport type {\n ExpandedRenderFunctionResult,\n RenderFunctionOptions,\n RenderFunctionResult,\n} from '@ms-cloudpack/common-types';\nimport { javascriptExtensions, sourceExtensions, typescriptExtensions } from '@ms-cloudpack/path-utilities';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { getDefaultHtmlResponse } from './getDefaultHtmlResponse.js';\nimport { getCustomRenderErrorResponse, getErrorResponse } from './getErrorResponse.js';\nimport { injectScripts } from './injectScripts.js';\nimport { isHtmlAcceptable, isHtmlType } from './isHtmlAcceptable.js';\nimport { bundleServerEntry } from './ssr/bundleServerEntry.js';\nimport { renderCustomScript } from './ssr/renderCustomScript.js';\n\n/**\n * Get the response for the given route. If the route has a custom render script, use that.\n * Returns an error response if the file referenced by the script doesn't exist or throws an error.\n */\nexport async function renderRoute(\n options: RenderFunctionOptions,\n context: EnsurePackageBundledContext,\n): Promise<ExpandedRenderFunctionResult | null> {\n const { route, session } = options;\n const { appPath } = session.config;\n\n // Get the script to render (if any). Prefer serverEntry if provided.\n // eslint-disable-next-line etc/no-deprecated\n let renderScriptPath = route.renderScript && path.resolve(appPath, route.renderScript);\n\n if (route.serverEntry) {\n const serverEntryExt = path.extname(route.serverEntry.sourcePath).toLowerCase();\n if (sourceExtensions.includes(serverEntryExt)) {\n // Server entry is a source file, so bundle it\n const serverEntryResult = await bundleServerEntry(\n { ...options, serverEntryPath: route.serverEntry.sourcePath },\n context,\n );\n if (typeof serverEntryResult === 'string') {\n renderScriptPath = serverEntryResult;\n } else {\n // This means there was an error\n return serverEntryResult;\n }\n } else {\n // HTML or something, so use it as-is\n renderScriptPath = path.resolve(appPath, route.serverEntry.sourcePath);\n }\n }\n\n // Get an initial result from either the renderScript/serverEntry or default handler.\n let rawResult: RenderFunctionResult;\n if (renderScriptPath) {\n const scriptExt = path.extname(renderScriptPath).toLowerCase();\n if (scriptExt === '.html' || scriptExt === '.htm') {\n // HTML file: just read it\n rawResult = await readStaticHtml({ renderScriptPath, req: options.req });\n } else if (javascriptExtensions.includes(scriptExt)) {\n // JS file: run its function\n rawResult = await renderCustomScript({ ...options, renderScriptPath });\n } else {\n // Other file type: error. Technically we could just serve it as-is following the non-HTML\n // content type logic, but this probably indicates there's been a misunderstanding and we\n // should direct them to use a more appropriate type of route instead.\n let message = 'is not a supported file type. ';\n if (typescriptExtensions.includes(scriptExt)) {\n message += 'Use `serverEntry` for TS files.';\n } else {\n message +=\n `Supported file types are ${route.serverEntry ? 'TS, JS, or HTML' : 'JS or HTML (use `serverEntry` for TS)'}. ` +\n 'If you want to serve a static non-HTML file, use a route with `staticPath`, or a `serverEntry` ' +\n 'which returns the file content for advanced scenarios.';\n }\n return getCustomRenderErrorResponse({\n message,\n route,\n req: options.req,\n scriptPath: renderScriptPath,\n });\n }\n } else {\n rawResult = await getDefaultHtmlResponse(options);\n }\n\n if (rawResult === null) {\n // This means the custom renderScript fully handled the request.\n return null;\n }\n\n if (rawResult === undefined) {\n return getCustomRenderErrorResponse({\n message:\n `returned undefined. If the script fully handled the request (sent a response), ` +\n `return null instead. Otherwise ensure that the function returns the content to be rendered.`,\n route,\n req: options.req,\n scriptPath: renderScriptPath,\n });\n }\n\n const result: ExpandedRenderFunctionResult = {\n contentType: 'text/html',\n statusCode: 200,\n ...(typeof rawResult === 'string' ? { content: rawResult } : rawResult),\n };\n\n // If it's HTML and a success statusCode, inject the import map and appropriate scripts.\n if (result.statusCode === 200 && isHtmlType(result.contentType)) {\n if (isHtmlAcceptable(options.req)) {\n // Inject the import map and scripts.\n await injectScripts(options, result);\n } else {\n // It appears we're accidentally returning HTML when a different file type was requested.\n // This could happen for overly broad route matches such as '*', or if no routes are configured.\n return getCustomRenderErrorResponse({\n message:\n 'returned HTML, but this appears to be a non-HTML request. This is likely due to an ' +\n 'overly broad match or other misconfiguration of server.routes in the cloudpack config.',\n route,\n scriptPath: renderScriptPath,\n req: options.req,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Read a static HTML file, or return an error response if the file can't be read.\n */\nasync function readStaticHtml(\n params: Pick<RenderFunctionOptions, 'req'> & {\n renderScriptPath: string;\n },\n): Promise<RenderFunctionResult> {\n const { renderScriptPath, req } = params;\n try {\n return (await fsPromises.readFile(renderScriptPath, 'utf8')) || '';\n } catch (e) {\n return getErrorResponse({\n req,\n message: `Error reading HTML file at \"${renderScriptPath}\":\\n${(e as Error).stack || e}`,\n });\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import { type EnsurePackageBundledContext } from '@ms-cloudpack/api-server';
2
+ import type { RenderFunctionOptions, ExpandedRenderFunctionResult } from '@ms-cloudpack/common-types';
3
+ export declare function bundleServerEntry(options: Pick<RenderFunctionOptions, 'definition' | 'route' | 'req'> & {
4
+ /** Relative serverEntry source path from the route */
5
+ serverEntryPath: string;
6
+ }, context: EnsurePackageBundledContext): Promise<string | ExpandedRenderFunctionResult>;
7
+ //# sourceMappingURL=bundleServerEntry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleServerEntry.d.ts","sourceRoot":"","sources":["../../../src/renderRoute/ssr/bundleServerEntry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,2BAA2B,EAAwB,MAAM,0BAA0B,CAAC;AAClG,OAAO,KAAK,EAAE,qBAAqB,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAOtG,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,IAAI,CAAC,qBAAqB,EAAE,YAAY,GAAG,OAAO,GAAG,KAAK,CAAC,GAAG;IACrE,sDAAsD;IACtD,eAAe,EAAE,MAAM,CAAC;CACzB,EACD,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,MAAM,GAAG,4BAA4B,CAAC,CAwDhD"}