@ms-cloudpack/app-server 0.19.3 → 0.20.0

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.
@@ -125,9 +125,8 @@ async function bundleServerEntry(options, context) {
125
125
  version,
126
126
  targetEnvironment: 'node',
127
127
  // TODO: This will only watch for changes in the given package, not dependencies.
128
- // Since we implicitly use production mode for node bundles, this means changes to
129
- // dependencies will be missed.
130
- shouldWatch: !environmentInfo.isJest,
128
+ // File watching is disabled in production mode for performance.
129
+ shouldWatch: !environmentInfo.isJest && context.session.config.mode !== 'production',
131
130
  // Irrelevant with implicit production bundling
132
131
  enqueueDependencies: false,
133
132
  }, context);
@@ -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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,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 // Since we implicitly use production mode for node bundles, this means changes to\n // dependencies will be missed.\n shouldWatch: !environmentInfo.isJest,\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":"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,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,CAA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AAI,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/app-server",
3
- "version": "0.19.3",
3
+ "version": "0.20.0",
4
4
  "description": "An implementation of the App server for Cloudpack.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,15 +14,15 @@
14
14
  }
15
15
  },
16
16
  "dependencies": {
17
- "@ms-cloudpack/api-server": "^0.64.6",
18
- "@ms-cloudpack/bundle-server": "^0.7.21",
19
- "@ms-cloudpack/common-types": "^0.26.2",
20
- "@ms-cloudpack/create-express-app": "^1.10.41",
17
+ "@ms-cloudpack/api-server": "^0.64.8",
18
+ "@ms-cloudpack/bundle-server": "^0.8.0",
19
+ "@ms-cloudpack/common-types": "^0.26.4",
20
+ "@ms-cloudpack/create-express-app": "^1.10.43",
21
21
  "@ms-cloudpack/environment": "^0.1.1",
22
- "@ms-cloudpack/import-map": "^0.10.35",
23
- "@ms-cloudpack/inline-scripts": "^0.2.20",
22
+ "@ms-cloudpack/import-map": "^0.10.37",
23
+ "@ms-cloudpack/inline-scripts": "^0.2.22",
24
24
  "@ms-cloudpack/path-string-parsing": "^1.2.7",
25
- "@ms-cloudpack/path-utilities": "^3.1.12",
25
+ "@ms-cloudpack/path-utilities": "^3.1.14",
26
26
  "@ms-cloudpack/task-reporter": "^0.17.2",
27
27
  "@ms-cloudpack/worker-pool": "^0.4.1",
28
28
  "happy-dom": "^18.0.0",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "devDependencies": {
32
32
  "@ms-cloudpack/common-types-browser": "^0.6.2",
33
- "@ms-cloudpack/config": "^0.37.0",
33
+ "@ms-cloudpack/config": "^0.37.2",
34
34
  "@ms-cloudpack/eslint-plugin-internal": "^0.0.1",
35
35
  "@ms-cloudpack/scripts": "^0.0.1",
36
36
  "@ms-cloudpack/test-utilities": "^0.5.0"