kempo-server 3.0.12 → 3.1.1
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/LICENSE.md +60 -0
- package/dist/router.js +1 -1
- package/docs/caching.html +60 -12
- package/docs/cli-utils.html +60 -12
- package/docs/configuration.html +60 -12
- package/docs/examples.html +60 -12
- package/docs/fs-utils.html +60 -12
- package/docs/getting-started.html +60 -12
- package/docs/index.html +60 -12
- package/docs/middleware.html +61 -13
- package/docs/request-response.html +60 -12
- package/docs/routing.html +60 -12
- package/docs/templating.html +61 -13
- package/docs/theme.css +1 -1
- package/docs-src/middleware.page.html +1 -1
- package/docs-src/nav.fragment.html +60 -12
- package/package.json +4 -1
- package/src/router.js +38 -14
- package/tests/router-custom-route-ssr.node-test.js +5 -5
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/LICENSE.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dustin Poissant
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Third-Party Licenses
|
|
26
|
+
|
|
27
|
+
This project includes third-party software. The following sections detail the licenses for these components:
|
|
28
|
+
|
|
29
|
+
### Lit
|
|
30
|
+
|
|
31
|
+
This project includes Lit, which is licensed under the BSD-3-Clause License:
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
Copyright 2017 Google LLC. All rights reserved.
|
|
35
|
+
|
|
36
|
+
Redistribution and use in source and binary forms, with or without
|
|
37
|
+
modification, are permitted provided that the following conditions are met:
|
|
38
|
+
|
|
39
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
40
|
+
list of conditions and the following disclaimer.
|
|
41
|
+
|
|
42
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
43
|
+
this list of conditions and the following disclaimer in the documentation
|
|
44
|
+
and/or other materials provided with the distribution.
|
|
45
|
+
|
|
46
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
47
|
+
contributors may be used to endorse or promote products derived from
|
|
48
|
+
this software without specific prior written permission.
|
|
49
|
+
|
|
50
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
51
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
52
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
53
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
54
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
55
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
56
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
57
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
58
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
59
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
60
|
+
```
|
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/caching.html
CHANGED
|
@@ -37,13 +37,35 @@
|
|
|
37
37
|
class="d-if ph"
|
|
38
38
|
style="align-items: center"
|
|
39
39
|
>
|
|
40
|
-
<img
|
|
40
|
+
<img
|
|
41
|
+
src="./media/icon32.png"
|
|
42
|
+
alt="Kempo Server Icon"
|
|
43
|
+
class="pr"
|
|
44
|
+
/>
|
|
41
45
|
Kempo Server
|
|
42
46
|
</a>
|
|
43
47
|
<div class="flex"></div>
|
|
44
|
-
<a
|
|
45
|
-
|
|
46
|
-
|
|
48
|
+
<a
|
|
49
|
+
href="https://github.com/dustinpoissant/kempo-server?tab=License-1-ov-file#creative-commons-attribution-noncommercial-sharealike-20"
|
|
50
|
+
target="_blank"
|
|
51
|
+
><k-icon name="license"></k-icon></a>
|
|
52
|
+
<a
|
|
53
|
+
href="https://www.npmjs.com/package/kempo-server"
|
|
54
|
+
target="_blank"
|
|
55
|
+
><k-icon name="npm"></k-icon></a>
|
|
56
|
+
<a
|
|
57
|
+
href="https://github.com/dustinpoissant/kempo-server"
|
|
58
|
+
target="_blank"
|
|
59
|
+
><k-icon name="github-mark"></k-icon></a>
|
|
60
|
+
<k-theme-switcher
|
|
61
|
+
class="mr"
|
|
62
|
+
style="
|
|
63
|
+
--padding: 0.5rem;
|
|
64
|
+
--c_active: var(--tc_on_primary);
|
|
65
|
+
--tc_active: var(--c_primary);
|
|
66
|
+
--c_inactive__hover: rgba(255, 255, 255, 0.1);
|
|
67
|
+
"
|
|
68
|
+
></k-theme-switcher>
|
|
47
69
|
</k-nav>
|
|
48
70
|
<div style="width: 100%; height: 4rem;"></div>
|
|
49
71
|
<k-aside
|
|
@@ -51,9 +73,15 @@
|
|
|
51
73
|
state="offscreen"
|
|
52
74
|
>
|
|
53
75
|
<menu>
|
|
54
|
-
<a
|
|
76
|
+
<a
|
|
77
|
+
href="./"
|
|
78
|
+
class="ta-center bb mb r0"
|
|
79
|
+
>
|
|
55
80
|
<h1 class="tc-primary">Kempo Server</h1>
|
|
56
|
-
<img
|
|
81
|
+
<img
|
|
82
|
+
src="./media/icon128.png"
|
|
83
|
+
alt="Kempo UI Icon"
|
|
84
|
+
/>
|
|
57
85
|
</a>
|
|
58
86
|
|
|
59
87
|
<h3 class="mt mb0">Advanced Features</h3>
|
|
@@ -72,18 +100,38 @@
|
|
|
72
100
|
<br /><br />
|
|
73
101
|
|
|
74
102
|
</menu>
|
|
103
|
+
<k-aside-spacer></k-aside-spacer>
|
|
104
|
+
<k-theme-switcher
|
|
105
|
+
labels
|
|
106
|
+
style="--padding:var(--spacer_h);margin:var(--spacer_h) auto"
|
|
107
|
+
></k-theme-switcher>
|
|
75
108
|
</k-aside>
|
|
76
|
-
<script
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
<script
|
|
109
|
+
<script
|
|
110
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Aside.js"
|
|
111
|
+
type="module"
|
|
112
|
+
></script>
|
|
113
|
+
<script
|
|
114
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Main.js"
|
|
115
|
+
type="module"
|
|
116
|
+
></script>
|
|
117
|
+
<script
|
|
118
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Nav.js"
|
|
119
|
+
type="module"
|
|
120
|
+
></script>
|
|
121
|
+
<script
|
|
122
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Icon.js"
|
|
123
|
+
type="module"
|
|
124
|
+
></script>
|
|
125
|
+
<script
|
|
126
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/ThemeSwitcher.js"
|
|
127
|
+
type="module"
|
|
128
|
+
></script>
|
|
81
129
|
<script>
|
|
82
130
|
document.getElementById('toggleNavSideMenu').addEventListener('click', async () => {
|
|
83
131
|
await window.customElements.whenDefined('k-aside');
|
|
84
132
|
document.getElementById('navSideMenu').toggle();
|
|
85
133
|
});
|
|
86
|
-
document.addEventListener('click', function(e) {
|
|
134
|
+
document.addEventListener('click', function (e) {
|
|
87
135
|
if (e.target.matches('a[href^="#"]')) {
|
|
88
136
|
e.preventDefault();
|
|
89
137
|
const targetId = e.target.getAttribute('href').replace('#', '');
|
package/docs/cli-utils.html
CHANGED
|
@@ -37,13 +37,35 @@
|
|
|
37
37
|
class="d-if ph"
|
|
38
38
|
style="align-items: center"
|
|
39
39
|
>
|
|
40
|
-
<img
|
|
40
|
+
<img
|
|
41
|
+
src="./media/icon32.png"
|
|
42
|
+
alt="Kempo Server Icon"
|
|
43
|
+
class="pr"
|
|
44
|
+
/>
|
|
41
45
|
Kempo Server
|
|
42
46
|
</a>
|
|
43
47
|
<div class="flex"></div>
|
|
44
|
-
<a
|
|
45
|
-
|
|
46
|
-
|
|
48
|
+
<a
|
|
49
|
+
href="https://github.com/dustinpoissant/kempo-server?tab=License-1-ov-file#creative-commons-attribution-noncommercial-sharealike-20"
|
|
50
|
+
target="_blank"
|
|
51
|
+
><k-icon name="license"></k-icon></a>
|
|
52
|
+
<a
|
|
53
|
+
href="https://www.npmjs.com/package/kempo-server"
|
|
54
|
+
target="_blank"
|
|
55
|
+
><k-icon name="npm"></k-icon></a>
|
|
56
|
+
<a
|
|
57
|
+
href="https://github.com/dustinpoissant/kempo-server"
|
|
58
|
+
target="_blank"
|
|
59
|
+
><k-icon name="github-mark"></k-icon></a>
|
|
60
|
+
<k-theme-switcher
|
|
61
|
+
class="mr"
|
|
62
|
+
style="
|
|
63
|
+
--padding: 0.5rem;
|
|
64
|
+
--c_active: var(--tc_on_primary);
|
|
65
|
+
--tc_active: var(--c_primary);
|
|
66
|
+
--c_inactive__hover: rgba(255, 255, 255, 0.1);
|
|
67
|
+
"
|
|
68
|
+
></k-theme-switcher>
|
|
47
69
|
</k-nav>
|
|
48
70
|
<div style="width: 100%; height: 4rem;"></div>
|
|
49
71
|
<k-aside
|
|
@@ -51,9 +73,15 @@
|
|
|
51
73
|
state="offscreen"
|
|
52
74
|
>
|
|
53
75
|
<menu>
|
|
54
|
-
<a
|
|
76
|
+
<a
|
|
77
|
+
href="./"
|
|
78
|
+
class="ta-center bb mb r0"
|
|
79
|
+
>
|
|
55
80
|
<h1 class="tc-primary">Kempo Server</h1>
|
|
56
|
-
<img
|
|
81
|
+
<img
|
|
82
|
+
src="./media/icon128.png"
|
|
83
|
+
alt="Kempo UI Icon"
|
|
84
|
+
/>
|
|
57
85
|
</a>
|
|
58
86
|
|
|
59
87
|
<h3 class="mt mb0">Advanced Features</h3>
|
|
@@ -72,18 +100,38 @@
|
|
|
72
100
|
<br /><br />
|
|
73
101
|
|
|
74
102
|
</menu>
|
|
103
|
+
<k-aside-spacer></k-aside-spacer>
|
|
104
|
+
<k-theme-switcher
|
|
105
|
+
labels
|
|
106
|
+
style="--padding:var(--spacer_h);margin:var(--spacer_h) auto"
|
|
107
|
+
></k-theme-switcher>
|
|
75
108
|
</k-aside>
|
|
76
|
-
<script
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
<script
|
|
109
|
+
<script
|
|
110
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Aside.js"
|
|
111
|
+
type="module"
|
|
112
|
+
></script>
|
|
113
|
+
<script
|
|
114
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Main.js"
|
|
115
|
+
type="module"
|
|
116
|
+
></script>
|
|
117
|
+
<script
|
|
118
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Nav.js"
|
|
119
|
+
type="module"
|
|
120
|
+
></script>
|
|
121
|
+
<script
|
|
122
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Icon.js"
|
|
123
|
+
type="module"
|
|
124
|
+
></script>
|
|
125
|
+
<script
|
|
126
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/ThemeSwitcher.js"
|
|
127
|
+
type="module"
|
|
128
|
+
></script>
|
|
81
129
|
<script>
|
|
82
130
|
document.getElementById('toggleNavSideMenu').addEventListener('click', async () => {
|
|
83
131
|
await window.customElements.whenDefined('k-aside');
|
|
84
132
|
document.getElementById('navSideMenu').toggle();
|
|
85
133
|
});
|
|
86
|
-
document.addEventListener('click', function(e) {
|
|
134
|
+
document.addEventListener('click', function (e) {
|
|
87
135
|
if (e.target.matches('a[href^="#"]')) {
|
|
88
136
|
e.preventDefault();
|
|
89
137
|
const targetId = e.target.getAttribute('href').replace('#', '');
|
package/docs/configuration.html
CHANGED
|
@@ -37,13 +37,35 @@
|
|
|
37
37
|
class="d-if ph"
|
|
38
38
|
style="align-items: center"
|
|
39
39
|
>
|
|
40
|
-
<img
|
|
40
|
+
<img
|
|
41
|
+
src="./media/icon32.png"
|
|
42
|
+
alt="Kempo Server Icon"
|
|
43
|
+
class="pr"
|
|
44
|
+
/>
|
|
41
45
|
Kempo Server
|
|
42
46
|
</a>
|
|
43
47
|
<div class="flex"></div>
|
|
44
|
-
<a
|
|
45
|
-
|
|
46
|
-
|
|
48
|
+
<a
|
|
49
|
+
href="https://github.com/dustinpoissant/kempo-server?tab=License-1-ov-file#creative-commons-attribution-noncommercial-sharealike-20"
|
|
50
|
+
target="_blank"
|
|
51
|
+
><k-icon name="license"></k-icon></a>
|
|
52
|
+
<a
|
|
53
|
+
href="https://www.npmjs.com/package/kempo-server"
|
|
54
|
+
target="_blank"
|
|
55
|
+
><k-icon name="npm"></k-icon></a>
|
|
56
|
+
<a
|
|
57
|
+
href="https://github.com/dustinpoissant/kempo-server"
|
|
58
|
+
target="_blank"
|
|
59
|
+
><k-icon name="github-mark"></k-icon></a>
|
|
60
|
+
<k-theme-switcher
|
|
61
|
+
class="mr"
|
|
62
|
+
style="
|
|
63
|
+
--padding: 0.5rem;
|
|
64
|
+
--c_active: var(--tc_on_primary);
|
|
65
|
+
--tc_active: var(--c_primary);
|
|
66
|
+
--c_inactive__hover: rgba(255, 255, 255, 0.1);
|
|
67
|
+
"
|
|
68
|
+
></k-theme-switcher>
|
|
47
69
|
</k-nav>
|
|
48
70
|
<div style="width: 100%; height: 4rem;"></div>
|
|
49
71
|
<k-aside
|
|
@@ -51,9 +73,15 @@
|
|
|
51
73
|
state="offscreen"
|
|
52
74
|
>
|
|
53
75
|
<menu>
|
|
54
|
-
<a
|
|
76
|
+
<a
|
|
77
|
+
href="./"
|
|
78
|
+
class="ta-center bb mb r0"
|
|
79
|
+
>
|
|
55
80
|
<h1 class="tc-primary">Kempo Server</h1>
|
|
56
|
-
<img
|
|
81
|
+
<img
|
|
82
|
+
src="./media/icon128.png"
|
|
83
|
+
alt="Kempo UI Icon"
|
|
84
|
+
/>
|
|
57
85
|
</a>
|
|
58
86
|
|
|
59
87
|
<h3 class="mt mb0">Advanced Features</h3>
|
|
@@ -72,18 +100,38 @@
|
|
|
72
100
|
<br /><br />
|
|
73
101
|
|
|
74
102
|
</menu>
|
|
103
|
+
<k-aside-spacer></k-aside-spacer>
|
|
104
|
+
<k-theme-switcher
|
|
105
|
+
labels
|
|
106
|
+
style="--padding:var(--spacer_h);margin:var(--spacer_h) auto"
|
|
107
|
+
></k-theme-switcher>
|
|
75
108
|
</k-aside>
|
|
76
|
-
<script
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
<script
|
|
109
|
+
<script
|
|
110
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Aside.js"
|
|
111
|
+
type="module"
|
|
112
|
+
></script>
|
|
113
|
+
<script
|
|
114
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Main.js"
|
|
115
|
+
type="module"
|
|
116
|
+
></script>
|
|
117
|
+
<script
|
|
118
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Nav.js"
|
|
119
|
+
type="module"
|
|
120
|
+
></script>
|
|
121
|
+
<script
|
|
122
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Icon.js"
|
|
123
|
+
type="module"
|
|
124
|
+
></script>
|
|
125
|
+
<script
|
|
126
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/ThemeSwitcher.js"
|
|
127
|
+
type="module"
|
|
128
|
+
></script>
|
|
81
129
|
<script>
|
|
82
130
|
document.getElementById('toggleNavSideMenu').addEventListener('click', async () => {
|
|
83
131
|
await window.customElements.whenDefined('k-aside');
|
|
84
132
|
document.getElementById('navSideMenu').toggle();
|
|
85
133
|
});
|
|
86
|
-
document.addEventListener('click', function(e) {
|
|
134
|
+
document.addEventListener('click', function (e) {
|
|
87
135
|
if (e.target.matches('a[href^="#"]')) {
|
|
88
136
|
e.preventDefault();
|
|
89
137
|
const targetId = e.target.getAttribute('href').replace('#', '');
|
package/docs/examples.html
CHANGED
|
@@ -37,13 +37,35 @@
|
|
|
37
37
|
class="d-if ph"
|
|
38
38
|
style="align-items: center"
|
|
39
39
|
>
|
|
40
|
-
<img
|
|
40
|
+
<img
|
|
41
|
+
src="./media/icon32.png"
|
|
42
|
+
alt="Kempo Server Icon"
|
|
43
|
+
class="pr"
|
|
44
|
+
/>
|
|
41
45
|
Kempo Server
|
|
42
46
|
</a>
|
|
43
47
|
<div class="flex"></div>
|
|
44
|
-
<a
|
|
45
|
-
|
|
46
|
-
|
|
48
|
+
<a
|
|
49
|
+
href="https://github.com/dustinpoissant/kempo-server?tab=License-1-ov-file#creative-commons-attribution-noncommercial-sharealike-20"
|
|
50
|
+
target="_blank"
|
|
51
|
+
><k-icon name="license"></k-icon></a>
|
|
52
|
+
<a
|
|
53
|
+
href="https://www.npmjs.com/package/kempo-server"
|
|
54
|
+
target="_blank"
|
|
55
|
+
><k-icon name="npm"></k-icon></a>
|
|
56
|
+
<a
|
|
57
|
+
href="https://github.com/dustinpoissant/kempo-server"
|
|
58
|
+
target="_blank"
|
|
59
|
+
><k-icon name="github-mark"></k-icon></a>
|
|
60
|
+
<k-theme-switcher
|
|
61
|
+
class="mr"
|
|
62
|
+
style="
|
|
63
|
+
--padding: 0.5rem;
|
|
64
|
+
--c_active: var(--tc_on_primary);
|
|
65
|
+
--tc_active: var(--c_primary);
|
|
66
|
+
--c_inactive__hover: rgba(255, 255, 255, 0.1);
|
|
67
|
+
"
|
|
68
|
+
></k-theme-switcher>
|
|
47
69
|
</k-nav>
|
|
48
70
|
<div style="width: 100%; height: 4rem;"></div>
|
|
49
71
|
<k-aside
|
|
@@ -51,9 +73,15 @@
|
|
|
51
73
|
state="offscreen"
|
|
52
74
|
>
|
|
53
75
|
<menu>
|
|
54
|
-
<a
|
|
76
|
+
<a
|
|
77
|
+
href="./"
|
|
78
|
+
class="ta-center bb mb r0"
|
|
79
|
+
>
|
|
55
80
|
<h1 class="tc-primary">Kempo Server</h1>
|
|
56
|
-
<img
|
|
81
|
+
<img
|
|
82
|
+
src="./media/icon128.png"
|
|
83
|
+
alt="Kempo UI Icon"
|
|
84
|
+
/>
|
|
57
85
|
</a>
|
|
58
86
|
|
|
59
87
|
<h3 class="mt mb0">Advanced Features</h3>
|
|
@@ -72,18 +100,38 @@
|
|
|
72
100
|
<br /><br />
|
|
73
101
|
|
|
74
102
|
</menu>
|
|
103
|
+
<k-aside-spacer></k-aside-spacer>
|
|
104
|
+
<k-theme-switcher
|
|
105
|
+
labels
|
|
106
|
+
style="--padding:var(--spacer_h);margin:var(--spacer_h) auto"
|
|
107
|
+
></k-theme-switcher>
|
|
75
108
|
</k-aside>
|
|
76
|
-
<script
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
<script
|
|
109
|
+
<script
|
|
110
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Aside.js"
|
|
111
|
+
type="module"
|
|
112
|
+
></script>
|
|
113
|
+
<script
|
|
114
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Main.js"
|
|
115
|
+
type="module"
|
|
116
|
+
></script>
|
|
117
|
+
<script
|
|
118
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Nav.js"
|
|
119
|
+
type="module"
|
|
120
|
+
></script>
|
|
121
|
+
<script
|
|
122
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/Icon.js"
|
|
123
|
+
type="module"
|
|
124
|
+
></script>
|
|
125
|
+
<script
|
|
126
|
+
src="https://cdn.jsdelivr.net/npm/kempo-ui@0.3/src/components/ThemeSwitcher.js"
|
|
127
|
+
type="module"
|
|
128
|
+
></script>
|
|
81
129
|
<script>
|
|
82
130
|
document.getElementById('toggleNavSideMenu').addEventListener('click', async () => {
|
|
83
131
|
await window.customElements.whenDefined('k-aside');
|
|
84
132
|
document.getElementById('navSideMenu').toggle();
|
|
85
133
|
});
|
|
86
|
-
document.addEventListener('click', function(e) {
|
|
134
|
+
document.addEventListener('click', function (e) {
|
|
87
135
|
if (e.target.matches('a[href^="#"]')) {
|
|
88
136
|
e.preventDefault();
|
|
89
137
|
const targetId = e.target.getAttribute('href').replace('#', '');
|