@slim-lang/core 1.2.12 → 1.2.13

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.
Files changed (48) hide show
  1. package/README.md +522 -14
  2. package/package.json +2 -6
  3. package/packages/slim/server/main.slim +433 -422
  4. package/run-dev-slim.js +10 -5
  5. package/run-slim.js +10 -20
  6. package/src/bin/api/github_get.js +7 -12
  7. package/src/bin/api/github_req.js +54 -241
  8. package/src/bin/api/lock.js +2 -1
  9. package/src/bin/api/spm.js +20 -91
  10. package/src/bin/cli.js +73 -102
  11. package/src/bin/config.default.json +11 -11
  12. package/src/bin/helpers.js +2 -7
  13. package/src/bin/spm.js +3 -7
  14. package/src/checker.js +1705 -388
  15. package/src/compile.js +131 -100
  16. package/src/external/classErrors.js +5 -6
  17. package/src/external/client.js +0 -2
  18. package/src/external/core.js +355 -237
  19. package/src/external/defaults.js +12 -4
  20. package/src/external/dom.js +663 -0
  21. package/src/external/helpers.js +87 -58
  22. package/src/external/reactive.js +601 -0
  23. package/src/external/router.js +117 -0
  24. package/src/external/slim-globals.d.ts +43 -4
  25. package/src/external/typeSyntax.js +258 -0
  26. package/src/external/types.js +1 -1
  27. package/src/format.js +183 -12
  28. package/src/handlers/errorHandler.js +9 -36
  29. package/src/jsdoc.js +36 -16
  30. package/src/modulePaths.js +15 -5
  31. package/src/reactivity.js +774 -0
  32. package/src/repl.js +1 -1
  33. package/src/suggest.js +60 -0
  34. package/src/syntax/babel.js +46 -0
  35. package/src/syntax/index.js +39 -0
  36. package/src/syntax/lower.js +666 -0
  37. package/src/syntax/markup.js +195 -0
  38. package/src/syntax/plugin.js +903 -0
  39. package/src/syntax/types.js +106 -0
  40. package/src/test-runner.js +5 -5
  41. package/src/transform.js +209 -244
  42. package/packages/slim/helpers/string.js +0 -43
  43. package/packages/slim/types/hash.js +0 -11
  44. package/src/handlers/parser/components.js +0 -316
  45. package/src/handlers/parserHandler.js +0 -789
  46. package/src/lexer.js +0 -174
  47. package/src/parser.js +0 -803
  48. package/src/sourcemap.js +0 -0
