kempo-server 1.0.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.
@@ -0,0 +1,343 @@
1
+ <html lang="en" theme="auto">
2
+ <head>
3
+ <meta charset='utf-8'>
4
+ <meta http-equiv='X-UA-Compatible' content='IE=edge'>
5
+ <title>Kempo Server - Documentation</title>
6
+ <meta name='viewport' content='width=device-width, initial-scale=1'>
7
+ <link rel="stylesheet" href="/essential.css" />
8
+ </head>
9
+ <body>
10
+ <main>
11
+ <h1 class="ta-center">Kempo Server</h1>
12
+ <p>A lightweight, zero-dependency, file based routing server.</p>
13
+
14
+ <details class="b r mb">
15
+ <summary class="p">Table of Contents</summary>
16
+ <hr class="m0 mb" />
17
+ <ul class="mt ml pl">
18
+ <li><a href="#gettingStarted">Getting Started</a></li>
19
+ <li>
20
+ <a href="#routes">Routes</a>
21
+ <ul>
22
+ <li><a href="#htmlRoutes">HTML Routes</a></li>
23
+ <li><a href="#dynamicRoutes">Dynamic Routes</a></li>
24
+ <li><a href="#request">Request Object</a></li>
25
+ <li><a href="#response">Response Object</a></li>
26
+ </ul>
27
+ </li>
28
+ <li>
29
+ <a href="#config">Configuration</a>
30
+ <ul>
31
+ <li><a href="#allowedMimes">allowedMimes</a></li>
32
+ <li><a href="#disallowedRegex">disallowedRegex</a></li>
33
+ <li><a href="#routeFiles">routeFiles</a></li>
34
+ <li><a href="#noRescanPaths">noRescanPaths</a></li>
35
+ <li><a href="#customRoutes">customRoutes</a></li>
36
+ <li><a href="#maxRescanAttempts">maxRescanAttempts</a></li>
37
+ </ul>
38
+ </li>
39
+ <li><a href="#features">Features</a></li>
40
+ <li><a href="#examples">Examples</a></li>
41
+ <li><a href="#cli">Command Line Options</a></li>
42
+ <li><a href="#demos">Live Demos</a></li>
43
+ </ul>
44
+ </details>
45
+
46
+ <h3 id="gettingStarted">Getting Started</h3>
47
+ <p>1. Install the npm package.</p>
48
+ <pre><code>npm install kempo-server</code></pre>
49
+ <p>2. Add it to your <code>package.json</code> scripts, use the <code>--root</code> flag to tell it where the root of your site is.</p>
50
+ <pre><code class="hljs json">{<br /> ...<br /> <span class="hljs-attr">"scripts"</span>: {<br /> <span class="hljs-attr">"start"</span>: <span class="hljs-string">"kempo-server --root public"</span><br /> }<br /> ...<br />}</code></pre>
51
+ <p>3. Run it in your terminal.</p>
52
+ <pre><code>npm run start</code></pre>
53
+
54
+ <h3 id="routes">Routes</h3>
55
+ <p>A route is a request to a directory that will be handled by a file. To define routes, create the directory structure to the route and create a file with the name of the method that this file will handle. For example <code>GET.js</code> will handle the <code>GET</code> requests, <code>POST.js</code> will handle the <code>POST</code> requests and so on. Use <code>index.js</code> to handle all request types.</p>
56
+ <p>The Javascript file must have a <b>default</b> export that is the function that will handle the request. It will be passed a <code>request</code> object and a <code>response</code> object (See <a href="#request">Request Object</a> below).</p>
57
+ <p>For example this directory structure:</p>
58
+ <pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br /></code></pre>
59
+ <p>Would be used to handle <code>GET my/route/</code>, <code>POST my/route/</code> and <code>GET my/other/route/</code></p>
60
+
61
+ <h5 id="htmlRoutes">HTML Routes</h5>
62
+ <p>Just like JS files, HTML files can be used to define a route. Use <code>GET.html</code>, <code>POST.html</code>, ect... to define files that will be served when that route is requested.</p>
63
+ <pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br />│ ├─ POST.html<br />│ ├─ GET.html<br /></code></pre>
64
+ <h5><code>index</code> fallbacks</h5>
65
+ <p><code>index.js</code> or <code>index.html</code> will be used as a fallback for all routes if a <i>method</i> file is not defined. In the above examples we do not have any routes defined for <code>DELETE</code>, <code>PUT</code> <code>PATCH</code>, ect... so lets use an <code>index.js</code> and <code>index.html</code> to be a "catch-all" for all the methods we have not created handlers for.</p>
66
+ <pre><code class="hljs markdown">my/<br />├─ route/<br />│ ├─ GET.js<br />│ ├─ POST.js<br />│ ├─ index.js<br />├─ other/<br />│ ├─ route/<br />│ │ ├─ GET.js<br />│ │ ├─ index.js<br />│ ├─ POST.html<br />│ ├─ GET.html<br />│ ├─ index.html<br />├─ index.hml<br /></code></pre>
67
+
68
+ <h3 id="dynamicRoutes">Dynamic Routes</h3>
69
+ <p>A dynamic route is a route with a "param" in its path. To define the dynamic parts of the route just wrap the directory name in square brackets. For example if you wanted to get a users profile, or perform CRUD operations on a user you might create the following directory structure.</p>
70
+ <pre><code class="hljs markdown">api/<br />├─ user/<br />│ ├─ [id]/<br />│ │ ├─ [info]/<br />│ │ │ ├─ GET.js<br />│ │ │ ├─ DELETE.js<br />│ │ │ ├─ PUT.js<br />│ │ │ ├─ POST.js<br />│ │ ├─ GET.js<br /></code></pre>
71
+ <p>When a request is made to <code>/api/user/123/info</code>, the route file <code>api/user/[id]/[info]/GET.js</code> would be executed and receive an request object with <code>request.params</code> containing <code>{ id: "123", info: "info" }</code>.</p>
72
+
73
+ <h3 id="request">Request Object</h3>
74
+ <p>Kempo Server provides a request object that makes working with HTTP requests easier:</p>
75
+
76
+ <h4>Properties</h4>
77
+ <ul>
78
+ <li><code>request.params</code> - Route parameters from dynamic routes (e.g., <code>{ id: "123", info: "info" }</code>)</li>
79
+ <li><code>request.query</code> - Query string parameters as an object (e.g., <code>{ page: "1", limit: "10" }</code>)</li>
80
+ <li><code>request.path</code> - The pathname of the request URL</li>
81
+ <li><code>request.method</code> - HTTP method (GET, POST, etc.)</li>
82
+ <li><code>request.headers</code> - Request headers object</li>
83
+ <li><code>request.url</code> - Full request URL</li>
84
+ </ul>
85
+
86
+ <h4>Methods</h4>
87
+ <ul>
88
+ <li><code>await request.json()</code> - Parse request body as JSON</li>
89
+ <li><code>await request.text()</code> - Get request body as text</li>
90
+ <li><code>await request.body()</code> - Get raw request body as string</li>
91
+ <li><code>await request.buffer()</code> - Get request body as Buffer</li>
92
+ <li><code>request.get(headerName)</code> - Get specific header value</li>
93
+ <li><code>request.is(type)</code> - Check if content-type contains specified type</li>
94
+ </ul>
95
+
96
+ <h3 id="response">Response Object</h3>
97
+ <p>Kempo Server also provides a response object that makes sending responses easier:</p>
98
+
99
+ <h4>Methods</h4>
100
+ <ul>
101
+ <li><code>response.json(object)</code> - Send JSON response with automatic content-type</li>
102
+ <li><code>response.send(data)</code> - Send response (auto-detects content type)</liI >
103
+ <li><code>response.html(htmlString)</code> - Send HTML response</li>
104
+ <li><code>response.text(textString)</code> - Send plain text response</li>
105
+ <li><code>response.status(code)</code> - Set status code (chainable)</li>
106
+ <li><code>response.set(field, value)</code> - Set header (chainable)</li>
107
+ <li><code>response.type(contentType)</code> - Set content type (chainable)</li>
108
+ <li><code>response.redirect(url, statusCode)</code> - Redirect to URL</li>
109
+ <li><code>response.cookie(name, value, options)</code> - Set cookie</li>
110
+ <li><code>response.clearCookie(name, options)</code> - Clear cookie</li>
111
+ </ul>
112
+
113
+ <h4>Example Route File</h4>
114
+ <p>Here's an example of what a route file might look like:</p>
115
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <span class="hljs-keyword">const</span> { includeDetails } = request.query;<br /> <br /> <span class="hljs-comment">// Fetch user data from database</span><br /> <span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> getUserById(id);<br /> <br /> <span class="hljs-keyword">if</span> (!userData) {<br /> <span class="hljs-keyword">return</span> response.status(<span class="hljs-number">404</span>).json({ error: <span class="hljs-string">'User not found'</span> });<br /> }<br /> <br /> response.json(userData);<br />}</code></pre>
116
+
117
+ <h4>POST Request Example</h4>
118
+ <p>Here's an example of handling JSON data in a POST request:</p>
119
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> updateData = <span class="hljs-keyword">await</span> request.json();<br /> <br /> <span class="hljs-comment">// Update user in database</span><br /> <span class="hljs-keyword">const</span> updatedUser = <span class="hljs-keyword">await</span> updateUser(id, updateData);<br /> <br /> response.json(updatedUser);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).json({ error: <span class="hljs-string">'Invalid JSON'</span> });<br /> }<br />}</code></pre>
120
+
121
+ <h4>Response Methods Examples</h4>
122
+ <p>The response object supports multiple ways to send responses:</p>
123
+ <pre><code class="hljs javascript"><span class="hljs-comment">// Different response types</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-comment">// JSON response</span><br /> response.json({ message: <span class="hljs-string">'Hello World'</span> });<br /> <br /> <span class="hljs-comment">// HTML response</span><br /> response.html(<span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>);<br /> <br /> <span class="hljs-comment">// Text response</span><br /> response.text(<span class="hljs-string">'Hello World'</span>);<br /> <br /> <span class="hljs-comment">// Status code chaining</span><br /> response.status(<span class="hljs-number">201</span>).json({ created: <span class="hljs-literal">true</span> });<br /> <br /> <span class="hljs-comment">// Custom headers</span><br /> response.set(<span class="hljs-string">'X-Custom-Header'</span>, <span class="hljs-string">'value'</span>).json({ data: <span class="hljs-string">'test'</span> });<br /> <br /> <span class="hljs-comment">// Redirect</span><br /> response.redirect(<span class="hljs-string">'/login'</span>);<br /> <br /> <span class="hljs-comment">// Set cookies</span><br /> response.cookie(<span class="hljs-string">'session'</span>, <span class="hljs-string">'abc123'</span>, { httpOnly: <span class="hljs-literal">true</span> }).json({ success: <span class="hljs-literal">true</span> });<br />}</code></pre>
124
+
125
+ <h3 id="config">Configuration</h3>
126
+ <p>To configure the server create a <code>.config.json</code> within the root directory of your server (<code>public</code> in the start example <a href="#gettingStarted">above</a>).</p>
127
+ <p>This json file can have any of the following 6 properties, any property not defined will use the "Default Config".</p>
128
+ <ul>
129
+ <li><a href="#allowedMimes">allowedMimes</a></li>
130
+ <li><a href="#disallowedRegex">disallowedRegex</a></li>
131
+ <li><a href="#customRoutes">customRoutes</a></li>
132
+ <li><a href="#routeFiles">routeFiles</a></li>
133
+ <li><a href="#noRescanPaths">noRescanPaths</a></li>
134
+ <li><a href="#maxRescanAttempts">maxRescanAttempts</a></li>
135
+ </ul>
136
+
137
+ <h4 id="allowedMimes">allowedMimes</h4>
138
+ <p>An object mapping file extensions to their MIME types. Files with extensions not in this list will not be served.</p>
139
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"allowedMimes"</span>: {<br /> <span class="hljs-attr">"html"</span>: <span class="hljs-string">"text/html"</span>,<br /> <span class="hljs-attr">"css"</span>: <span class="hljs-string">"text/css"</span>,<br /> <span class="hljs-attr">"js"</span>: <span class="hljs-string">"application/javascript"</span>,<br /> <span class="hljs-attr">"json"</span>: <span class="hljs-string">"application/json"</span>,<br /> <span class="hljs-attr">"png"</span>: <span class="hljs-string">"image/png"</span>,<br /> <span class="hljs-attr">"jpg"</span>: <span class="hljs-string">"image/jpeg"</span><br /> }<br />}</code></pre>
140
+
141
+ <h4 id="disallowedRegex">disallowedRegex</h4>
142
+ <p>An array of regular expressions that match paths that should never be served. This provides security by preventing access to sensitive files.</p>
143
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"disallowedRegex"</span>: [<br /> <span class="hljs-string">"^/\\..*"</span>,<br /> <span class="hljs-string">"\\.env$"</span>,<br /> <span class="hljs-string">"\\.config$"</span>,<br /> <span class="hljs-string">"password"</span><br /> ]<br />}</code></pre>
144
+
145
+ <h4 id="routeFiles">routeFiles</h4>
146
+ <p>An array of filenames that should be treated as route handlers and executed as JavaScript modules.</p>
147
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"routeFiles"</span>: [<br /> <span class="hljs-string">"GET.js"</span>,<br /> <span class="hljs-string">"POST.js"</span>,<br /> <span class="hljs-string">"PUT.js"</span>,<br /> <span class="hljs-string">"DELETE.js"</span>,<br /> <span class="hljs-string">"index.js"</span><br /> ]<br />}</code></pre>
148
+
149
+ <h4 id="noRescanPaths">noRescanPaths</h4>
150
+ <p>An array of regex patterns for paths that should not trigger a file system rescan. This improves performance for common static assets.</p>
151
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"noRescanPaths"</span>: [<br /> <span class="hljs-string">"/favicon\\.ico$"</span>,<br /> <span class="hljs-string">"/robots\\.txt$"</span>,<br /> <span class="hljs-string">"\\.map$"</span><br /> ]<br />}</code></pre>
152
+
153
+ <h4 id="customRoutes">customRoutes</h4>
154
+ <p>An object mapping custom route paths to file paths. Useful for aliasing or serving files from outside the document root.</p>
155
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"customRoutes"</span>: {<br /> <span class="hljs-attr">"/vendor/bootstrap.css"</span>: <span class="hljs-string">"./node_modules/bootstrap/dist/css/bootstrap.min.css"</span>,<br /> <span class="hljs-attr">"/api/status"</span>: <span class="hljs-string">"./status.js"</span><br /> }<br />}</code></pre>
156
+
157
+ <h4 id="maxRescanAttempts">maxRescanAttempts</h4>
158
+ <p>The maximum number of times to attempt rescanning the file system when a file is not found. Defaults to 3.</p>
159
+ <pre><code class="hljs json">{<br /> <span class="hljs-attr">"maxRescanAttempts"</span>: <span class="hljs-number">3</span><br />}</code></pre>
160
+
161
+ <h3 id="features">Features</h3>
162
+ <ul>
163
+ <li><strong>Zero Dependencies</strong> - No external dependencies required</li>
164
+ <li><strong>File-based Routing</strong> - Routes are defined by your directory structure</li>
165
+ <li><strong>Dynamic Routes</strong> - Support for parameterized routes with square bracket syntax</li>
166
+ <li><strong>Multiple HTTP Methods</strong> - Support for GET, POST, PUT, DELETE, and more</li>
167
+ <li><strong>Static File Serving</strong> - Automatically serves static files with proper MIME types</li>
168
+ <li><strong>HTML Routes</strong> - Support for both JavaScript and HTML route handlers</li>
169
+ <li><strong>Configurable</strong> - Customize behavior with a simple JSON config file</li>
170
+ <li><strong>Security</strong> - Built-in protection against serving sensitive files</li>
171
+ <li><strong>Performance</strong> - Smart file system caching and rescan optimization</li>
172
+ </ul>
173
+
174
+ <h3 id="examples">Examples</h3>
175
+
176
+ <h4>Simple API Route</h4>
177
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/hello/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { name } = request.query;<br /> <span class="hljs-keyword">const</span> message = name ? <span class="hljs-string">`Hello ${name}!`</span> : <span class="hljs-string">'Hello World!'</span>;<br /> <br /> response.json({ message });<br />}</code></pre>
178
+
179
+ <h4>Dynamic User Profile Route</h4>
180
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/users/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <span class="hljs-keyword">const</span> { includeProfile } = request.query;<br /> <br /> <span class="hljs-comment">// Simulate database lookup</span><br /> <span class="hljs-keyword">const</span> user = {<br /> id: id,<br /> name: <span class="hljs-string">`User ${id}`</span>,<br /> email: <span class="hljs-string">`user${id}@example.com`</span><br /> };<br /> <br /> <span class="hljs-keyword">if</span> (includeProfile === <span class="hljs-string">'true'</span>) {<br /> user.profile = {<br /> bio: <span class="hljs-string">`Bio for user ${id}`</span>,<br /> joinDate: <span class="hljs-string">'2024-01-01'</span><br /> };<br /> }<br /> <br /> response.json(user);<br />}</code></pre>
181
+
182
+ <h4>Form Handling Route</h4>
183
+ <pre><code class="hljs javascript"><span class="hljs-comment">// contact/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> body = <span class="hljs-keyword">await</span> request.text();<br /> <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> URLSearchParams(body);<br /> <span class="hljs-keyword">const</span> name = formData.get(<span class="hljs-string">'name'</span>);<br /> <span class="hljs-keyword">const</span> email = formData.get(<span class="hljs-string">'email'</span>);<br /> <br /> <span class="hljs-comment">// Process form data...</span><br /> <br /> response.html(<span class="hljs-string">'&lt;h1&gt;Thank you for your message!&lt;/h1&gt;'</span>);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).html(<span class="hljs-string">'&lt;h1&gt;Error processing form&lt;/h1&gt;'</span>);<br /> }<br />}</code></pre>
184
+
185
+ <h3 id="cli">Command Line Options</h3>
186
+ <p>Kempo Server supports several command line options to customize its behavior:</p>
187
+ <ul>
188
+ <li><code>--root &lt;path&gt;</code> - Set the document root directory (required)</li>
189
+ <li><code>--port &lt;number&gt;</code> - Set the port number (default: 3000)</li>
190
+ <li><code>--host &lt;address&gt;</code> - Set the host address (default: localhost)</li>
191
+ <li><code>--verbose</code> - Enable verbose logging</li>
192
+ </ul>
193
+
194
+ <pre><code>kempo-server --root public --port 8080 --host 0.0.0.0 --verbose</code></pre>
195
+
196
+ <h3 id="demos">Live Demos</h3>
197
+ <p>Try out the example API endpoints below. These demonstrations show the actual routes working in this documentation site.</p>
198
+
199
+ <div class="mb">
200
+ <h4 class="mt0">Get User Profile</h4>
201
+ <p><code>GET /api/user/[id]</code></p>
202
+ <div class="row -mx">
203
+ <div class="col m-span-12 d-span-6 px">
204
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id } = request.params;<br /> <br /> <span class="hljs-keyword">const</span> userData = {<br /> id: id,<br /> profile: {<br /> name: <span class="hljs-string">`${id.charAt(0).toUpperCase()}${id.slice(1)}`</span>,<br /> joinDate: <span class="hljs-string">'2024-01-15'</span>,<br /> posts: <span class="hljs-number">42</span><br /> }<br /> };<br /> <br /> response.json(userData);<br />}</code></pre>
205
+ <div class="mb">
206
+ <input type="text" id="userId" placeholder="Enter user ID (e.g., john)" value="john" class="mb mr">
207
+ <button onclick="fetchUser()" class="primary">GET User</button>
208
+ </div>
209
+ </div>
210
+ <div class="col m-span-12 d-span-6 px">
211
+ <h5>Response:</h5>
212
+ <pre><output id="userOutput" class="pb">Click "GET User" to see the response</output></pre>
213
+ </div>
214
+ </div>
215
+ </div>
216
+
217
+ <div class="mb">
218
+ <h4 class="mt0">Get User Info</h4>
219
+ <p><code>GET /api/user/[id]/[info]</code></p>
220
+ <div class="row -mx">
221
+ <div class="col m-span-12 d-span-6 px">
222
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/[info]/GET.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id, info } = request.params;<br /> <br /> <span class="hljs-keyword">const</span> userInfo = {<br /> id: id,<br /> details: {<br /> bio: <span class="hljs-string">`This is ${id}'s bio`</span>,<br /> location: <span class="hljs-string">'Earth'</span>,<br /> website: <span class="hljs-string">`https://${id}.dev`</span>,<br /> followers: <span class="hljs-number">123</span>,<br /> following: <span class="hljs-number">456</span><br /> }<br /> };<br /> <br /> response.json(userInfo);<br />}</code></pre>
223
+ <div class="mb">
224
+ <input type="text" id="userInfoId" placeholder="Enter user ID" value="alice" class="mb mr">
225
+ <button onclick="fetchUserInfo()" class="primary">GET User Info</button>
226
+ </div>
227
+ </div>
228
+ <div class="col m-span-12 d-span-6 px">
229
+ <h5>Response:</h5>
230
+ <pre><output id="userInfoOutput" class="pb">Click "GET User Info" to see the response</output></pre>
231
+ </div>
232
+ </div>
233
+ </div>
234
+
235
+ <div class="mb">
236
+ <h4 class="mt0">Update User Info</h4>
237
+ <p><code>POST /api/user/[id]/[info]</code></p>
238
+ <div class="row -mx">
239
+ <div class="col m-span-12 d-span-6 px">
240
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/[info]/POST.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id, info } = request.params;<br /> <br /> <span class="hljs-keyword">try</span> {<br /> <span class="hljs-keyword">const</span> updateData = <span class="hljs-keyword">await</span> request.json();<br /> <br /> <span class="hljs-keyword">const</span> updatedUser = {<br /> id: id,<br /> message: <span class="hljs-string">'User info updated successfully'</span>,<br /> updatedFields: updateData<br /> };<br /> <br /> response.json(updatedUser);<br /> } <span class="hljs-keyword">catch</span> (error) {<br /> response.status(<span class="hljs-number">400</span>).json({ error: <span class="hljs-string">'Invalid JSON'</span> });<br /> }<br />}</code></pre>
241
+ <div class="mb">
242
+ <input type="text" id="postUserId" placeholder="Enter user ID" value="bob" class="mb">
243
+ <textarea id="postData" placeholder="Enter JSON data to update" class="mb">{
244
+ "bio": "Updated bio text",
245
+ "location": "New York"
246
+ }</textarea>
247
+ <button onclick="updateUserInfo()" class="primary">POST Update</button>
248
+ </div>
249
+ </div>
250
+ <div class="col m-span-12 d-span-6 px">
251
+ <h5>Response:</h5>
252
+ <pre><output id="postOutput" class="pb">Click "POST Update" to see the response</output></pre>
253
+ </div>
254
+ </div>
255
+ </div>
256
+
257
+ <div class="mb">
258
+ <h4 class="mt0">Delete User Info</h4>
259
+ <p><code>DELETE /api/user/[id]/[info]</code></p>
260
+ <div class="row -mx">
261
+ <div class="col m-span-12 d-span-6 px">
262
+ <pre><code class="hljs javascript"><span class="hljs-comment">// api/user/[id]/[info]/DELETE.js</span><br /><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">request, response</span>) </span>{<br /> <span class="hljs-keyword">const</span> { id, info } = request.params;<br /> <br /> <span class="hljs-keyword">const</span> result = {<br /> id: id,<br /> message: <span class="hljs-string">'User info deleted successfully'</span>,<br /> deletedAt: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString()<br /> };<br /> <br /> response.json(result);<br />}</code></pre>
263
+ <div class="mb">
264
+ <input type="text" id="deleteUserId" placeholder="Enter user ID" value="charlie" class="mr">
265
+ <button onclick="deleteUserInfo()" class="primary">DELETE Info</button>
266
+ </div>
267
+ </div>
268
+ <div class="col m-span-12 d-span-6 px">
269
+ <h5>Response:</h5>
270
+ <pre><output id="deleteOutput" class="pb">Click "DELETE Info" to see the response</output></pre>
271
+ </div>
272
+ </div>
273
+ </div>
274
+
275
+ <script>
276
+ async function fetchUser() {
277
+ const userId = document.getElementById('userId').value || 'john';
278
+ const output = document.getElementById('userOutput');
279
+
280
+ try {
281
+ output.textContent = 'Loading...';
282
+ const response = await fetch(`/api/user/${userId}`);
283
+ const data = await response.json();
284
+ output.textContent = JSON.stringify(data, null, 2);
285
+ } catch (error) {
286
+ output.textContent = `Error: ${error.message}`;
287
+ }
288
+ }
289
+
290
+ async function fetchUserInfo() {
291
+ const userId = document.getElementById('userInfoId').value || 'alice';
292
+ const output = document.getElementById('userInfoOutput');
293
+
294
+ try {
295
+ output.textContent = 'Loading...';
296
+ const response = await fetch(`/api/user/${userId}/info`);
297
+ const data = await response.json();
298
+ output.textContent = JSON.stringify(data, null, 2);
299
+ } catch (error) {
300
+ output.textContent = `Error: ${error.message}`;
301
+ }
302
+ }
303
+
304
+ async function updateUserInfo() {
305
+ const userId = document.getElementById('postUserId').value || 'bob';
306
+ const postData = document.getElementById('postData').value;
307
+ const output = document.getElementById('postOutput');
308
+
309
+ try {
310
+ output.textContent = 'Loading...';
311
+ const response = await fetch(`/api/user/${userId}/info`, {
312
+ method: 'POST',
313
+ headers: {
314
+ 'Content-Type': 'application/json',
315
+ },
316
+ body: postData
317
+ });
318
+ const data = await response.json();
319
+ output.textContent = JSON.stringify(data, null, 2);
320
+ } catch (error) {
321
+ output.textContent = `Error: ${error.message}`;
322
+ }
323
+ }
324
+
325
+ async function deleteUserInfo() {
326
+ const userId = document.getElementById('deleteUserId').value || 'charlie';
327
+ const output = document.getElementById('deleteOutput');
328
+
329
+ try {
330
+ output.textContent = 'Loading...';
331
+ const response = await fetch(`/api/user/${userId}/info`, {
332
+ method: 'DELETE'
333
+ });
334
+ const data = await response.json();
335
+ output.textContent = JSON.stringify(data, null, 2);
336
+ } catch (error) {
337
+ output.textContent = `Error: ${error.message}`;
338
+ }
339
+ }
340
+ </script>
341
+ </main>
342
+ </body>
343
+ </html>
package/findFile.js ADDED
@@ -0,0 +1,139 @@
1
+ import path from 'path';
2
+
3
+ export default (files, rootPath, requestPath, method, log) => {
4
+ log(`Finding file for: ${method} ${requestPath}`, 3);
5
+
6
+ // Normalize paths for comparison
7
+ const normalizeRequestPath = requestPath.startsWith('/') ? requestPath.slice(1) : requestPath;
8
+ const requestSegments = normalizeRequestPath ? normalizeRequestPath.split('/') : [];
9
+
10
+ log(`Normalized request path: ${normalizeRequestPath}`, 4);
11
+ log(`Request segments: [${requestSegments.join(', ')}]`, 4);
12
+
13
+ // Helper function to check if a segment is dynamic (wrapped in brackets)
14
+ const isDynamicSegment = (segment) => segment.startsWith('[') && segment.endsWith(']');
15
+
16
+ // Helper function to extract parameter name from dynamic segment
17
+ const getParamName = (segment) => segment.slice(1, -1);
18
+
19
+ // Helper function to normalize file paths for comparison
20
+ const getRelativePath = (filePath) => {
21
+ const relative = path.relative(rootPath, filePath);
22
+ return relative.replace(/\\/g, '/');
23
+ };
24
+
25
+ // Check for exact file match
26
+ const exactMatch = files.find(file => {
27
+ const relativePath = getRelativePath(file);
28
+ return relativePath === normalizeRequestPath;
29
+ });
30
+
31
+ if (exactMatch) {
32
+ log(`Found exact match: ${exactMatch}`, 2);
33
+ return [exactMatch, {}];
34
+ }
35
+
36
+ // Look for directory index files if request ends with / or is empty
37
+ const isDirectoryRequest = requestPath === '/' || requestPath.endsWith('/') || !path.extname(requestPath);
38
+
39
+ if (isDirectoryRequest) {
40
+ log(`Processing directory request`, 3);
41
+ const dirPath = normalizeRequestPath || '';
42
+ const methodUpper = method.toUpperCase();
43
+
44
+ // Priority order: METHOD.js, METHOD.html, index.js, index.html
45
+ const indexFiles = [
46
+ `${methodUpper}.js`,
47
+ `${methodUpper}.html`,
48
+ 'index.js',
49
+ 'index.html'
50
+ ];
51
+
52
+ log(`Looking for index files: [${indexFiles.join(', ')}]`, 3);
53
+
54
+ for (const indexFile of indexFiles) {
55
+ const indexPath = dirPath ? `${dirPath}/${indexFile}` : indexFile;
56
+ const exactIndexMatch = files.find(file => {
57
+ const relativePath = getRelativePath(file);
58
+ return relativePath === indexPath;
59
+ });
60
+
61
+ if (exactIndexMatch) {
62
+ log(`Found index file: ${exactIndexMatch}`, 2);
63
+ return [exactIndexMatch, {}];
64
+ }
65
+ }
66
+ }
67
+
68
+ // Look for dynamic routes
69
+ log(`Searching for dynamic routes...`, 3);
70
+ const dynamicMatches = [];
71
+
72
+ for (const file of files) {
73
+ const relativePath = getRelativePath(file);
74
+ const fileSegments = relativePath.split('/');
75
+ const fileName = fileSegments[fileSegments.length - 1];
76
+ const fileDirSegments = fileSegments.slice(0, -1);
77
+
78
+ // Check if this could be a dynamic match
79
+ if (fileDirSegments.length !== requestSegments.length) {
80
+ continue;
81
+ }
82
+
83
+ const pathParams = {};
84
+ let isMatch = true;
85
+
86
+ // Compare each segment
87
+ for (let i = 0; i < fileDirSegments.length; i++) {
88
+ const fileSegment = fileDirSegments[i];
89
+ const requestSegment = requestSegments[i];
90
+
91
+ if (isDynamicSegment(fileSegment)) {
92
+ // This is a dynamic segment, capture the parameter
93
+ const paramName = getParamName(fileSegment);
94
+ pathParams[paramName] = requestSegment;
95
+ log(`Dynamic match: [${paramName}] = ${requestSegment}`, 4);
96
+ } else if (fileSegment !== requestSegment) {
97
+ // Static segment doesn't match
98
+ isMatch = false;
99
+ break;
100
+ }
101
+ }
102
+
103
+ if (isMatch) {
104
+ // Check if this is an exact file match or directory index
105
+ if (!isDirectoryRequest) {
106
+ // Direct file match
107
+ log(`Found dynamic file match: ${file}`, 3);
108
+ dynamicMatches.push({ file, pathParams, priority: 0 });
109
+ } else {
110
+ // Directory request - check for index files
111
+ const methodUpper = method.toUpperCase();
112
+ const indexFiles = [
113
+ `${methodUpper}.js`,
114
+ `${methodUpper}.html`,
115
+ 'index.js',
116
+ 'index.html'
117
+ ];
118
+
119
+ const priority = indexFiles.indexOf(fileName);
120
+ if (priority !== -1) {
121
+ log(`Found dynamic directory match: ${file} (priority: ${priority})`, 3);
122
+ dynamicMatches.push({ file, pathParams, priority });
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ // Sort by priority (lower number = higher priority) and return the best match
129
+ if (dynamicMatches.length > 0) {
130
+ dynamicMatches.sort((a, b) => a.priority - b.priority);
131
+ const bestMatch = dynamicMatches[0];
132
+ log(`Best dynamic match: ${bestMatch.file} with params: ${JSON.stringify(bestMatch.pathParams)}`, 2);
133
+ return [bestMatch.file, bestMatch.pathParams];
134
+ }
135
+
136
+ // No match found
137
+ log(`No file found for: ${requestPath}`, 3);
138
+ return [false, {}];
139
+ }
package/getFiles.js ADDED
@@ -0,0 +1,73 @@
1
+ import { readdir, stat } from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ export default async (root, config, log) => {
5
+ log(`Starting directory scan from: ${root}`, 2);
6
+ const paths = [];
7
+
8
+ // Get file extension from path
9
+ const getExtension = (filePath) => {
10
+ const ext = path.extname(filePath).toLowerCase();
11
+ return ext.startsWith('.') ? ext.slice(1) : ext;
12
+ };
13
+
14
+ // Check if path matches any disallowed regex patterns
15
+ const isDisallowed = (filePath) => {
16
+ const relativePath = path.relative(root, filePath).replace(/\\/g, '/');
17
+ const urlPath = '/' + relativePath;
18
+
19
+ const disallowed = config.disallowedRegex.some(pattern => {
20
+ const regex = new RegExp(pattern);
21
+ return regex.test(urlPath) || regex.test(relativePath);
22
+ });
23
+
24
+ if (disallowed) {
25
+ log(`Skipping disallowed file: ${relativePath}`, 4);
26
+ }
27
+
28
+ return disallowed;
29
+ };
30
+
31
+ // Check if file extension is in allowed MIME types
32
+ const isAllowedMimeType = (filePath) => {
33
+ const ext = getExtension(filePath);
34
+ const allowed = config.allowedMimes.hasOwnProperty(ext);
35
+
36
+ if (!allowed) {
37
+ log(`Skipping file with disallowed extension: ${path.relative(root, filePath)} (.${ext})`, 4);
38
+ }
39
+
40
+ return allowed;
41
+ };
42
+
43
+ // Recursive function to scan directories
44
+ const scanDirectory = async (currentPath) => {
45
+ try {
46
+ const entries = await readdir(currentPath);
47
+ log(`Scanning directory: ${path.relative(root, currentPath)} (${entries.length} entries)`, 3);
48
+
49
+ for (const entry of entries) {
50
+ const fullPath = path.join(currentPath, entry);
51
+ const stats = await stat(fullPath);
52
+
53
+ if (stats.isDirectory()) {
54
+ // Recursively scan subdirectories
55
+ await scanDirectory(fullPath);
56
+ } else if (stats.isFile()) {
57
+ // Check if file should be included
58
+ if (isAllowedMimeType(fullPath) && !isDisallowed(fullPath)) {
59
+ paths.push(fullPath);
60
+ log(`Added file: ${path.relative(root, fullPath)}`, 4);
61
+ }
62
+ }
63
+ }
64
+ } catch (error) {
65
+ // Skip directories/files that can't be accessed
66
+ log(`Could not access directory: ${currentPath} - ${error.message}`, 1);
67
+ }
68
+ };
69
+
70
+ await scanDirectory(root);
71
+ log(`Directory scan complete. Found ${paths.length} files`, 2);
72
+ return paths;
73
+ }
package/getFlags.js ADDED
@@ -0,0 +1,35 @@
1
+ export default (args, flagDefaults = {}, flagMap = {}) => {
2
+ const flags = { ...flagDefaults };
3
+
4
+ for (let i = 0; i < args.length; i++) {
5
+ const arg = args[i];
6
+
7
+ // Handle long flags (--flag)
8
+ if (arg.startsWith('--')) {
9
+ const flag = arg.substring(2);
10
+ const nextArg = args[i + 1];
11
+
12
+ if (!nextArg || nextArg.startsWith('-')) {
13
+ flags[flag] = true;
14
+ } else {
15
+ flags[flag] = nextArg;
16
+ i++; // Skip the next argument as it's the value
17
+ }
18
+ }
19
+ // Handle short flags (-f)
20
+ else if (arg.startsWith('-')) {
21
+ const shortFlag = arg.substring(1);
22
+ const flag = flagMap[shortFlag] || shortFlag;
23
+ const nextArg = args[i + 1];
24
+
25
+ if (!nextArg || nextArg.startsWith('-')) {
26
+ flags[flag] = true;
27
+ } else {
28
+ flags[flag] = nextArg;
29
+ i++; // Skip the next argument as it's the value
30
+ }
31
+ }
32
+ }
33
+
34
+ return flags;
35
+ }