kempo-server 3.0.4 → 3.0.5
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.
- package/dist/router.js +1 -1
- package/package.json +1 -1
- package/src/router.js +60 -21
- package/tests/router-custom-route-ssr.node-test.js +189 -0
package/dist/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import path from"path";import{readFile,stat,readdir}from"fs/promises";import{pathToFileURL}from"url";import defaultConfig from"./defaultConfig.js";import getFiles from"./getFiles.js";import findFile from"./findFile.js";import serveFile from"./serveFile.js";import MiddlewareRunner from"./middlewareRunner.js";import ModuleCache from"./moduleCache.js";import createRequestWrapper,{readRawBody,parseBody}from"./requestWrapper.js";import createResponseWrapper from"./responseWrapper.js";import{corsMiddleware,compressionMiddleware,rateLimitMiddleware,securityMiddleware,loggingMiddleware}from"./builtinMiddleware.js";import{onRescan}from"./rescan.js";import{renderDir}from"./templating/index.js";export default async(flags,log)=>{log("Initializing router",3);const rootPath=path.isAbsolute(flags.root)?flags.root:path.join(process.cwd(),flags.root);log(`Root path: ${rootPath}`,3);let config=defaultConfig;try{const configFileName=flags.config||".config.js",configPath=path.isAbsolute(configFileName)?configFileName:path.join(rootPath,configFileName);if(log(`Config file name: ${configFileName}`,3),log(`Config path: ${configPath}`,3),path.isAbsolute(configFileName))log("Config file name is absolute, skipping validation",4);else{const relativeConfigPath=path.relative(rootPath,configPath);if(log(`Relative config path: ${relativeConfigPath}`,4),log(`Starts with '..': ${relativeConfigPath.startsWith("..")}`,4),relativeConfigPath.startsWith("..")||path.isAbsolute(relativeConfigPath))throw log("Validation failed - throwing error",4),new Error(`Config file must be within the server root directory. Config path: ${configPath}, Root path: ${rootPath}`);log("Validation passed",4)}let userConfig;if(log(`Loading config from: ${configPath}`,3),configPath.endsWith(".js")){const configUrl=pathToFileURL(configPath).href+`?t=${Date.now()}`;userConfig=(await import(configUrl)).default}else{const configContent=await readFile(configPath,"utf8");userConfig=JSON.parse(configContent)}if(!userConfig)throw new Error("Config file is empty or has no default export");config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded and merged with defaults",3)}catch(e){if(e.message.includes("Config file must be within the server root directory"))throw e;const configFileName=flags.config||".config.js";if(configFileName.endsWith(".js"))try{const jsonFallback=configFileName.replace(/\.js$/,".json"),jsonPath=path.isAbsolute(jsonFallback)?jsonFallback:path.join(rootPath,jsonFallback);log(`Trying JSON fallback: ${jsonPath}`,3);const configContent=await readFile(jsonPath,"utf8"),userConfig=JSON.parse(configContent);config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded from JSON fallback",3)}catch(e2){log("Using default config (no config file found)",3)}else log("Using default config (no config file found)",3)}const dis=new Set(config.disallowedRegex);if(dis.add("^/\\..*"),dis.add("\\.config\\.js$"),dis.add("\\.config\\.json$"),dis.add("\\.git/"),config.disallowedRegex=[...dis],log(`Config loaded with ${config.disallowedRegex.length} disallowed patterns`,3),config.templating.preRender){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,count=await renderDir(rootPath,rootPath,globals,state,maxFragmentDepth);log(`Pre-rendered ${count} page(s)`,2)}let files=await getFiles(rootPath,config,log);log(`Initial scan found ${files.length} files`,2),onRescan(async done=>{try{files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2),done(null,files.length)}catch(error){log(`Rescan failed: ${error.message}`,1),done(error)}});const middlewareRunner=new MiddlewareRunner;if(config.middleware?.cors?.enabled&&(middlewareRunner.use(corsMiddleware(config.middleware.cors)),log("CORS middleware enabled",3)),config.middleware?.compression?.enabled&&(middlewareRunner.use(compressionMiddleware(config.middleware.compression)),log("Compression middleware enabled",3)),config.middleware?.rateLimit?.enabled&&(middlewareRunner.use(rateLimitMiddleware(config.middleware.rateLimit)),log("Rate limit middleware enabled",3)),config.middleware?.security?.enabled&&(middlewareRunner.use(securityMiddleware(config.middleware.security)),log("Security middleware enabled",3)),config.middleware?.logging?.enabled&&(middlewareRunner.use(loggingMiddleware(config.middleware.logging,log)),log("Logging middleware enabled",3)),config.middleware?.custom&&config.middleware.custom.length>0){log(`Loading ${config.middleware.custom.length} custom middleware files`,3);for(const middlewarePath of config.middleware.custom)try{const resolvedPath=path.isAbsolute(middlewarePath)?middlewarePath:path.resolve(rootPath,middlewarePath),middlewareUrl=pathToFileURL(resolvedPath).href+`?t=${Date.now()}`,customMiddleware=(await import(middlewareUrl)).default;"function"==typeof customMiddleware?(middlewareRunner.use(customMiddleware(config.middleware)),log(`Custom middleware loaded: ${middlewarePath}`,3)):log(`Custom middleware error: ${middlewarePath} does not export a default function`,1)}catch(error){log(`Custom middleware error for ${middlewarePath}: ${error.message}`,1)}}let moduleCache=null;config.cache?.enabled&&(moduleCache=new ModuleCache(config.cache),log(`Module cache initialized: ${config.cache.maxSize} max modules, ${config.cache.maxMemoryMB}MB limit, ${config.cache.ttlMs}ms TTL`,2));const customRoutes=new Map,wildcardRoutes=new Map;if(config.customRoutes&&Object.keys(config.customRoutes).length>0){log(`Processing ${Object.keys(config.customRoutes).length} custom routes`,3);for(const[urlPath,filePath]of Object.entries(config.customRoutes))if(urlPath.includes("*")){const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);wildcardRoutes.set(urlPath,resolvedPath),log(`Wildcard route mapped: ${urlPath} -> ${resolvedPath}`,3)}else{const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);customRoutes.set(urlPath,resolvedPath),log(`Custom route mapped: ${urlPath} -> ${resolvedPath}`,3)}}const matchWildcardRoute=(requestPath,pattern)=>{const regexPattern=(pattern.startsWith("/")?pattern:"/"+pattern).replace(/\*\*/g,"(.+)").replace(/\*/g,"([^/]+)");return new RegExp(`^${regexPattern}$`).exec(requestPath)},serveStaticCustomFile=async(filePath,res)=>{const fileExtension=path.extname(filePath).toLowerCase().slice(1),mimeConfig=config.allowedMimes[fileExtension];let mimeType,encoding;"string"==typeof mimeConfig?(mimeType=mimeConfig,encoding=mimeType.startsWith("text/")?"utf8":void 0):(mimeType=mimeConfig?.mime||"application/octet-stream",encoding="utf8"===mimeConfig?.encoding?"utf8":void 0);const fileContent=await readFile(filePath,encoding);log(`Serving custom file as ${mimeType} (${fileContent.length} bytes)`,2);const contentType="utf8"===encoding&&mimeType.startsWith("text/")?`${mimeType}; charset=utf-8`:mimeType;res.writeHead(200,{"Content-Type":contentType}),res.end(fileContent)},executeRouteModule=async(filePath,req,res,params={})=>{let module;if(moduleCache&&config.cache?.enabled){const fileStats=await stat(filePath);if(module=moduleCache.get(filePath,fileStats),!module){const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl);const estimatedSizeKB=fileStats.size/1024;moduleCache.set(filePath,module,fileStats,estimatedSizeKB)}}else{const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl)}if("function"!=typeof module.default)return log(`Route file does not export a function: ${filePath}`,0),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Route file does not export a function");const enhancedReq=createRequestWrapper(req,params),enhancedRes=createResponseWrapper(res),rawBody=await readRawBody(req);enhancedReq._rawBody=rawBody,enhancedReq.body=parseBody(rawBody,req.headers["content-type"]),moduleCache&&(enhancedReq._kempoCache=moduleCache),await module.default(enhancedReq,enhancedRes)},walkDynamic=async(base,segments)=>{if(0===segments.length)return{filePath:base,params:{}};const[head,...rest]=segments;let entries;try{entries=await readdir(base,{withFileTypes:!0})}catch{return null}for(const entry of entries)if(entry.name===head)if(entry.isDirectory()){const result=await walkDynamic(path.join(base,head),rest);if(result)return result}else if(entry.isFile()&&0===rest.length)return{filePath:path.join(base,head),params:{}};for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("[")||!entry.name.endsWith("]"))continue;const paramName=entry.name.slice(1,-1),result=await walkDynamic(path.join(base,entry.name),rest);if(result)return{filePath:result.filePath,params:{[paramName]:head,...result.params}}}return null},serveResolvedPath=async(filePath,fileStat,params,req,res)=>{if(fileStat.isDirectory()){const methodUpper=req.method.toUpperCase(),candidates=[`${methodUpper}.js`,`${methodUpper}.html`,"index.js","index.html","index.htm"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}return config.routeFiles.includes(candidate)?(log(`Executing route file: ${candidatePath}`,2),await executeRouteModule(candidatePath,req,res,params),!0):(log(`Serving index file: ${candidatePath}`,2),await serveStaticCustomFile(candidatePath,res),!0)}return null}const fileName=path.basename(filePath);return config.routeFiles.includes(fileName)?(log(`Executing route file: ${filePath}`,2),await executeRouteModule(filePath,req,res,params),!0):(await serveStaticCustomFile(filePath,res),!0)},serveCustomRoutePath=async(resolvedFilePath,req,res)=>{let fileStat;try{return fileStat=await stat(resolvedFilePath),await serveResolvedPath(resolvedFilePath,fileStat,{},req,res)}catch(e){if("ENOENT"!==e.code)throw e}let current=resolvedFilePath;const remaining=[];for(;current!==path.dirname(current);){remaining.unshift(path.basename(current)),current=path.dirname(current);try{if(!(await stat(current)).isDirectory())break;const result=await walkDynamic(current,remaining);if(!result)return null;const resolvedStat=await stat(result.filePath);return await serveResolvedPath(result.filePath,resolvedStat,result.params,req,res)}catch(e2){if("ENOENT"!==e2.code)throw e2}}return null},rescanAttempts=new Map,dynamicNoRescanPaths=new Set,shouldSkipRescan=requestPath=>config.noRescanPaths.some(pattern=>new RegExp(pattern).test(requestPath))?(log(`Skipping rescan for configured pattern: ${requestPath}`,3),!0):!!dynamicNoRescanPaths.has(requestPath)&&(log(`Skipping rescan for dynamically blacklisted path: ${requestPath}`,3),!0),handler=async(req,res)=>{if(parseInt(req.headers["content-length"]||"0",10)>config.maxBodySize)return res.writeHead(413,{"Content-Type":"text/plain"}),void res.end("Payload Too Large");const rawBody=await new Promise((resolve,reject)=>{if(["GET","HEAD"].includes(req.method)&&!req.headers["content-length"])return resolve("");let body="",size=0;req.on("data",chunk=>{if(size+=chunk.length,size>config.maxBodySize)return req.destroy(),void reject(new Error("Payload Too Large"));body+=chunk.toString()}),req.on("end",()=>resolve(body)),req.on("error",reject)}).catch(err=>{if("Payload Too Large"===err.message)return res.writeHead(413,{"Content-Type":"text/plain"}),res.end("Payload Too Large"),null;throw err});if(null===rawBody)return;req._bufferedBody=rawBody;const enhancedRequest=createRequestWrapper(req,{}),enhancedResponse=createResponseWrapper(res);enhancedRequest._rawBody=rawBody,enhancedRequest.body=parseBody(rawBody,req.headers["content-type"]),await middlewareRunner.run(enhancedRequest,enhancedResponse,async()=>{const requestPath=enhancedRequest.url.split("?")[0];log(`${enhancedRequest.method} ${requestPath}`,4),log(`customRoutes keys: ${Array.from(customRoutes.keys()).join(", ")}`,4);const normalizePath=p=>{try{let np=decodeURIComponent(p);return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}catch(e){log(`Warning: Failed to decode URI component "${p}": ${e.message}`,1);let np=p;return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}},normalizedRequestPath=normalizePath(requestPath);log(`Normalized requestPath: ${normalizedRequestPath}`,4);let matchedKey=null;for(const key of customRoutes.keys())if(normalizePath(key)===normalizedRequestPath){matchedKey=key;break}if(matchedKey){const customFilePath=customRoutes.get(matchedKey);log(`Serving custom route: ${normalizedRequestPath} -> ${customFilePath}`,3);try{if(await serveCustomRoutePath(customFilePath,req,res))return;return log(`Custom route path not found: ${customFilePath}`,1),res.writeHead(404,{"Content-Type":"text/plain"}),void res.end("Custom route file not found")}catch(error){return log(`Error serving custom route ${normalizedRequestPath}: ${error.message}`,1),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Internal Server Error")}}const wildcardMatch=(requestPath=>{for(const[pattern,filePath]of wildcardRoutes){const matches=matchWildcardRoute(requestPath,pattern);if(matches)return{filePath:filePath,matches:matches}}return null})(requestPath);if(wildcardMatch){const resolvedFilePath=((filePath,matches)=>{let resolvedPath=filePath,matchIndex=1;for(;resolvedPath.includes("**")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("**",matches[matchIndex]),matchIndex++;for(;resolvedPath.includes("*")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("*",matches[matchIndex]),matchIndex++;return path.isAbsolute(resolvedPath)?resolvedPath:path.resolve(rootPath,resolvedPath)})(wildcardMatch.filePath,wildcardMatch.matches);log(`Serving wildcard route: ${requestPath} -> ${resolvedFilePath}`,3);try{if(await serveCustomRoutePath(resolvedFilePath,req,res))return;log(`Wildcard route path not found: ${requestPath}`,2)}catch(error){return log(`Error serving wildcard route ${requestPath}: ${error.message}`,1),enhancedResponse.writeHead(500,{"Content-Type":"text/plain"}),void enhancedResponse.end("Internal Server Error")}}const served=await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache);if(!served&&config.maxRescanAttempts>0&&!shouldSkipRescan(requestPath)){log("File not found, rescanning directory...",1),files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2);await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache)?rescanAttempts.delete(requestPath):((requestPath=>{const newAttempts=(rescanAttempts.get(requestPath)||0)+1;rescanAttempts.set(requestPath,newAttempts),newAttempts>config.maxRescanAttempts&&(dynamicNoRescanPaths.add(requestPath),log(`Path ${requestPath} added to dynamic blacklist after ${newAttempts} failed attempts`,1)),log(`Rescan attempt ${newAttempts}/${config.maxRescanAttempts} for: ${requestPath}`,3)})(requestPath),log(`404 - File not found after rescan: ${requestPath}`,1),enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found"))}else served||(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found"))})};return handler.moduleCache=moduleCache,handler.getStats=()=>moduleCache?.getStats()||null,handler.logCacheStats=()=>moduleCache?.logStats(log),handler.clearCache=()=>moduleCache?.clear(),handler};
|
|
1
|
+
import path from"path";import{readFile,stat,readdir}from"fs/promises";import{pathToFileURL}from"url";import defaultConfig from"./defaultConfig.js";import getFiles from"./getFiles.js";import findFile from"./findFile.js";import serveFile from"./serveFile.js";import MiddlewareRunner from"./middlewareRunner.js";import ModuleCache from"./moduleCache.js";import createRequestWrapper,{readRawBody,parseBody}from"./requestWrapper.js";import createResponseWrapper from"./responseWrapper.js";import{corsMiddleware,compressionMiddleware,rateLimitMiddleware,securityMiddleware,loggingMiddleware}from"./builtinMiddleware.js";import{onRescan}from"./rescan.js";import{renderDir,renderPage}from"./templating/index.js";export default async(flags,log)=>{log("Initializing router",3);const rootPath=path.isAbsolute(flags.root)?flags.root:path.join(process.cwd(),flags.root);log(`Root path: ${rootPath}`,3);let config=defaultConfig;try{const configFileName=flags.config||".config.js",configPath=path.isAbsolute(configFileName)?configFileName:path.join(rootPath,configFileName);if(log(`Config file name: ${configFileName}`,3),log(`Config path: ${configPath}`,3),path.isAbsolute(configFileName))log("Config file name is absolute, skipping validation",4);else{const relativeConfigPath=path.relative(rootPath,configPath);if(log(`Relative config path: ${relativeConfigPath}`,4),log(`Starts with '..': ${relativeConfigPath.startsWith("..")}`,4),relativeConfigPath.startsWith("..")||path.isAbsolute(relativeConfigPath))throw log("Validation failed - throwing error",4),new Error(`Config file must be within the server root directory. Config path: ${configPath}, Root path: ${rootPath}`);log("Validation passed",4)}let userConfig;if(log(`Loading config from: ${configPath}`,3),configPath.endsWith(".js")){const configUrl=pathToFileURL(configPath).href+`?t=${Date.now()}`;userConfig=(await import(configUrl)).default}else{const configContent=await readFile(configPath,"utf8");userConfig=JSON.parse(configContent)}if(!userConfig)throw new Error("Config file is empty or has no default export");config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded and merged with defaults",3)}catch(e){if(e.message.includes("Config file must be within the server root directory"))throw e;const configFileName=flags.config||".config.js";if(configFileName.endsWith(".js"))try{const jsonFallback=configFileName.replace(/\.js$/,".json"),jsonPath=path.isAbsolute(jsonFallback)?jsonFallback:path.join(rootPath,jsonFallback);log(`Trying JSON fallback: ${jsonPath}`,3);const configContent=await readFile(jsonPath,"utf8"),userConfig=JSON.parse(configContent);config={...defaultConfig,...userConfig,allowedMimes:{...defaultConfig.allowedMimes,...userConfig.allowedMimes||{}},middleware:{...defaultConfig.middleware,...userConfig.middleware||{}},customRoutes:{...defaultConfig.customRoutes,...userConfig.customRoutes||{}},cache:{...defaultConfig.cache,...userConfig.cache||{}},templating:{...defaultConfig.templating,...userConfig.templating||{}}},log("User config loaded from JSON fallback",3)}catch(e2){log("Using default config (no config file found)",3)}else log("Using default config (no config file found)",3)}const dis=new Set(config.disallowedRegex);if(dis.add("^/\\..*"),dis.add("\\.config\\.js$"),dis.add("\\.config\\.json$"),dis.add("\\.git/"),config.disallowedRegex=[...dis],log(`Config loaded with ${config.disallowedRegex.length} disallowed patterns`,3),config.templating.preRender){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,count=await renderDir(rootPath,rootPath,globals,state,maxFragmentDepth);log(`Pre-rendered ${count} page(s)`,2);for(const[urlPattern,dirPath]of Object.entries(config.customRoutes||{})){const baseDirRaw=dirPath.includes("*")?dirPath.split("*")[0]:dirPath,resolvedBaseDir=(path.isAbsolute(baseDirRaw)?baseDirRaw:path.resolve(rootPath,baseDirRaw)).replace(/[/\\]+$/,"");try{if(!(await stat(resolvedBaseDir)).isDirectory())continue;const extraCount=await renderDir(resolvedBaseDir,resolvedBaseDir,globals,state,maxFragmentDepth);log(`Pre-rendered ${extraCount} page(s) from custom route: ${urlPattern}`,2)}catch{}}}let files=await getFiles(rootPath,config,log);log(`Initial scan found ${files.length} files`,2),onRescan(async done=>{try{files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2),done(null,files.length)}catch(error){log(`Rescan failed: ${error.message}`,1),done(error)}});const middlewareRunner=new MiddlewareRunner;if(config.middleware?.cors?.enabled&&(middlewareRunner.use(corsMiddleware(config.middleware.cors)),log("CORS middleware enabled",3)),config.middleware?.compression?.enabled&&(middlewareRunner.use(compressionMiddleware(config.middleware.compression)),log("Compression middleware enabled",3)),config.middleware?.rateLimit?.enabled&&(middlewareRunner.use(rateLimitMiddleware(config.middleware.rateLimit)),log("Rate limit middleware enabled",3)),config.middleware?.security?.enabled&&(middlewareRunner.use(securityMiddleware(config.middleware.security)),log("Security middleware enabled",3)),config.middleware?.logging?.enabled&&(middlewareRunner.use(loggingMiddleware(config.middleware.logging,log)),log("Logging middleware enabled",3)),config.middleware?.custom&&config.middleware.custom.length>0){log(`Loading ${config.middleware.custom.length} custom middleware files`,3);for(const middlewarePath of config.middleware.custom)try{const resolvedPath=path.isAbsolute(middlewarePath)?middlewarePath:path.resolve(rootPath,middlewarePath),middlewareUrl=pathToFileURL(resolvedPath).href+`?t=${Date.now()}`,customMiddleware=(await import(middlewareUrl)).default;"function"==typeof customMiddleware?(middlewareRunner.use(customMiddleware(config.middleware)),log(`Custom middleware loaded: ${middlewarePath}`,3)):log(`Custom middleware error: ${middlewarePath} does not export a default function`,1)}catch(error){log(`Custom middleware error for ${middlewarePath}: ${error.message}`,1)}}let moduleCache=null;config.cache?.enabled&&(moduleCache=new ModuleCache(config.cache),log(`Module cache initialized: ${config.cache.maxSize} max modules, ${config.cache.maxMemoryMB}MB limit, ${config.cache.ttlMs}ms TTL`,2));const customRoutes=new Map,wildcardRoutes=new Map;if(config.customRoutes&&Object.keys(config.customRoutes).length>0){log(`Processing ${Object.keys(config.customRoutes).length} custom routes`,3);for(const[urlPath,filePath]of Object.entries(config.customRoutes))if(urlPath.includes("*")){const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);wildcardRoutes.set(urlPath,resolvedPath),log(`Wildcard route mapped: ${urlPath} -> ${resolvedPath}`,3)}else{const resolvedPath=path.isAbsolute(filePath)?filePath:path.resolve(rootPath,filePath);customRoutes.set(urlPath,resolvedPath),log(`Custom route mapped: ${urlPath} -> ${resolvedPath}`,3)}}const matchWildcardRoute=(requestPath,pattern)=>{const regexPattern=(pattern.startsWith("/")?pattern:"/"+pattern).replace(/\*\*/g,"(.+)").replace(/\*/g,"([^/]+)");return new RegExp(`^${regexPattern}$`).exec(requestPath)},serveStaticCustomFile=async(filePath,res)=>{const fileExtension=path.extname(filePath).toLowerCase().slice(1),mimeConfig=config.allowedMimes[fileExtension];let mimeType,encoding;"string"==typeof mimeConfig?(mimeType=mimeConfig,encoding=mimeType.startsWith("text/")?"utf8":void 0):(mimeType=mimeConfig?.mime||"application/octet-stream",encoding="utf8"===mimeConfig?.encoding?"utf8":void 0);const fileContent=await readFile(filePath,encoding);log(`Serving custom file as ${mimeType} (${fileContent.length} bytes)`,2);const contentType="utf8"===encoding&&mimeType.startsWith("text/")?`${mimeType}; charset=utf-8`:mimeType;res.writeHead(200,{"Content-Type":contentType}),res.end(fileContent)},executeRouteModule=async(filePath,req,res,params={})=>{let module;if(moduleCache&&config.cache?.enabled){const fileStats=await stat(filePath);if(module=moduleCache.get(filePath,fileStats),!module){const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl);const estimatedSizeKB=fileStats.size/1024;moduleCache.set(filePath,module,fileStats,estimatedSizeKB)}}else{const fileUrl=pathToFileURL(filePath).href+`?t=${Date.now()}`;module=await import(fileUrl)}if("function"!=typeof module.default)return log(`Route file does not export a function: ${filePath}`,0),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Route file does not export a function");const enhancedReq=createRequestWrapper(req,params),enhancedRes=createResponseWrapper(res),rawBody=await readRawBody(req);enhancedReq._rawBody=rawBody,enhancedReq.body=parseBody(rawBody,req.headers["content-type"]),moduleCache&&(enhancedReq._kempoCache=moduleCache),await module.default(enhancedReq,enhancedRes)},walkDynamic=async(base,segments)=>{if(0===segments.length)return{filePath:base,params:{}};const[head,...rest]=segments;let entries;try{entries=await readdir(base,{withFileTypes:!0})}catch{return null}for(const entry of entries)if(entry.name===head)if(entry.isDirectory()){const result=await walkDynamic(path.join(base,head),rest);if(result)return result}else if(entry.isFile()&&0===rest.length)return{filePath:path.join(base,head),params:{}};for(const entry of entries){if(!entry.isDirectory()||!entry.name.startsWith("[")||!entry.name.endsWith("]"))continue;const paramName=entry.name.slice(1,-1),result=await walkDynamic(path.join(base,entry.name),rest);if(result)return{filePath:result.filePath,params:{[paramName]:head,...result.params}}}return null},serveResolvedPath=async(filePath,fileStat,params,req,res)=>{if(fileStat.isDirectory()){const methodUpper=req.method.toUpperCase(),candidates=[`${methodUpper}.js`,`${methodUpper}.html`,"index.js","index.html","index.htm"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}return config.routeFiles.includes(candidate)?(log(`Executing route file: ${candidatePath}`,2),await executeRouteModule(candidatePath,req,res,params),!0):(log(`Serving index file: ${candidatePath}`,2),await serveStaticCustomFile(candidatePath,res),!0)}return null}const fileName=path.basename(filePath);return config.routeFiles.includes(fileName)?(log(`Executing route file: ${filePath}`,2),await executeRouteModule(filePath,req,res,params),!0):(await serveStaticCustomFile(filePath,res),!0)},serveCustomRoutePath=async(resolvedFilePath,req,res,customRootDir=null)=>{let fileStat;try{fileStat=await stat(resolvedFilePath);const result=await serveResolvedPath(resolvedFilePath,fileStat,{},req,res);if(result)return result}catch(e){if("ENOENT"!==e.code)throw e}if(!fileStat){let current=resolvedFilePath;const remaining=[];for(;current!==path.dirname(current);){remaining.unshift(path.basename(current)),current=path.dirname(current);try{if(!(await stat(current)).isDirectory())break;const result=await walkDynamic(current,remaining);if(!result)break;const resolvedStat=await stat(result.filePath),served=await serveResolvedPath(result.filePath,resolvedStat,result.params,req,res);if(served)return served;break}catch(e2){if("ENOENT"!==e2.code)throw e2}}}if(config.templating?.ssr&&customRootDir){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,base=resolvedFilePath.replace(/\.html$/,"").replace(/[\/\\]+$/,"");for(const pageFile of[base+".page.html",path.join(base,"index.page.html")])try{await stat(pageFile);const html=await renderPage(pageFile,customRootDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),log(`SSR rendered custom route: ${pageFile}`,2),!0}catch(e){log(`SSR custom route miss for ${pageFile}: ${e.message}`,3)}}return null},rescanAttempts=new Map,dynamicNoRescanPaths=new Set,shouldSkipRescan=requestPath=>config.noRescanPaths.some(pattern=>new RegExp(pattern).test(requestPath))?(log(`Skipping rescan for configured pattern: ${requestPath}`,3),!0):!!dynamicNoRescanPaths.has(requestPath)&&(log(`Skipping rescan for dynamically blacklisted path: ${requestPath}`,3),!0),handler=async(req,res)=>{if(parseInt(req.headers["content-length"]||"0",10)>config.maxBodySize)return res.writeHead(413,{"Content-Type":"text/plain"}),void res.end("Payload Too Large");const rawBody=await new Promise((resolve,reject)=>{if(["GET","HEAD"].includes(req.method)&&!req.headers["content-length"])return resolve("");let body="",size=0;req.on("data",chunk=>{if(size+=chunk.length,size>config.maxBodySize)return req.destroy(),void reject(new Error("Payload Too Large"));body+=chunk.toString()}),req.on("end",()=>resolve(body)),req.on("error",reject)}).catch(err=>{if("Payload Too Large"===err.message)return res.writeHead(413,{"Content-Type":"text/plain"}),res.end("Payload Too Large"),null;throw err});if(null===rawBody)return;req._bufferedBody=rawBody;const enhancedRequest=createRequestWrapper(req,{}),enhancedResponse=createResponseWrapper(res);enhancedRequest._rawBody=rawBody,enhancedRequest.body=parseBody(rawBody,req.headers["content-type"]),await middlewareRunner.run(enhancedRequest,enhancedResponse,async()=>{const requestPath=enhancedRequest.url.split("?")[0];log(`${enhancedRequest.method} ${requestPath}`,4),log(`customRoutes keys: ${Array.from(customRoutes.keys()).join(", ")}`,4);const normalizePath=p=>{try{let np=decodeURIComponent(p);return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}catch(e){log(`Warning: Failed to decode URI component "${p}": ${e.message}`,1);let np=p;return np.startsWith("/")||(np="/"+np),np.length>1&&np.endsWith("/")&&(np=np.slice(0,-1)),np}},normalizedRequestPath=normalizePath(requestPath);log(`Normalized requestPath: ${normalizedRequestPath}`,4);let matchedKey=null;for(const key of customRoutes.keys())if(normalizePath(key)===normalizedRequestPath){matchedKey=key;break}if(matchedKey){const customFilePath=customRoutes.get(matchedKey);log(`Serving custom route: ${normalizedRequestPath} -> ${customFilePath}`,3);try{if(await serveCustomRoutePath(customFilePath,req,res,customFilePath))return;return log(`Custom route path not found: ${customFilePath}`,1),res.writeHead(404,{"Content-Type":"text/plain"}),void res.end("Custom route file not found")}catch(error){return log(`Error serving custom route ${normalizedRequestPath}: ${error.message}`,1),res.writeHead(500,{"Content-Type":"text/plain"}),void res.end("Internal Server Error")}}const wildcardMatch=(requestPath=>{for(const[pattern,filePath]of wildcardRoutes){const matches=matchWildcardRoute(requestPath,pattern);if(matches)return{filePath:filePath,matches:matches}}return null})(requestPath);if(wildcardMatch){const resolvedFilePath=((filePath,matches)=>{let resolvedPath=filePath,matchIndex=1;for(;resolvedPath.includes("**")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("**",matches[matchIndex]),matchIndex++;for(;resolvedPath.includes("*")&&matchIndex<matches.length;)resolvedPath=resolvedPath.replace("*",matches[matchIndex]),matchIndex++;return path.isAbsolute(resolvedPath)?resolvedPath:path.resolve(rootPath,resolvedPath)})(wildcardMatch.filePath,wildcardMatch.matches);log(`Serving wildcard route: ${requestPath} -> ${resolvedFilePath}`,3);try{const customRootDir=wildcardMatch.filePath.split("*")[0].replace(/[\/\\]+$/,"");if(await serveCustomRoutePath(resolvedFilePath,req,res,customRootDir))return;log(`Wildcard route path not found: ${requestPath}`,2)}catch(error){return log(`Error serving wildcard route ${requestPath}: ${error.message}`,1),enhancedResponse.writeHead(500,{"Content-Type":"text/plain"}),void enhancedResponse.end("Internal Server Error")}}const served=await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache);if(!served&&config.maxRescanAttempts>0&&!shouldSkipRescan(requestPath)){log("File not found, rescanning directory...",1),files=await getFiles(rootPath,config,log),log(`Rescan found ${files.length} files`,2);await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache)?rescanAttempts.delete(requestPath):((requestPath=>{const newAttempts=(rescanAttempts.get(requestPath)||0)+1;rescanAttempts.set(requestPath,newAttempts),newAttempts>config.maxRescanAttempts&&(dynamicNoRescanPaths.add(requestPath),log(`Path ${requestPath} added to dynamic blacklist after ${newAttempts} failed attempts`,1)),log(`Rescan attempt ${newAttempts}/${config.maxRescanAttempts} for: ${requestPath}`,3)})(requestPath),log(`404 - File not found after rescan: ${requestPath}`,1),enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found"))}else served||(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found"))})};return handler.moduleCache=moduleCache,handler.getStats=()=>moduleCache?.getStats()||null,handler.logCacheStats=()=>moduleCache?.logStats(log),handler.clearCache=()=>moduleCache?.clear(),handler};
|
package/package.json
CHANGED
package/src/router.js
CHANGED
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
loggingMiddleware
|
|
18
18
|
} from './builtinMiddleware.js';
|
|
19
19
|
import { onRescan } from './rescan.js';
|
|
20
|
-
import { renderDir } from './templating/index.js';
|
|
20
|
+
import { renderDir, renderPage } from './templating/index.js';
|
|
21
21
|
|
|
22
22
|
export default async (flags, log) => {
|
|
23
23
|
log('Initializing router', 3);
|
|
@@ -148,6 +148,19 @@ export default async (flags, log) => {
|
|
|
148
148
|
const {globals, state, maxFragmentDepth} = config.templating;
|
|
149
149
|
const count = await renderDir(rootPath, rootPath, globals, state, maxFragmentDepth);
|
|
150
150
|
log(`Pre-rendered ${count} page(s)`, 2);
|
|
151
|
+
|
|
152
|
+
for(const [urlPattern, dirPath] of Object.entries(config.customRoutes || {})) {
|
|
153
|
+
const baseDirRaw = dirPath.includes('*') ? dirPath.split('*')[0] : dirPath;
|
|
154
|
+
const resolvedBaseDir = (path.isAbsolute(baseDirRaw)
|
|
155
|
+
? baseDirRaw
|
|
156
|
+
: path.resolve(rootPath, baseDirRaw)).replace(/[/\\]+$/, '');
|
|
157
|
+
try {
|
|
158
|
+
const s = await stat(resolvedBaseDir);
|
|
159
|
+
if(!s.isDirectory()) continue;
|
|
160
|
+
const extraCount = await renderDir(resolvedBaseDir, resolvedBaseDir, globals, state, maxFragmentDepth);
|
|
161
|
+
log(`Pre-rendered ${extraCount} page(s) from custom route: ${urlPattern}`, 2);
|
|
162
|
+
} catch { /* directory doesn't exist or isn't accessible, skip */ }
|
|
163
|
+
}
|
|
151
164
|
}
|
|
152
165
|
|
|
153
166
|
let files = await getFiles(rootPath, config, log);
|
|
@@ -421,33 +434,58 @@ export default async (flags, log) => {
|
|
|
421
434
|
|
|
422
435
|
// Resolves a custom route path supporting files, directories, and [param] segments.
|
|
423
436
|
// Returns true if handled, null if path not found.
|
|
424
|
-
|
|
437
|
+
// customRootDir: root used for template/fragment lookup when attempting SSR.
|
|
438
|
+
const serveCustomRoutePath = async (resolvedFilePath, req, res, customRootDir = null) => {
|
|
425
439
|
let fileStat;
|
|
426
440
|
try {
|
|
427
441
|
fileStat = await stat(resolvedFilePath);
|
|
428
|
-
|
|
442
|
+
const result = await serveResolvedPath(resolvedFilePath, fileStat, {}, req, res);
|
|
443
|
+
if(result) return result;
|
|
444
|
+
// Directory existed but no index/route candidates — fall through to SSR
|
|
429
445
|
} catch(e) {
|
|
430
446
|
if(e.code !== 'ENOENT') throw e;
|
|
431
447
|
}
|
|
432
448
|
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
+
if(!fileStat) {
|
|
450
|
+
// Path doesn't exist literally — walk backwards to find the nearest existing
|
|
451
|
+
// ancestor directory, then traverse forward with [param] support.
|
|
452
|
+
let current = resolvedFilePath;
|
|
453
|
+
const remaining = [];
|
|
454
|
+
while(current !== path.dirname(current)) {
|
|
455
|
+
remaining.unshift(path.basename(current));
|
|
456
|
+
current = path.dirname(current);
|
|
457
|
+
try {
|
|
458
|
+
const s = await stat(current);
|
|
459
|
+
if(!s.isDirectory()) break;
|
|
460
|
+
const result = await walkDynamic(current, remaining);
|
|
461
|
+
if(!result) break;
|
|
462
|
+
const resolvedStat = await stat(result.filePath);
|
|
463
|
+
const served = await serveResolvedPath(result.filePath, resolvedStat, result.params, req, res);
|
|
464
|
+
if(served) return served;
|
|
465
|
+
break;
|
|
466
|
+
} catch(e2) {
|
|
467
|
+
if(e2.code !== 'ENOENT') throw e2;
|
|
468
|
+
}
|
|
449
469
|
}
|
|
450
470
|
}
|
|
471
|
+
|
|
472
|
+
if(config.templating?.ssr && customRootDir) {
|
|
473
|
+
const {globals, state, maxFragmentDepth} = config.templating;
|
|
474
|
+
const base = resolvedFilePath.replace(/\.html$/, '').replace(/[\/\\]+$/, '');
|
|
475
|
+
for(const pageFile of [base + '.page.html', path.join(base, 'index.page.html')]) {
|
|
476
|
+
try {
|
|
477
|
+
await stat(pageFile);
|
|
478
|
+
const html = await renderPage(pageFile, customRootDir, globals, state, maxFragmentDepth);
|
|
479
|
+
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
|
|
480
|
+
res.end(html);
|
|
481
|
+
log(`SSR rendered custom route: ${pageFile}`, 2);
|
|
482
|
+
return true;
|
|
483
|
+
} catch(e) {
|
|
484
|
+
log(`SSR custom route miss for ${pageFile}: ${e.message}`, 3);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
451
489
|
return null;
|
|
452
490
|
};
|
|
453
491
|
|
|
@@ -572,7 +610,7 @@ export default async (flags, log) => {
|
|
|
572
610
|
const customFilePath = customRoutes.get(matchedKey);
|
|
573
611
|
log(`Serving custom route: ${normalizedRequestPath} -> ${customFilePath}`, 3);
|
|
574
612
|
try {
|
|
575
|
-
const result = await serveCustomRoutePath(customFilePath, req, res);
|
|
613
|
+
const result = await serveCustomRoutePath(customFilePath, req, res, customFilePath);
|
|
576
614
|
if(result) return;
|
|
577
615
|
log(`Custom route path not found: ${customFilePath}`, 1);
|
|
578
616
|
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
@@ -592,7 +630,8 @@ export default async (flags, log) => {
|
|
|
592
630
|
const resolvedFilePath = resolveWildcardPath(wildcardMatch.filePath, wildcardMatch.matches);
|
|
593
631
|
log(`Serving wildcard route: ${requestPath} -> ${resolvedFilePath}`, 3);
|
|
594
632
|
try {
|
|
595
|
-
const
|
|
633
|
+
const customRootDir = wildcardMatch.filePath.split('*')[0].replace(/[\/\\]+$/, '');
|
|
634
|
+
const result = await serveCustomRoutePath(resolvedFilePath, req, res, customRootDir);
|
|
596
635
|
if(result) return;
|
|
597
636
|
log(`Wildcard route path not found: ${requestPath}`, 2);
|
|
598
637
|
} catch(error) {
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import http from 'http';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import {withTempDir} from './utils/temp-dir.js';
|
|
4
|
+
import {write} from './utils/file-writer.js';
|
|
5
|
+
import {randomPort} from './utils/port.js';
|
|
6
|
+
import {httpGet} from './utils/http.js';
|
|
7
|
+
import router from '../src/router.js';
|
|
8
|
+
|
|
9
|
+
const startServer = async (dir, flags, config) => {
|
|
10
|
+
await write(dir, `${flags.root}/.config.json`, JSON.stringify(config));
|
|
11
|
+
const handler = await router({...flags, logging: 0}, () => {});
|
|
12
|
+
const server = http.createServer(handler);
|
|
13
|
+
const port = randomPort();
|
|
14
|
+
await new Promise(r => server.listen(port, r));
|
|
15
|
+
await new Promise(r => setTimeout(r, 30));
|
|
16
|
+
return {server, port};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export default {
|
|
20
|
+
'wildcard custom route renders .page.html via SSR': async ({pass, fail}) => {
|
|
21
|
+
try {
|
|
22
|
+
await withTempDir(async (dir) => {
|
|
23
|
+
const template = '<html><body><location name="main" /></body></html>';
|
|
24
|
+
const page = '<page template="default"><content location="main"><h1>Admin Page</h1></content></page>';
|
|
25
|
+
|
|
26
|
+
await write(dir, 'admin/default.template.html', template);
|
|
27
|
+
await write(dir, 'admin/dashboard.page.html', page);
|
|
28
|
+
await write(dir, 'public/index.html', '<h1>root</h1>');
|
|
29
|
+
|
|
30
|
+
const prev = process.cwd();
|
|
31
|
+
process.chdir(dir);
|
|
32
|
+
const {server, port} = await startServer(dir, {root: 'public'}, {
|
|
33
|
+
customRoutes: {'/admin/**': '../admin/**'},
|
|
34
|
+
templating: {ssr: true}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const r = await httpGet(`http://localhost:${port}/admin/dashboard`);
|
|
39
|
+
if(r.res.statusCode !== 200) throw new Error(`expected 200, got ${r.res.statusCode}`);
|
|
40
|
+
const body = r.body.toString();
|
|
41
|
+
if(!body.includes('<h1>Admin Page</h1>')) throw new Error(`missing page content: ${body}`);
|
|
42
|
+
if(!body.includes('<html>')) throw new Error(`missing template wrapper: ${body}`);
|
|
43
|
+
} finally {
|
|
44
|
+
server.close();
|
|
45
|
+
process.chdir(prev);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
pass('wildcard custom route renders .page.html via SSR');
|
|
49
|
+
} catch(e) {
|
|
50
|
+
fail(e.message);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
'wildcard custom route renders index.page.html for directory path': async ({pass, fail}) => {
|
|
55
|
+
try {
|
|
56
|
+
await withTempDir(async (dir) => {
|
|
57
|
+
const template = '<html><body><location name="main" /></body></html>';
|
|
58
|
+
const page = '<page template="default"><content location="main"><h1>Section Index</h1></content></page>';
|
|
59
|
+
|
|
60
|
+
await write(dir, 'admin/default.template.html', template);
|
|
61
|
+
await write(dir, 'admin/users/index.page.html', page);
|
|
62
|
+
await write(dir, 'public/index.html', '<h1>root</h1>');
|
|
63
|
+
|
|
64
|
+
const prev = process.cwd();
|
|
65
|
+
process.chdir(dir);
|
|
66
|
+
const {server, port} = await startServer(dir, {root: 'public'}, {
|
|
67
|
+
customRoutes: {'/admin/**': '../admin/**'},
|
|
68
|
+
templating: {ssr: true}
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const r = await httpGet(`http://localhost:${port}/admin/users`);
|
|
73
|
+
if(r.res.statusCode !== 200) throw new Error(`expected 200, got ${r.res.statusCode}`);
|
|
74
|
+
const body = r.body.toString();
|
|
75
|
+
if(!body.includes('<h1>Section Index</h1>')) throw new Error(`missing page content: ${body}`);
|
|
76
|
+
} finally {
|
|
77
|
+
server.close();
|
|
78
|
+
process.chdir(prev);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
pass('wildcard custom route renders index.page.html for directory path');
|
|
82
|
+
} catch(e) {
|
|
83
|
+
fail(e.message);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
'SSR not attempted for custom route when templating.ssr is false': async ({pass, fail}) => {
|
|
88
|
+
try {
|
|
89
|
+
await withTempDir(async (dir) => {
|
|
90
|
+
const template = '<html><body><location name="main" /></body></html>';
|
|
91
|
+
const page = '<page template="default"><content location="main"><h1>Should Not Render</h1></content></page>';
|
|
92
|
+
|
|
93
|
+
await write(dir, 'admin/default.template.html', template);
|
|
94
|
+
await write(dir, 'admin/dashboard.page.html', page);
|
|
95
|
+
await write(dir, 'public/index.html', '<h1>root</h1>');
|
|
96
|
+
|
|
97
|
+
const prev = process.cwd();
|
|
98
|
+
process.chdir(dir);
|
|
99
|
+
const {server, port} = await startServer(dir, {root: 'public'}, {
|
|
100
|
+
customRoutes: {'/admin/**': '../admin/**'},
|
|
101
|
+
templating: {ssr: false}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
const r = await httpGet(`http://localhost:${port}/admin/dashboard`);
|
|
106
|
+
if(r.res.statusCode !== 404) throw new Error(`expected 404, got ${r.res.statusCode}`);
|
|
107
|
+
} finally {
|
|
108
|
+
server.close();
|
|
109
|
+
process.chdir(prev);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
pass('SSR not attempted when templating.ssr is false');
|
|
113
|
+
} catch(e) {
|
|
114
|
+
fail(e.message);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
'wildcard custom route SSR uses custom root for template/fragment lookup': async ({pass, fail}) => {
|
|
119
|
+
try {
|
|
120
|
+
await withTempDir(async (dir) => {
|
|
121
|
+
const template = '<html><fragment name="nav" /><location name="main" /></html>';
|
|
122
|
+
const fragment = '<nav>Custom Nav</nav>';
|
|
123
|
+
const page = '<page template="default"><content location="main"><p>Content</p></content></page>';
|
|
124
|
+
|
|
125
|
+
await write(dir, 'admin/default.template.html', template);
|
|
126
|
+
await write(dir, 'admin/nav.fragment.html', fragment);
|
|
127
|
+
await write(dir, 'admin/about.page.html', page);
|
|
128
|
+
await write(dir, 'public/index.html', '<h1>root</h1>');
|
|
129
|
+
|
|
130
|
+
const prev = process.cwd();
|
|
131
|
+
process.chdir(dir);
|
|
132
|
+
const {server, port} = await startServer(dir, {root: 'public'}, {
|
|
133
|
+
customRoutes: {'/admin/**': '../admin/**'},
|
|
134
|
+
templating: {ssr: true}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const r = await httpGet(`http://localhost:${port}/admin/about`);
|
|
139
|
+
if(r.res.statusCode !== 200) throw new Error(`expected 200, got ${r.res.statusCode}`);
|
|
140
|
+
const body = r.body.toString();
|
|
141
|
+
if(!body.includes('<nav>Custom Nav</nav>')) throw new Error(`fragment not resolved: ${body}`);
|
|
142
|
+
if(!body.includes('<p>Content</p>')) throw new Error(`page content missing: ${body}`);
|
|
143
|
+
} finally {
|
|
144
|
+
server.close();
|
|
145
|
+
process.chdir(prev);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
pass('custom route SSR uses custom root for template/fragment lookup');
|
|
149
|
+
} catch(e) {
|
|
150
|
+
fail(e.message);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
'preRender renders .page.html files in wildcard custom route directory': async ({pass, fail}) => {
|
|
155
|
+
try {
|
|
156
|
+
await withTempDir(async (dir) => {
|
|
157
|
+
const template = '<html><body><location name="main" /></body></html>';
|
|
158
|
+
const page = '<page template="default"><content location="main"><h1>Pre-rendered</h1></content></page>';
|
|
159
|
+
|
|
160
|
+
await write(dir, 'admin/default.template.html', template);
|
|
161
|
+
await write(dir, 'admin/info.page.html', page);
|
|
162
|
+
await write(dir, 'public/index.html', '<h1>root</h1>');
|
|
163
|
+
|
|
164
|
+
const prev = process.cwd();
|
|
165
|
+
process.chdir(dir);
|
|
166
|
+
const {server, port} = await startServer(dir, {root: 'public'}, {
|
|
167
|
+
customRoutes: {'/admin/**': '../admin/**'},
|
|
168
|
+
templating: {preRender: true}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
// preRender should have written admin/info.html
|
|
173
|
+
const {readFile} = await import('fs/promises');
|
|
174
|
+
const rendered = await readFile(path.join(dir, 'admin', 'info.html'), 'utf8');
|
|
175
|
+
if(!rendered.includes('<h1>Pre-rendered</h1>')) throw new Error(`missing content: ${rendered}`);
|
|
176
|
+
// Serving the static pre-rendered file should also work
|
|
177
|
+
const r = await httpGet(`http://localhost:${port}/admin/info.html`);
|
|
178
|
+
if(r.res.statusCode !== 200) throw new Error(`expected 200, got ${r.res.statusCode}`);
|
|
179
|
+
} finally {
|
|
180
|
+
server.close();
|
|
181
|
+
process.chdir(prev);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
pass('preRender renders .page.html files in wildcard custom route directory');
|
|
185
|
+
} catch(e) {
|
|
186
|
+
fail(e.message);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
};
|