kempo-server 3.0.12 → 3.1.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.
- package/CHANGELOG.md +5 -0
- package/dist/router.js +1 -1
- package/docs/middleware.html +1 -1
- package/docs/templating.html +1 -1
- package/docs-src/middleware.page.html +1 -1
- package/package.json +1 -1
- package/src/router.js +38 -14
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `kempo-server` are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [3.1.0] - 2026-04-19
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **`rootPath` injected into custom middleware config.** When the server loads custom middleware, it now merges `rootPath` (the absolute path to the server root directory) into the config object passed to each middleware factory. Previously middleware received only the raw `middleware` config section; now it receives `{ ...middlewareConfig, rootPath }`. This allows middleware to resolve files relative to the project root without hardcoding paths.
|
|
9
|
+
|
|
5
10
|
## [3.0.12] - 2026-04-17
|
|
6
11
|
|
|
7
12
|
### Added
|
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,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`,`${methodUpper}.page.html`,"index.js","index.html","index.page.html","index.htm","CATCH.js","CATCH.html","CATCH.page.html"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}if(candidate.endsWith(".page.html")){log(`Rendering page template: ${candidatePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(candidatePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}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);if(fileName.endsWith(".page.html")){log(`Rendering page template: ${filePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(filePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}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,serveCatchFallback=async(requestPath,req,res)=>{const candidates=["CATCH.js","CATCH.html","CATCH.page.html"];let dir=path.join(rootPath,requestPath.startsWith("/")?requestPath.slice(1):requestPath);for(path.extname(dir)&&(dir=path.dirname(dir));dir.startsWith(rootPath);){for(const candidate of candidates){const candidatePath=path.join(dir,candidate);try{await stat(candidatePath)}catch{continue}if(log(`Serving catch fallback: ${candidatePath}`,2),"CATCH.page.html"===candidate){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,html=await renderPage(candidatePath,rootPath,globals,state,maxFragmentDepth);return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}if("CATCH.js"===candidate)return await executeRouteModule(candidatePath,req,res),!0;const fileContent=await readFile(candidatePath,"utf8");return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(fileContent),!0}const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return!1},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);if(await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache))rescanAttempts.delete(requestPath);else{if((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),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}}else if(!served){if(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;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,renderExternalPage}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,rootPath:rootPath})),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,"\0GLOBSTAR\0").replace(/\*/g,"([^/]+)").replace(/\x00GLOBSTAR\x00/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},getResolveDir=(pageFilePath,reqUrl)=>{if(pageFilePath.startsWith(rootPath))return path.dirname(pageFilePath);const urlParts=reqUrl.split("?")[0].replace(/\/+$/,"").split("/").filter(Boolean),depth=urlParts.length;let fakeDir=rootPath;for(let i=0;i<depth;i++)fakeDir=path.join(fakeDir,urlParts[i]||"__scope__");return fakeDir},serveResolvedPath=async(filePath,fileStat,params,req,res)=>{if(fileStat.isDirectory()){const methodUpper=req.method.toUpperCase(),candidates=[`${methodUpper}.js`,`${methodUpper}.html`,`${methodUpper}.page.html`,"index.js","index.html","index.page.html","index.htm","CATCH.js","CATCH.html","CATCH.page.html"];for(const candidate of candidates){const candidatePath=path.join(filePath,candidate);try{await stat(candidatePath)}catch{continue}if(candidate.endsWith(".page.html")){log(`Rendering page template: ${candidatePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(candidatePath,req.url),html=await renderExternalPage(candidatePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}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);if(fileName.endsWith(".page.html")){log(`Rendering page template: ${filePath}`,2);const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(filePath,req.url),html=await renderExternalPage(filePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}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 resolveDir=getResolveDir(pageFile,req.url),html=await renderExternalPage(pageFile,rootPath,resolveDir,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,serveCatchFallbackFrom=async(startDir,boundDir,req,res)=>{const candidates=["CATCH.js","CATCH.html","CATCH.page.html"];let dir=path.extname(startDir)?path.dirname(startDir):startDir;const bound=path.resolve(boundDir);for(;path.resolve(dir).startsWith(bound);){for(const candidate of candidates){const candidatePath=path.join(dir,candidate);try{await stat(candidatePath)}catch{continue}if(log(`Serving catch fallback: ${candidatePath}`,2),"CATCH.page.html"===candidate){const{globals:globals,state:state,maxFragmentDepth:maxFragmentDepth}=config.templating,resolveDir=getResolveDir(candidatePath,req.url),html=await renderExternalPage(candidatePath,rootPath,resolveDir,globals,state,maxFragmentDepth);return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(html),!0}if("CATCH.js"===candidate)return await executeRouteModule(candidatePath,req,res),!0;const fileContent=await readFile(candidatePath,"utf8");return res.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),res.end(fileContent),!0}const parent=path.dirname(dir);if(parent===dir)break;dir=parent}return!1},serveCatchFallback=(requestPath,req,res)=>{const startDir=path.join(rootPath,requestPath.startsWith("/")?requestPath.slice(1):requestPath);return serveCatchFallbackFrom(startDir,rootPath,req,res)},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;if(log(`Wildcard route path not found: ${requestPath}`,2),await serveCatchFallbackFrom(resolvedFilePath,customRootDir,req,res))return}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);if(await serveFile(files,rootPath,requestPath,req.method,config,req,res,log,moduleCache))rescanAttempts.delete(requestPath);else{if((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),await serveCatchFallback(requestPath,req,res))return;enhancedResponse.writeHead(404,{"Content-Type":"text/plain"}),enhancedResponse.end("Not Found")}}else if(!served){if(shouldSkipRescan(requestPath)?log(`404 - Skipped rescan for: ${requestPath}`,2):log(`404 - File not found: ${requestPath}`,1),await serveCatchFallback(requestPath,req,res))return;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/docs/middleware.html
CHANGED
|
@@ -176,7 +176,7 @@
|
|
|
176
176
|
|
|
177
177
|
<h3>Middleware Function Parameters</h3>
|
|
178
178
|
<ul>
|
|
179
|
-
<li><code>config</code> -
|
|
179
|
+
<li><code>config</code> - The middleware config object, extended with <code>rootPath</code> (absolute path to the server root directory)</li>
|
|
180
180
|
<li><code>req</code> - Request object (can be modified)</li>
|
|
181
181
|
<li><code>res</code> - Response object (can be modified)</li>
|
|
182
182
|
<li><code>next</code> - Function to call the next middleware or route handler</li>
|
package/docs/templating.html
CHANGED
|
@@ -336,7 +336,7 @@
|
|
|
336
336
|
</div>
|
|
337
337
|
<p>A common use case is sending templated emails. Create a dedicated email directory with a shared template, per-email pages, reusable fragments, and optional global content:</p>
|
|
338
338
|
<pre><code class="hljs javascript"><span class="hljs-keyword">import</span> { renderPageToString } <span class="hljs-keyword">from</span> <span class="hljs-string">'kempo-server/templating'</span>;<br /><span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;<br /><br /><span class="hljs-keyword">const</span> emailsDir = path.resolve(<span class="hljs-string">'./emails'</span>);<br /><span class="hljs-keyword">const</span> html = <span class="hljs-keyword">await</span> renderPageToString(<br /> path.join(emailsDir, <span class="hljs-string">'welcome.page.html'</span>),<br /> { userName: <span class="hljs-string">'Alice'</span>, orderId: <span class="hljs-string">'1234'</span> }<br />);</code></pre>
|
|
339
|
-
<p>Built-in vars (<code>2026</code>, <code>2026-04-
|
|
339
|
+
<p>Built-in vars (<code>2026</code>, <code>2026-04-19</code>, <code>2026-04-19T16:45:40.333Z</code>, <code>1776617140333</code>) are always available. Note that <code><page></code> tag attributes take highest priority and override <code>vars</code> with the same key.</p>
|
|
340
340
|
|
|
341
341
|
<h3 id="render-external-page">renderExternalPage</h3>
|
|
342
342
|
<p>Identical pipeline to <code>renderPage</code>, but decouples the page file's physical location from where templates and fragments are resolved. Use this when a page file lives outside <code>rootDir</code> — for example, in a plugin or extension package — but should be rendered using the host project's templates, fragments, and globals.</p>
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
|
|
77
77
|
<h3>Middleware Function Parameters</h3>
|
|
78
78
|
<ul>
|
|
79
|
-
<li><code>config</code> -
|
|
79
|
+
<li><code>config</code> - The middleware config object, extended with <code>rootPath</code> (absolute path to the server root directory)</li>
|
|
80
80
|
<li><code>req</code> - Request object (can be modified)</li>
|
|
81
81
|
<li><code>res</code> - Response object (can be modified)</li>
|
|
82
82
|
<li><code>next</code> - Function to call the next middleware or route handler</li>
|
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,
|
|
20
|
+
import { renderDir, renderExternalPage } from './templating/index.js';
|
|
21
21
|
|
|
22
22
|
export default async (flags, log) => {
|
|
23
23
|
log('Initializing router', 3);
|
|
@@ -218,7 +218,7 @@ export default async (flags, log) => {
|
|
|
218
218
|
const customMiddleware = middlewareModule.default;
|
|
219
219
|
|
|
220
220
|
if (typeof customMiddleware === 'function') {
|
|
221
|
-
middlewareRunner.use(customMiddleware(config.middleware));
|
|
221
|
+
middlewareRunner.use(customMiddleware({ ...config.middleware, rootPath }));
|
|
222
222
|
log(`Custom middleware loaded: ${middlewarePath}`, 3);
|
|
223
223
|
} else {
|
|
224
224
|
log(`Custom middleware error: ${middlewarePath} does not export a default function`, 1);
|
|
@@ -269,8 +269,9 @@ export default async (flags, log) => {
|
|
|
269
269
|
// Convert wildcard pattern to regex
|
|
270
270
|
// IMPORTANT: Replace ** BEFORE * to avoid replacing both * in **
|
|
271
271
|
const regexPattern = normalizedPattern
|
|
272
|
-
.replace(/\*\*/g, '
|
|
273
|
-
.replace(/\*/g, '([^/]+)')
|
|
272
|
+
.replace(/\*\*/g, '\x00GLOBSTAR\x00') // placeholder to avoid double-replace
|
|
273
|
+
.replace(/\*/g, '([^/]+)') // single * — one path segment
|
|
274
|
+
.replace(/\x00GLOBSTAR\x00/g, '(.*)'); // ** — zero or more segments including slashes
|
|
274
275
|
|
|
275
276
|
const regex = new RegExp(`^${regexPattern}$`);
|
|
276
277
|
return regex.exec(requestPath);
|
|
@@ -395,6 +396,18 @@ export default async (flags, log) => {
|
|
|
395
396
|
return null;
|
|
396
397
|
};
|
|
397
398
|
|
|
399
|
+
// Build a virtual resolveDir that reflects the URL depth, so pathToRoot is computed correctly.
|
|
400
|
+
// For pages inside rootPath use their actual dir; for external pages fake a subdir at the right depth.
|
|
401
|
+
const getResolveDir = (pageFilePath, reqUrl) => {
|
|
402
|
+
if(pageFilePath.startsWith(rootPath)) return path.dirname(pageFilePath);
|
|
403
|
+
const urlParts = reqUrl.split('?')[0].replace(/\/+$/, '').split('/').filter(Boolean);
|
|
404
|
+
const depth = urlParts.length;
|
|
405
|
+
// Build a virtual path depth levels deep inside rootPath
|
|
406
|
+
let fakeDir = rootPath;
|
|
407
|
+
for(let i = 0; i < depth; i++) fakeDir = path.join(fakeDir, urlParts[i] || '__scope__');
|
|
408
|
+
return fakeDir;
|
|
409
|
+
};
|
|
410
|
+
|
|
398
411
|
// Serve a resolved file or directory (fileStat already known).
|
|
399
412
|
// Returns true if handled, null if directory has no matching route/index file.
|
|
400
413
|
const serveResolvedPath = async (filePath, fileStat, params, req, res) => {
|
|
@@ -418,7 +431,8 @@ export default async (flags, log) => {
|
|
|
418
431
|
if(candidate.endsWith('.page.html')) {
|
|
419
432
|
log(`Rendering page template: ${candidatePath}`, 2);
|
|
420
433
|
const {globals, state, maxFragmentDepth} = config.templating;
|
|
421
|
-
const
|
|
434
|
+
const resolveDir = getResolveDir(candidatePath, req.url);
|
|
435
|
+
const html = await renderExternalPage(candidatePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
|
|
422
436
|
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
|
|
423
437
|
res.end(html);
|
|
424
438
|
return true;
|
|
@@ -439,7 +453,8 @@ export default async (flags, log) => {
|
|
|
439
453
|
if(fileName.endsWith('.page.html')) {
|
|
440
454
|
log(`Rendering page template: ${filePath}`, 2);
|
|
441
455
|
const {globals, state, maxFragmentDepth} = config.templating;
|
|
442
|
-
const
|
|
456
|
+
const resolveDir = getResolveDir(filePath, req.url);
|
|
457
|
+
const html = await renderExternalPage(filePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
|
|
443
458
|
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
|
|
444
459
|
res.end(html);
|
|
445
460
|
return true;
|
|
@@ -496,7 +511,8 @@ export default async (flags, log) => {
|
|
|
496
511
|
for(const pageFile of [base + '.page.html', path.join(base, 'index.page.html')]) {
|
|
497
512
|
try {
|
|
498
513
|
await stat(pageFile);
|
|
499
|
-
const
|
|
514
|
+
const resolveDir = getResolveDir(pageFile, req.url);
|
|
515
|
+
const html = await renderExternalPage(pageFile, rootPath, resolveDir, globals, state, maxFragmentDepth);
|
|
500
516
|
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
|
|
501
517
|
res.end(html);
|
|
502
518
|
log(`SSR rendered custom route: ${pageFile}`, 2);
|
|
@@ -513,22 +529,23 @@ export default async (flags, log) => {
|
|
|
513
529
|
// Track 404 attempts to avoid unnecessary rescans
|
|
514
530
|
const rescanAttempts = new Map(); // path -> attempt count
|
|
515
531
|
|
|
516
|
-
// Walk up the directory tree
|
|
532
|
+
// Walk up the directory tree looking for CATCH.js, CATCH.html, CATCH.page.html.
|
|
533
|
+
// startDir: absolute path to begin the walk. boundDir: walk stops here (inclusive).
|
|
517
534
|
// Returns true if a catch fallback handler was found and served, false otherwise.
|
|
518
|
-
const
|
|
535
|
+
const serveCatchFallbackFrom = async (startDir, boundDir, req, res) => {
|
|
519
536
|
const candidates = ['CATCH.js', 'CATCH.html', 'CATCH.page.html'];
|
|
520
|
-
let dir = path.
|
|
521
|
-
|
|
522
|
-
if(path.extname(dir)) dir = path.dirname(dir);
|
|
537
|
+
let dir = path.extname(startDir) ? path.dirname(startDir) : startDir;
|
|
538
|
+
const bound = path.resolve(boundDir);
|
|
523
539
|
|
|
524
|
-
while(dir.startsWith(
|
|
540
|
+
while(path.resolve(dir).startsWith(bound)) {
|
|
525
541
|
for(const candidate of candidates) {
|
|
526
542
|
const candidatePath = path.join(dir, candidate);
|
|
527
543
|
try { await stat(candidatePath); } catch { continue; }
|
|
528
544
|
log(`Serving catch fallback: ${candidatePath}`, 2);
|
|
529
545
|
if(candidate === 'CATCH.page.html') {
|
|
530
546
|
const {globals, state, maxFragmentDepth} = config.templating;
|
|
531
|
-
const
|
|
547
|
+
const resolveDir = getResolveDir(candidatePath, req.url);
|
|
548
|
+
const html = await renderExternalPage(candidatePath, rootPath, resolveDir, globals, state, maxFragmentDepth);
|
|
532
549
|
res.writeHead(404, {'Content-Type': 'text/html; charset=utf-8'});
|
|
533
550
|
res.end(html);
|
|
534
551
|
return true;
|
|
@@ -549,6 +566,12 @@ export default async (flags, log) => {
|
|
|
549
566
|
}
|
|
550
567
|
return false;
|
|
551
568
|
};
|
|
569
|
+
|
|
570
|
+
const serveCatchFallback = (requestPath, req, res) => {
|
|
571
|
+
const startDir = path.join(rootPath, requestPath.startsWith('/') ? requestPath.slice(1) : requestPath);
|
|
572
|
+
return serveCatchFallbackFrom(startDir, rootPath, req, res);
|
|
573
|
+
};
|
|
574
|
+
|
|
552
575
|
const dynamicNoRescanPaths = new Set(); // paths that have exceeded max attempts
|
|
553
576
|
|
|
554
577
|
// Helper function to check if a path should skip rescanning
|
|
@@ -692,6 +715,7 @@ export default async (flags, log) => {
|
|
|
692
715
|
const result = await serveCustomRoutePath(resolvedFilePath, req, res, customRootDir);
|
|
693
716
|
if(result) return;
|
|
694
717
|
log(`Wildcard route path not found: ${requestPath}`, 2);
|
|
718
|
+
if(await serveCatchFallbackFrom(resolvedFilePath, customRootDir, req, res)) return;
|
|
695
719
|
} catch(error) {
|
|
696
720
|
log(`Error serving wildcard route ${requestPath}: ${error.message}`, 1);
|
|
697
721
|
enhancedResponse.writeHead(500, { 'Content-Type': 'text/plain' });
|