@@ -1,423 +1,434 @@
1
- use http from "http"
2
- use * as fs from "fs"
3
- use * as nodePath from "path"
4
- import process from 'node:process';
5
-
6
- export type ServerInstance = typeof Server;
7
-
8
- export struct RedirectRoute {
9
- from: string
10
- to: string
11
- }
12
-
13
- export struct StaticRoute {
14
- from: string
15
- to: string
16
- }
17
-
18
- export struct SlimServerConf {
19
- port: int = 3000
20
- dev: bool = false
21
- redirects: object[] = [{}]
22
- statics: object[] = [{}]
23
- }
24
-
25
- class Server {
26
- constructor(port: int = 3000) {
27
- this.port = port;
28
- this.routes = [];
29
- this.apiRoutes = {};
30
- this.clients = [];
31
- this.staticDirs = [];
32
- this.dev = false;
33
-
34
- this.#loadConfig();
35
- }
36
-
37
- #loadConfig() {
38
- let configDir = process.cwd();
39
- let raw: object = {};
40
-
41
- try {
42
- const slimConf = JSON.parse(fs.readFileSync(nodePath.join(process.cwd(), "slimconfig.json"), "utf8"));
43
- if (slimConf.main) configDir = nodePath.dirname(nodePath.resolve(slimConf.main));
44
- } catch (e) {}
45
-
46
- try {
47
- raw = JSON.parse(fs.readFileSync(nodePath.join(configDir, "slimserver.json"), "utf8"));
48
- } catch (e) {}
49
-
50
- const conf = SlimServerConf.new(raw);
51
-
52
- this.port = conf.port;
53
- this.dev = conf.dev || process.env.SLIM_DEV === "1";
54
-
55
- this.redirect(conf.redirects);
56
-
57
- const statics = conf.statics.map(entry => {
58
- if (empty entry) return entry;
59
- return { from: entry.from, to: nodePath.resolve(configDir, entry.to) };
60
- });
61
-
62
- this.static(statics);
63
- }
64
-
65
- page(path: string, render: function, options?: object) {
66
- let additionalScript = ""
67
- let scriptId = 0;
68
-
69
- func renderTag(content: string[]) {
70
- const tags: object = {
71
- "css": {
72
- tag: "link",
73
- attr: "href",
74
- additionalAttrs: {
75
- rel: "stylesheet"
76
- }
77
- },
78
- "js": {
79
- tag: "script",
80
- attr: "src"
81
- },
82
- }
83
-
84
- content.forEach(c => {
85
- const ext = c.split(".").pop();
86
-
87
- if (ext in tags) {
88
- const tag = tags[ext].tag;
89
- const attr = tags[ext].attr;
90
- const varName = `${tag}_${scriptId++}`;
91
- let additional = ""
92
-
93
- if ("additionalAttrs" in tags[ext]) {
94
- const additionalAttrs = tags[ext].additionalAttrs
95
-
96
- Object.keys(additionalAttrs).forEach(e => {
97
- additional += `${varName}.${e} = "${additionalAttrs[e]}"`
98
- })
99
- }
100
-
101
- additionalScript += `
102
- const ${varName} = document.createElement("${tag}");
103
- ${varName}.${attr} = ${JSON.stringify(c)};
104
- ${additional}
105
- document.head.appendChild(${varName});
106
- `;
107
- }
108
- });
109
- }
110
-
111
- if(options) {
112
- if ("head" in options) {
113
- const headLinks: string[] = options.head
114
-
115
- renderTag(headLinks)
116
- }
117
- if ("title" in options) {
118
- const title: string = options.title
119
-
120
- additionalScript += `document.title = "${title}";`
121
- }
122
- if ("icon" in options) {
123
- const icon: string = options.icon
124
-
125
- additionalScript += `
126
- link = document.createElement("link");
127
- link.rel = "icon";
128
- link.href = "${icon}";
129
- document.head.appendChild(link);
130
- `
131
- }
132
- if ("onload" in options) {
133
- const onload: function = options.onload
134
-
135
- additionalScript += `
136
- const __onload = ${String(onload)};__onload({ port: ${this.port}});
137
- `
138
- }
139
- }
140
-
141
- this.get(path, async (req, res, params) => {
142
- const isDev = this.dev
143
- let html = render({ dev: isDev, params });
144
- const eventsScript = __flush_events__();
145
-
146
- if(kindof html == "promise") {
147
- html = await html
148
- }
149
-
150
- if(kindof html == "object") {
151
- res.writeHead(200, {
152
- "Content-Type": "text/json; charset=utf-8",
153
- "Cache-Control": "no-store"
154
- });
155
- res.end(JSON.stringify(html))
156
-
157
- return
158
- }
159
-
160
- html += `<script>`
161
-
162
- html += additionalScript
163
-
164
- if (isDev) {
165
- html += `
166
- (function () {
167
- let connectedBefore = false;
168
-
169
- const es = new EventSource("/__slim_reload__");
170
-
171
- es.onopen = () => {
172
- if (connectedBefore) {
173
- location.reload();
174
- return;
175
- }
176
- connectedBefore = true;
177
- };
178
- })();`;
179
- }
180
-
181
- html += `</script>`
182
-
183
- if (eventsScript) {
184
- html += `<script>${eventsScript}</script>`
185
- }
186
-
187
- res.writeHead(200, {
188
- "Content-Type": "text/html; charset=utf-8",
189
- "Cache-Control": "no-store"
190
- });
191
-
192
- res.end(html);
193
- });
194
- }
195
-
196
- get(path: string, callback: function) {
197
- const compiled = this.compileRoute(path);
198
- this.routes.push({ regex: compiled.regex, keys: compiled.keys, callback });
199
- }
200
-
201
- escapeRegex(str: string) {
202
- const specials = ".^$*+?()[]{}|\\";
203
- let out = "";
204
-
205
- for (const ch of str) {
206
- if (specials.includes(ch)) out += "\\";
207
- out += ch;
208
- }
209
-
210
- return out;
211
- }
212
-
213
- compileRoute(route: string) {
214
- const keys = [];
215
-
216
- const pattern = route.split("/").map(segment => {
217
- if (segment.length > 2 && segment.startsWith("{") && segment.endsWith("}")) {
218
- keys.push(segment.slice(1, -1));
219
- return "([^/]+)";
220
- }
221
-
222
- return this.escapeRegex(segment);
223
- }).join("/");
224
-
225
- return { regex: new RegExp("^" + pattern + "$"), keys };
226
- }
227
-
228
- contentType(file: string) {
229
- const types: object = {
230
- html: "text/html",
231
- css: "text/css",
232
- js: "text/javascript",
233
- mjs: "text/javascript",
234
- json: "application/json",
235
- svg: "image/svg+xml",
236
- png: "image/png",
237
- jpg: "image/jpeg",
238
- jpeg: "image/jpeg",
239
- gif: "image/gif",
240
- webp: "image/webp",
241
- ico: "image/x-icon",
242
- woff: "font/woff",
243
- woff2: "font/woff2",
244
- ttf: "font/ttf",
245
- txt: "text/plain"
246
- };
247
-
248
- const ext = file.split(".").pop().toLowerCase();
249
- const mime = types[ext] ?? "application/octet-stream";
250
- const isText = mime.startsWith("text/") || mime == "application/json" || mime == "image/svg+xml";
251
-
252
- return isText ? `${mime}; charset=utf-8` : mime;
253
- }
254
-
255
- colorStatus(status: int) {
256
- const text = String(status);
257
-
258
- if (!process.stdout.isTTY) return text;
259
-
260
- const esc = String.fromCharCode(27);
261
- let color = "32";
262
-
263
- if (status >= 500) color = "31";
264
- else if (status >= 400) color = "33";
265
- else if (status >= 300) color = "36";
266
-
267
- return `${esc}[${color}m${text}${esc}[0m`;
268
- }
269
-
270
- api(path: string, handler: function) {
271
- this.apiRoutes[path] = handler;
272
- }
273
-
274
- redirect(paths: object[]) {
275
- for(const path of paths) {
276
- if(empty path) continue
277
-
278
- RedirectRoute.verify(path)
279
-
280
- const from = path.from
281
- const to = path.to
282
-
283
- this.get(from, async (req, res) => {
284
- res.writeHead(200, {
285
- "Content-Type": "text/html; charset=utf-8",
286
- "Cache-Control": "no-store"
287
- });
288
-
289
- res.end(`<script>window.location.href="${to}"</script>`);
290
- })
291
- }
292
- }
293
-
294
- static(paths: object[]) {
295
- for(const path of paths) {
296
- if(empty path) continue
297
-
298
- StaticRoute.verify(path)
299
-
300
- const from = path.from
301
- const to = path.to
302
-
303
- const root = nodePath.resolve(to);
304
-
305
- if (!fs.existsSync(root)) {
306
- log(`[SlimServer] Static setup ("${from}" -> "${to}"): directory not found: ${to}`);
307
- }
308
-
309
- this.staticDirs.push({ prefix: from, dir: to });
310
- }
311
- }
312
-
313
- start() {
314
- this.get("/__slim_reload__", (req, res) => {
315
- res.writeHead(200, {
316
- "Content-Type": "text/event-stream",
317
- "Cache-Control": "no-cache",
318
- "Connection": "keep-alive"
319
- });
320
-
321
- res.write("retry: 300\n\n");
322
-
323
- this.clients.push(res);
324
-
325
- req.on("close", () => {
326
- this.clients = this.clients.filter(x => x !== res);
327
- });
328
- });
329
-
330
- http.createServer((req, res) => {
331
- const url = req.url.split("?")[0];
332
-
333
- if (this.dev && url != "/__slim_reload__") {
334
- const started = Date.now();
335
-
336
- res.on("finish", () => {
337
- const ms = Date.now() - started;
338
- log(`${req.method} ${req.url} ${this.colorStatus(res.statusCode)} in ${ms}ms`);
339
- });
340
- }
341
-
342
- for (const route of this.routes) {
343
- const match = url.match(route.regex);
344
-
345
- if (match) {
346
- const params: object = {};
347
- route.keys.forEach((key, i) => {
348
- params[key] = decodeURIComponent(match[i + 1]);
349
- });
350
-
351
- route.callback(req, res, params);
352
- return;
353
- }
354
- }
355
-
356
- const apiRoute = this.apiRoutes[url];
357
-
358
- if (apiRoute) {
359
- let body = "";
360
- req.on("data", chunk => { body += chunk });
361
- req.on("end", async () => {
362
- let data = null;
363
-
364
- if (body) {
365
- try {
366
- data = JSON.parse(body);
367
- } catch (e) {
368
- res.writeHead(400, { "Content-Type": "application/json" });
369
- res.end(JSON.stringify({ error: "Invalid JSON body" }));
370
- return;
371
- }
372
- }
373
-
374
- try {
375
- const result = await apiRoute(data, req);
376
- res.writeHead(200, { "Content-Type": "application/json" });
377
- res.end(JSON.stringify(result ?? null));
378
- } catch (e) {
379
- res.writeHead(500, { "Content-Type": "application/json" });
380
- res.end(JSON.stringify({ error: e && e.message ? e.message : String(e) }));
381
- }
382
- });
383
- return;
384
- }
385
-
386
- for (const mount of this.staticDirs) {
387
- if (url == mount.prefix || url.startsWith(mount.prefix + "/")) {
388
- let relative = url.slice(mount.prefix.length);
389
- while (relative.startsWith("/")) relative = relative.slice(1);
390
-
391
- const root = nodePath.resolve(mount.dir);
392
- const filePath = nodePath.join(root, relative);
393
-
394
- if (filePath != root && !filePath.startsWith(root + nodePath.sep)) {
395
- res.writeHead(403);
396
- res.end("403");
397
- return;
398
- }
399
-
400
- fs.promises.readFile(filePath).then(data => {
401
- res.writeHead(200, {
402
- "Content-Type": this.contentType(filePath),
403
- "Cache-Control": "no-store"
404
- });
405
- res.end(data);
406
- }).catch(() => {
407
- res.writeHead(404);
408
- res.end("404");
409
- });
410
-
411
- return;
412
- }
413
- }
414
-
415
- res.writeHead(404);
416
- res.end("404");
417
- }).listen(this.port);
418
-
419
- log(`http://localhost:${this.port}`);
420
- }
421
- }
422
-
1
+ use http from "http"
2
+ use * as fs from "fs"
3
+ use * as nodePath from "path"
4
+ import process from 'node:process';
5
+
6
+ export type ServerInstance = typeof Server;
7
+
8
+ export struct RedirectRoute {
9
+ from: string
10
+ to: string
11
+ }
12
+
13
+ export struct StaticRoute {
14
+ from: string
15
+ to: string
16
+ }
17
+
18
+ export struct SlimServerConf {
19
+ port: int = 3000
20
+ dev: bool = false
21
+ redirects: object[] = [{}]
22
+ statics: object[] = [{}]
23
+ }
24
+
25
+ class Server {
26
+ constructor(port: int = 3000) {
27
+ this.port = port;
28
+ this.routes = [];
29
+ this.apiRoutes = {};
30
+ this.clients = [];
31
+ this.staticDirs = [];
32
+ this.dev = false;
33
+
34
+ this.#loadConfig();
35
+ }
36
+
37
+ #loadConfig() {
38
+ let configDir = process.cwd();
39
+ let raw: object = {};
40
+
41
+ try {
42
+ const slimConf = JSON.parse(fs.readFileSync(nodePath.join(process.cwd(), "slimconfig.json"), "utf8"));
43
+ if (slimConf.main) configDir = nodePath.dirname(nodePath.resolve(slimConf.main));
44
+ } catch (e) {}
45
+
46
+ try {
47
+ raw = JSON.parse(fs.readFileSync(nodePath.join(configDir, "slimserver.json"), "utf8"));
48
+ } catch (e) {}
49
+
50
+ const conf = SlimServerConf.new(raw);
51
+
52
+ this.port = conf.port;
53
+ this.dev = conf.dev || process.env.SLIM_DEV === "1";
54
+
55
+ this.redirect(conf.redirects);
56
+
57
+ const statics = conf.statics.map(entry => {
58
+ if (empty entry) return entry;
59
+ return { from: entry.from, to: nodePath.resolve(configDir, entry.to) };
60
+ });
61
+
62
+ this.static(statics);
63
+ }
64
+
65
+ page(path: string, render: function, options?: object) {
66
+ let additionalScript = ""
67
+ let scriptId = 0;
68
+
69
+ func renderTag(content: string[]) {
70
+ const tags: object = {
71
+ "css": {
72
+ tag: "link",
73
+ attr: "href",
74
+ additionalAttrs: {
75
+ rel: "stylesheet"
76
+ }
77
+ },
78
+ "js": {
79
+ tag: "script",
80
+ attr: "src"
81
+ },
82
+ }
83
+
84
+ content.forEach(c => {
85
+ const ext = c.split(".").pop();
86
+
87
+ if (ext in tags) {
88
+ const tag = tags[ext].tag;
89
+ const attr = tags[ext].attr;
90
+ const varName = `${tag}_${scriptId++}`;
91
+ let additional = ""
92
+
93
+ if ("additionalAttrs" in tags[ext]) {
94
+ const additionalAttrs = tags[ext].additionalAttrs
95
+
96
+ Object.keys(additionalAttrs).forEach(e => {
97
+ additional += `${varName}.${e} = "${additionalAttrs[e]}"`
98
+ })
99
+ }
100
+
101
+ additionalScript += `
102
+ const ${varName} = document.createElement("${tag}");
103
+ ${varName}.${attr} = ${JSON.stringify(c)};
104
+ ${additional}
105
+ document.head.appendChild(${varName});
106
+ `;
107
+ }
108
+ });
109
+ }
110
+
111
+ if(options) {
112
+ if ("head" in options) {
113
+ const headLinks: string[] = options.head
114
+
115
+ renderTag(headLinks)
116
+ }
117
+ if ("title" in options) {
118
+ const title: string = options.title
119
+
120
+ additionalScript += `document.title = "${title}";`
121
+ }
122
+ if ("icon" in options) {
123
+ const icon: string = options.icon
124
+
125
+ additionalScript += `
126
+ link = document.createElement("link");
127
+ link.rel = "icon";
128
+ link.href = "${icon}";
129
+ document.head.appendChild(link);
130
+ `
131
+ }
132
+ if ("onload" in options) {
133
+ const onload: function = options.onload
134
+
135
+ additionalScript += `
136
+ const __onload = ${String(onload)};__onload({ port: ${this.port}});
137
+ `
138
+ }
139
+ }
140
+
141
+ this.get(path, async (req, res, params) => {
142
+ const isDev = this.dev
143
+ let html = null
144
+
145
+ if (options && "hydrate" in options) {
146
+ const props = { dev: isDev, params, url: req.url }
147
+ const rendered = await renderToStringAsync(() => render(props))
148
+ const data = JSON.stringify(props).replace(/</g, "\\u003c")
149
+ html = `<div id="slim-root">${rendered.html}</div>` + rendered.script +
150
+ `<script>window.__slimProps = ${data}</script>` +
151
+ `<script type="module" src="${options.hydrate}"></script>`
152
+ } else {
153
+ html = render({ dev: isDev, params, url: req.url })
154
+ }
155
+ const eventsScript = __flush_events__();
156
+
157
+ if(kindof html == "promise") {
158
+ html = await html
159
+ }
160
+
161
+ if(kindof html == "object") {
162
+ res.writeHead(200, {
163
+ "Content-Type": "text/json; charset=utf-8",
164
+ "Cache-Control": "no-store"
165
+ });
166
+ res.end(JSON.stringify(html))
167
+
168
+ return
169
+ }
170
+
171
+ html += `<script>`
172
+
173
+ html += additionalScript
174
+
175
+ if (isDev) {
176
+ html += `
177
+ (function () {
178
+ let connectedBefore = false;
179
+
180
+ const es = new EventSource("/__slim_reload__");
181
+
182
+ es.onopen = () => {
183
+ if (connectedBefore) {
184
+ location.reload();
185
+ return;
186
+ }
187
+ connectedBefore = true;
188
+ };
189
+ })();`;
190
+ }
191
+
192
+ html += `</script>`
193
+
194
+ if (eventsScript) {
195
+ html += `<script>${eventsScript}</script>`
196
+ }
197
+
198
+ res.writeHead(200, {
199
+ "Content-Type": "text/html; charset=utf-8",
200
+ "Cache-Control": "no-store"
201
+ });
202
+
203
+ res.end(html);
204
+ });
205
+ }
206
+
207
+ get(path: string, callback: function) {
208
+ const compiled = this.compileRoute(path);
209
+ this.routes.push({ regex: compiled.regex, keys: compiled.keys, callback });
210
+ }
211
+
212
+ escapeRegex(str: string) {
213
+ const specials = ".^$*+?()[]{}|\\";
214
+ let out = "";
215
+
216
+ for (const ch of str) {
217
+ if (specials.includes(ch)) out += "\\";
218
+ out += ch;
219
+ }
220
+
221
+ return out;
222
+ }
223
+
224
+ compileRoute(route: string) {
225
+ const keys = [];
226
+
227
+ const pattern = route.split("/").map(segment => {
228
+ if (segment.length > 2 && segment.startsWith("{") && segment.endsWith("}")) {
229
+ keys.push(segment.slice(1, -1));
230
+ return "([^/]+)";
231
+ }
232
+
233
+ return this.escapeRegex(segment);
234
+ }).join("/");
235
+
236
+ return { regex: new RegExp("^" + pattern + "$"), keys };
237
+ }
238
+
239
+ contentType(file: string) {
240
+ const types: object = {
241
+ html: "text/html",
242
+ css: "text/css",
243
+ js: "text/javascript",
244
+ mjs: "text/javascript",
245
+ json: "application/json",
246
+ svg: "image/svg+xml",
247
+ png: "image/png",
248
+ jpg: "image/jpeg",
249
+ jpeg: "image/jpeg",
250
+ gif: "image/gif",
251
+ webp: "image/webp",
252
+ ico: "image/x-icon",
253
+ woff: "font/woff",
254
+ woff2: "font/woff2",
255
+ ttf: "font/ttf",
256
+ txt: "text/plain"
257
+ };
258
+
259
+ const ext = file.split(".").pop().toLowerCase();
260
+ const mime = types[ext] ?? "application/octet-stream";
261
+ const isText = mime.startsWith("text/") || mime == "application/json" || mime == "image/svg+xml";
262
+
263
+ return isText ? `${mime}; charset=utf-8` : mime;
264
+ }
265
+
266
+ colorStatus(status: int) {
267
+ const text = String(status);
268
+
269
+ if (!process.stdout.isTTY) return text;
270
+
271
+ const esc = String.fromCharCode(27);
272
+ let color = "32";
273
+
274
+ if (status >= 500) color = "31";
275
+ else if (status >= 400) color = "33";
276
+ else if (status >= 300) color = "36";
277
+
278
+ return `${esc}[${color}m${text}${esc}[0m`;
279
+ }
280
+
281
+ api(path: string, handler: function) {
282
+ this.apiRoutes[path] = handler;
283
+ }
284
+
285
+ redirect(paths: object[]) {
286
+ for(const path of paths) {
287
+ if(empty path) continue
288
+
289
+ RedirectRoute.verify(path)
290
+
291
+ const from = path.from
292
+ const to = path.to
293
+
294
+ this.get(from, async (req, res) => {
295
+ res.writeHead(200, {
296
+ "Content-Type": "text/html; charset=utf-8",
297
+ "Cache-Control": "no-store"
298
+ });
299
+
300
+ res.end(`<script>window.location.href="${to}"</script>`);
301
+ })
302
+ }
303
+ }
304
+
305
+ static(paths: object[]) {
306
+ for(const path of paths) {
307
+ if(empty path) continue
308
+
309
+ StaticRoute.verify(path)
310
+
311
+ const from = path.from
312
+ const to = path.to
313
+
314
+ const root = nodePath.resolve(to);
315
+
316
+ if (!fs.existsSync(root)) {
317
+ log(`[SlimServer] Static setup ("${from}" -> "${to}"): directory not found: ${to}`);
318
+ }
319
+
320
+ this.staticDirs.push({ prefix: from, dir: to });
321
+ }
322
+ }
323
+
324
+ start() {
325
+ this.get("/__slim_reload__", (req, res) => {
326
+ res.writeHead(200, {
327
+ "Content-Type": "text/event-stream",
328
+ "Cache-Control": "no-cache",
329
+ "Connection": "keep-alive"
330
+ });
331
+
332
+ res.write("retry: 300\n\n");
333
+
334
+ this.clients.push(res);
335
+
336
+ req.on("close", () => {
337
+ this.clients = this.clients.filter(x => x !== res);
338
+ });
339
+ });
340
+
341
+ http.createServer((req, res) => {
342
+ const url = req.url.split("?")[0];
343
+
344
+ if (this.dev && url != "/__slim_reload__") {
345
+ const started = Date.now();
346
+
347
+ res.on("finish", () => {
348
+ const ms = Date.now() - started;
349
+ log(`${req.method} ${req.url} ${this.colorStatus(res.statusCode)} in ${ms}ms`);
350
+ });
351
+ }
352
+
353
+ for (const route of this.routes) {
354
+ const match = url.match(route.regex);
355
+
356
+ if (match) {
357
+ const params: object = {};
358
+ route.keys.forEach((key, i) => {
359
+ params[key] = decodeURIComponent(match[i + 1]);
360
+ });
361
+
362
+ route.callback(req, res, params);
363
+ return;
364
+ }
365
+ }
366
+
367
+ const apiRoute = this.apiRoutes[url];
368
+
369
+ if (apiRoute) {
370
+ let body = "";
371
+ req.on("data", chunk => { body += chunk });
372
+ req.on("end", async () => {
373
+ let data = null;
374
+
375
+ if (body) {
376
+ try {
377
+ data = JSON.parse(body);
378
+ } catch (e) {
379
+ res.writeHead(400, { "Content-Type": "application/json" });
380
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
381
+ return;
382
+ }
383
+ }
384
+
385
+ try {
386
+ const result = await apiRoute(data, req);
387
+ res.writeHead(200, { "Content-Type": "application/json" });
388
+ res.end(JSON.stringify(result ?? null));
389
+ } catch (e) {
390
+ res.writeHead(500, { "Content-Type": "application/json" });
391
+ res.end(JSON.stringify({ error: e && e.message ? e.message : String(e) }));
392
+ }
393
+ });
394
+ return;
395
+ }
396
+
397
+ for (const mount of this.staticDirs) {
398
+ if (url == mount.prefix || url.startsWith(mount.prefix + "/")) {
399
+ let relative = url.slice(mount.prefix.length);
400
+ while (relative.startsWith("/")) relative = relative.slice(1);
401
+
402
+ const root = nodePath.resolve(mount.dir);
403
+ const filePath = nodePath.join(root, relative);
404
+
405
+ if (filePath != root && !filePath.startsWith(root + nodePath.sep)) {
406
+ res.writeHead(403);
407
+ res.end("403");
408
+ return;
409
+ }
410
+
411
+ fs.promises.readFile(filePath).then(data => {
412
+ res.writeHead(200, {
413
+ "Content-Type": this.contentType(filePath),
414
+ "Cache-Control": "no-store"
415
+ });
416
+ res.end(data);
417
+ }).catch(() => {
418
+ res.writeHead(404);
419
+ res.end("404");
420
+ });
421
+
422
+ return;
423
+ }
424
+ }
425
+
426
+ res.writeHead(404);
427
+ res.end("404");
428
+ }).listen(this.port);
429
+
430
+ log(`http://localhost:${this.port}`);
431
+ }
432
+ }
433
+
423
434
  export { Server };