@lango-project/lango-server 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +149 -18
- package/dist/.lango/localization.mjs +108 -0
- package/dist/.lango/runtime.mjs +25 -6
- package/dist/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/.lango/localization.mjs +108 -0
- package/dist/cli/.lango/runtime.mjs +25 -6
- package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/endpoint.mjs +2 -6
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +1 -1
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/options.mjs +2 -2
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/route_pattern.mjs +129 -0
- package/dist/cli/route_pattern.mjs.map +1 -0
- package/dist/cli/routes.mjs +25 -13
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/static_files.mjs +121 -25
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/endpoint.mjs +2 -6
- package/dist/endpoint.mjs.map +1 -1
- package/dist/http_failure.mjs +45 -0
- package/dist/http_failure.mjs.map +1 -0
- package/dist/longpoll_options.mjs +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/options.mjs +2 -2
- package/dist/options.mjs.map +1 -1
- package/dist/response.mjs +8 -0
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +22 -0
- package/dist/route_info.mjs.map +1 -0
- package/dist/route_pattern.mjs +129 -0
- package/dist/route_pattern.mjs.map +1 -0
- package/dist/routes.mjs +25 -13
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +132 -22
- package/dist/runtime.mjs.map +1 -1
- package/dist/server_context.mjs +25 -2
- package/dist/server_context.mjs.map +1 -1
- package/dist/static_files.mjs +121 -25
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs +38 -13
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +16 -1
- package/dist/tokens.mjs.map +1 -1
- package/package.json +3 -3
- package/src/endpoint.lango +3 -4
- package/src/http_failure.lango +26 -0
- package/src/longpoll_options.lango +1 -1
- package/src/options.lango +2 -2
- package/src/response.lango +6 -0
- package/src/route_info.lango +15 -0
- package/src/route_pattern.lango +86 -0
- package/src/routes.lango +20 -8
- package/src/runtime.lango +119 -19
- package/src/server_context.lango +19 -3
- package/src/static_files.lango +99 -23
- package/src/token.lango +24 -3
- package/src/tokens.lango +11 -1
package/dist/runtime.mjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { routePattern, matchPath, moreSpecific } from "./route_pattern.mjs";
|
|
1
2
|
import { ServerContext } from "./server_context.mjs";
|
|
2
3
|
import { Database } from "./database.mjs";
|
|
3
4
|
import { Token } from "./token.mjs";
|
|
4
5
|
import { Tokens } from "./tokens.mjs";
|
|
5
6
|
import { Response } from "./response.mjs";
|
|
7
|
+
import { HttpFailure } from "./http_failure.mjs";
|
|
6
8
|
import * as threads from "node:worker_threads";
|
|
7
9
|
import {
|
|
8
10
|
hostGlobal as __hostGlobal,
|
|
11
|
+
hostGlobalCall as __hostGlobalCall,
|
|
9
12
|
contextGet as __contextGet,
|
|
10
13
|
contextSet as __contextSet,
|
|
11
14
|
contextRestore as __contextRestore,
|
|
@@ -40,7 +43,12 @@ export class Runtime {
|
|
|
40
43
|
constructor(definition) {
|
|
41
44
|
__requireArity(arguments.length, [0], "constructor");
|
|
42
45
|
definition = __boundary(definition);
|
|
43
|
-
|
|
46
|
+
let refresh = __withArity((tokens) => {
|
|
47
|
+
tokens = __boundary(tokens);
|
|
48
|
+
return this.refreshTokens(tokens);
|
|
49
|
+
return null;
|
|
50
|
+
}, [0], "closure");
|
|
51
|
+
this.#serverContext = new ServerContext(__normalize(definition.routes), refresh);
|
|
44
52
|
this.#definition = definition;
|
|
45
53
|
this.#routes = [];
|
|
46
54
|
this.#events = { };
|
|
@@ -89,6 +97,16 @@ export class Runtime {
|
|
|
89
97
|
}, [0], "closure")).then(__withArity((handler) => {
|
|
90
98
|
handler = __boundary(handler);
|
|
91
99
|
this.#middlewares[name] = handler;
|
|
100
|
+
if (__requireBoolean(__normalize(spec.validate) !== null)) {
|
|
101
|
+
return this.#target({ module: __normalize(spec.module), handler: __normalize(spec.validate) });
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
return null;
|
|
105
|
+
}, [0], "closure")).then(__withArity((validator) => {
|
|
106
|
+
validator = __boundary(validator);
|
|
107
|
+
if (__requireBoolean(validator !== null)) {
|
|
108
|
+
return __call(validator, __normalize(this.#serverContext.routes()));
|
|
109
|
+
}
|
|
92
110
|
return null;
|
|
93
111
|
return null;
|
|
94
112
|
}, [0], "closure"));
|
|
@@ -99,7 +117,9 @@ export class Runtime {
|
|
|
99
117
|
pending = __boundary(pending);
|
|
100
118
|
route = __boundary(route);
|
|
101
119
|
if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
|
|
102
|
-
|
|
120
|
+
let prepared = __normalize(__hostGlobal(["Object"]).assign({ }, route));
|
|
121
|
+
prepared.pattern = routePattern(__normalize(route.path));
|
|
122
|
+
__add(this.#routes, prepared);
|
|
103
123
|
return pending;
|
|
104
124
|
}
|
|
105
125
|
return pending.then(__withArity((ignored) => {
|
|
@@ -116,7 +136,7 @@ export class Runtime {
|
|
|
116
136
|
}
|
|
117
137
|
middleware = __normalize(this.#middlewares[name]);
|
|
118
138
|
}
|
|
119
|
-
__add(this.#routes, { path: __normalize(route.path), auth: __normalize(route.auth), handler: handler, middleware: middleware });
|
|
139
|
+
__add(this.#routes, { path: __normalize(route.path), pattern: routePattern(__normalize(route.path)), auth: __normalize(route.auth), handler: handler, middleware: middleware });
|
|
120
140
|
return null;
|
|
121
141
|
return null;
|
|
122
142
|
}, [0], "closure"));
|
|
@@ -158,20 +178,20 @@ export class Runtime {
|
|
|
158
178
|
__requireArity(arguments.length, [0], "match");
|
|
159
179
|
path = __boundary(path);
|
|
160
180
|
let best = null;
|
|
161
|
-
let
|
|
181
|
+
let parameters = null;
|
|
182
|
+
let pattern = null;
|
|
162
183
|
for (const route of __normalize(this.#routes)) {
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (__requireBoolean(__requireBoolean(__normalize(path.startsWith(prefix))) && __requireBoolean(__normalize(prefix.length) > length))) {
|
|
169
|
-
best = route;
|
|
170
|
-
length = __normalize(prefix.length);
|
|
171
|
-
}
|
|
184
|
+
let captured = matchPath(__normalize(route.pattern), path);
|
|
185
|
+
if (__requireBoolean(__requireBoolean(captured !== null) && __requireBoolean(moreSpecific(__normalize(route.pattern), pattern)))) {
|
|
186
|
+
best = route;
|
|
187
|
+
parameters = captured;
|
|
188
|
+
pattern = __normalize(route.pattern);
|
|
172
189
|
}
|
|
173
190
|
}
|
|
174
|
-
|
|
191
|
+
if (__requireBoolean(best === null)) {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
return { route: best, parameters: parameters };
|
|
175
195
|
return null;
|
|
176
196
|
}
|
|
177
197
|
handle(task) {
|
|
@@ -194,10 +214,11 @@ export class Runtime {
|
|
|
194
214
|
} catch (error) {
|
|
195
215
|
return failure(401, "Unauthorized");
|
|
196
216
|
}
|
|
197
|
-
let
|
|
198
|
-
if (__requireBoolean(
|
|
217
|
+
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
218
|
+
if (__requireBoolean(matched === null)) {
|
|
199
219
|
return failure(404, "RouteNotFound");
|
|
200
220
|
}
|
|
221
|
+
let route = __normalize(matched.route);
|
|
201
222
|
let input = null;
|
|
202
223
|
try {
|
|
203
224
|
input = __normalize(__hostGlobal(["JSON"]).parse(__normalize(task.body)));
|
|
@@ -207,6 +228,13 @@ export class Runtime {
|
|
|
207
228
|
} catch (error) {
|
|
208
229
|
return failure(400, "InvalidJson");
|
|
209
230
|
}
|
|
231
|
+
try {
|
|
232
|
+
for (const [name, value] of __entries(__normalize(matched.parameters))) {
|
|
233
|
+
input[name] = __hostGlobalCall(["decodeURIComponent"], value);
|
|
234
|
+
}
|
|
235
|
+
} catch (error) {
|
|
236
|
+
return failure(400, "InvalidPath");
|
|
237
|
+
}
|
|
210
238
|
__contextScope.push(__contextSet("token", new Token(claims)));
|
|
211
239
|
__contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
|
|
212
240
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
@@ -239,6 +267,7 @@ export class Runtime {
|
|
|
239
267
|
validatedAt = __boundary(validatedAt);
|
|
240
268
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(fresh)) && __requireBoolean(__isNumber(validatedAt)))) {
|
|
241
269
|
stampValidation(claims, validatedAt);
|
|
270
|
+
__normalize(__contextGet("token").renew());
|
|
242
271
|
}
|
|
243
272
|
if (__requireBoolean(__requireBoolean(__normalize(route.auth) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasAuth(__normalize(route.auth))))))) {
|
|
244
273
|
throw { status: 401, error: "Unauthorized" };
|
|
@@ -268,8 +297,7 @@ export class Runtime {
|
|
|
268
297
|
output = __boundary(output);
|
|
269
298
|
if (__requireBoolean(__normalize(task.authorize) === true)) {
|
|
270
299
|
closeScope(__contextGet("db"), true);
|
|
271
|
-
let authorizedClaims =
|
|
272
|
-
authorizedClaims.validatedAt = __normalize(claims.validatedAt);
|
|
300
|
+
let authorizedClaims = this.#tokenClaims(__contextGet("token"), claims, true);
|
|
273
301
|
let encoded = __normalize(this.#tokens.sign(authorizedClaims));
|
|
274
302
|
if (__requireBoolean(__normalize(task.pollResult) === null)) {
|
|
275
303
|
return { status: 200, authorization: encoded };
|
|
@@ -291,10 +319,9 @@ export class Runtime {
|
|
|
291
319
|
}
|
|
292
320
|
closeScope(__contextGet("db"), true);
|
|
293
321
|
let result = __normalize(__contextGet("response").result(body));
|
|
294
|
-
let updated =
|
|
295
|
-
updated.validatedAt = __normalize(claims.validatedAt);
|
|
322
|
+
let updated = this.#tokenClaims(__contextGet("token"), claims, __normalize(result.status) < 400);
|
|
296
323
|
result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
|
|
297
|
-
if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
324
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(task.internal) !== true) && __requireBoolean(__normalize(this.#definition.settings.requestEvent))) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
298
325
|
return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
|
|
299
326
|
}
|
|
300
327
|
return result;
|
|
@@ -311,6 +338,9 @@ export class Runtime {
|
|
|
311
338
|
__contextScope.push(__contextSet("db", __capturedContext3));
|
|
312
339
|
error = __boundary(error);
|
|
313
340
|
closeScope(__contextGet("db"), false);
|
|
341
|
+
if (__requireBoolean(__isKindof(error, HttpFailure))) {
|
|
342
|
+
return __normalize(error.result());
|
|
343
|
+
}
|
|
314
344
|
if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
|
|
315
345
|
return failure(401, "Unauthorized");
|
|
316
346
|
}
|
|
@@ -335,6 +365,83 @@ export class Runtime {
|
|
|
335
365
|
__contextRestore(__contextScope);
|
|
336
366
|
}
|
|
337
367
|
}
|
|
368
|
+
#tokenClaims(token, claims, allowRenewal) {
|
|
369
|
+
__requireArity(arguments.length, [0, 1, 2], "tokenClaims");
|
|
370
|
+
token = __boundary(token);
|
|
371
|
+
claims = __boundary(claims);
|
|
372
|
+
allowRenewal = __boundary(allowRenewal);
|
|
373
|
+
let updated = __normalize(token.snapshot());
|
|
374
|
+
updated.validatedAt = __normalize(claims.validatedAt);
|
|
375
|
+
if (__requireBoolean(__requireBoolean(allowRenewal) && __requireBoolean(__normalize(token.renewalRequested())))) {
|
|
376
|
+
updated = __normalize(this.#tokens.renew(updated));
|
|
377
|
+
}
|
|
378
|
+
return updated;
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
refreshTokens(tokens) {
|
|
382
|
+
const __contextScope = [];
|
|
383
|
+
try {
|
|
384
|
+
__requireArity(arguments.length, [0], "refreshTokens");
|
|
385
|
+
tokens = __boundary(tokens);
|
|
386
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isArray(tokens))) || __requireBoolean(__normalize(tokens.length) === 0)) || __requireBoolean(__normalize(tokens.length) > 64))) {
|
|
387
|
+
throw "Token refresh requires 1 to 64 tokens";
|
|
388
|
+
}
|
|
389
|
+
let seen = [];
|
|
390
|
+
for (const encoded of tokens) {
|
|
391
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(encoded))) || __requireBoolean(encoded === "")) || __requireBoolean(__normalize(encoded.length) > 16384)) || __requireBoolean(__normalize(seen.includes(encoded))))) {
|
|
392
|
+
throw "Invalid refresh token";
|
|
393
|
+
}
|
|
394
|
+
seen.push(encoded);
|
|
395
|
+
}
|
|
396
|
+
let owner = __normalize(__contextGet("token").clientId);
|
|
397
|
+
let results = [];
|
|
398
|
+
let pending = __normalize(__hostGlobal(["Promise"]).resolve(null));
|
|
399
|
+
for (const encoded of tokens) {
|
|
400
|
+
let child = __normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(__contextGet("request").headers), { authorization: `Bearer ${encoded}` })) }));
|
|
401
|
+
pending = this.#refreshOne(pending, results, encoded, owner, child);
|
|
402
|
+
}
|
|
403
|
+
return pending.then(__withArity((ignored) => {
|
|
404
|
+
ignored = __boundary(ignored);
|
|
405
|
+
return results;
|
|
406
|
+
return null;
|
|
407
|
+
}, [0], "closure"));
|
|
408
|
+
return null;
|
|
409
|
+
} finally {
|
|
410
|
+
__contextRestore(__contextScope);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
#refreshOne(pending, results, encoded, owner, child) {
|
|
414
|
+
__requireArity(arguments.length, [0, 1, 2, 3, 4], "refreshOne");
|
|
415
|
+
pending = __boundary(pending);
|
|
416
|
+
results = __boundary(results);
|
|
417
|
+
encoded = __boundary(encoded);
|
|
418
|
+
owner = __boundary(owner);
|
|
419
|
+
child = __boundary(child);
|
|
420
|
+
return pending.then(__withArity((ignored) => {
|
|
421
|
+
ignored = __boundary(ignored);
|
|
422
|
+
let checked = null;
|
|
423
|
+
try {
|
|
424
|
+
checked = __normalize(this.#tokens.read(`Bearer ${encoded}`));
|
|
425
|
+
} catch (error) {
|
|
426
|
+
return failure(401, "Unauthorized");
|
|
427
|
+
}
|
|
428
|
+
if (__requireBoolean(__normalize(checked.clientId) !== owner)) {
|
|
429
|
+
return failure(401, "Unauthorized");
|
|
430
|
+
}
|
|
431
|
+
return this.handle({ request: child, body: "{}", internal: true });
|
|
432
|
+
return null;
|
|
433
|
+
}, [0], "closure")).then(__withArity((result) => {
|
|
434
|
+
result = __boundary(result);
|
|
435
|
+
let updated = null;
|
|
436
|
+
if (__requireBoolean(__normalize(result.status) < 400)) {
|
|
437
|
+
updated = result.headers["x-lango-token"];
|
|
438
|
+
}
|
|
439
|
+
__add(results, { previous: encoded, token: updated, status: __normalize(result.status) });
|
|
440
|
+
return null;
|
|
441
|
+
return null;
|
|
442
|
+
}, [0], "closure"));
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
338
445
|
#event(name, input) {
|
|
339
446
|
const __contextScope = [];
|
|
340
447
|
try {
|
|
@@ -381,9 +488,12 @@ export class Runtime {
|
|
|
381
488
|
const __contextScope = [];
|
|
382
489
|
try {
|
|
383
490
|
let claims = __normalize(__contextGet("token").snapshot());
|
|
384
|
-
if (__requireBoolean(
|
|
491
|
+
if (__requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000)) {
|
|
385
492
|
return null;
|
|
386
493
|
}
|
|
494
|
+
if (__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events))))) {
|
|
495
|
+
return __normalize(__hostGlobal(["Date"]).now());
|
|
496
|
+
}
|
|
387
497
|
let original = __normalize(__hostGlobal(["JSON"]).stringify(claims));
|
|
388
498
|
__contextScope.push(__contextSet("token", new Token(claims, true)));
|
|
389
499
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n\nRuntime(definition)\n @serverContext = new ServerContext()\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @middlewares[name] = handler\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n @routes.add(route)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n length = -1\n for @routes as route\n if route.path == path\n return route\n if route.path.endsWith(\"/*\")\n prefix = route.path.slice(0, -1)\n if path.startsWith(prefix) and prefix.length > length\n best = route\n length = prefix.length\n return best\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n route = match(request.path)\n if route == null\n return failure(404, \"RouteNotFound\")\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = token.snapshot()\n authorizedClaims.validatedAt = claims.validatedAt\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n closeScope(db, false)\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if !(\"validate\" in @events) or Date/now() - claims.validatedAt < 1000\n return null\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA;;;;;;;;;;;AA0PA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA;;;;;;;;;;;AAuUA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
package/dist/server_context.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routeInfo } from "./route_info.mjs";
|
|
1
2
|
import * as threads from "node:worker_threads";
|
|
2
3
|
import {
|
|
3
4
|
hostGlobal as __hostGlobal,
|
|
@@ -13,8 +14,30 @@ import {
|
|
|
13
14
|
} from "./.lango/runtime.mjs";
|
|
14
15
|
|
|
15
16
|
export class ServerContext {
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
#routes;
|
|
18
|
+
#refresh;
|
|
19
|
+
constructor(definitions = null, refresh = null) {
|
|
20
|
+
definitions = __boundary(definitions);
|
|
21
|
+
refresh = __boundary(refresh);
|
|
22
|
+
if (__requireBoolean(definitions === null)) {
|
|
23
|
+
definitions = [];
|
|
24
|
+
}
|
|
25
|
+
this.#routes = routeInfo(definitions);
|
|
26
|
+
this.#refresh = refresh;
|
|
27
|
+
}
|
|
28
|
+
refreshTokens(tokens) {
|
|
29
|
+
__requireArity(arguments.length, [0], "refreshTokens");
|
|
30
|
+
tokens = __boundary(tokens);
|
|
31
|
+
if (__requireBoolean(__normalize(this.#refresh) === null)) {
|
|
32
|
+
throw "Token refresh is unavailable";
|
|
33
|
+
}
|
|
34
|
+
let refresh = __normalize(this.#refresh);
|
|
35
|
+
return __call(refresh, tokens);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
routes() {
|
|
39
|
+
return __fromJson(__toJson(__normalize(this.#routes)));
|
|
40
|
+
return null;
|
|
18
41
|
}
|
|
19
42
|
publish(path, key, data) {
|
|
20
43
|
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class ServerContext()\n methods\n publish(path, key, data)\n cursor(path, key)\n\nServerContext()\n
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null, refresh = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n\nServerContext(definitions = null, refresh = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/static_files.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import * as path from "node:path";
|
|
|
3
3
|
import * as files from "serve-static";
|
|
4
4
|
import {
|
|
5
5
|
hostGlobal as __hostGlobal,
|
|
6
|
+
hostGlobalCall as __hostGlobalCall,
|
|
6
7
|
isNumber as __isNumber,
|
|
7
8
|
isString as __isString,
|
|
8
9
|
isBool as __isBool,
|
|
@@ -21,6 +22,7 @@ import {
|
|
|
21
22
|
export class StaticFiles {
|
|
22
23
|
#settings;
|
|
23
24
|
#serve;
|
|
25
|
+
#runtime;
|
|
24
26
|
constructor(settings) {
|
|
25
27
|
__requireArity(arguments.length, [0], "constructor");
|
|
26
28
|
settings = __boundary(settings);
|
|
@@ -28,7 +30,11 @@ export class StaticFiles {
|
|
|
28
30
|
if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
|
|
29
31
|
throw "Static directory must be a directory";
|
|
30
32
|
}
|
|
33
|
+
if (__requireBoolean(__requireBoolean(__normalize(settings.fallback) !== null) && __requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(path.join(__normalize(settings.directory), __normalize(settings.fallback))))).isFile()))))) {
|
|
34
|
+
throw "Static fallback must be a file";
|
|
35
|
+
}
|
|
31
36
|
this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
|
|
37
|
+
this.#runtime = __normalize(files.default(__normalize(settings.directory), { index: false, dotfiles: "allow", fallthrough: false, redirect: false }));
|
|
32
38
|
}
|
|
33
39
|
receive(req, res, failed) {
|
|
34
40
|
__requireArity(arguments.length, [0, 1, 2], "receive");
|
|
@@ -48,39 +54,88 @@ export class StaticFiles {
|
|
|
48
54
|
req.url = `/${__normalize(req.url)}`;
|
|
49
55
|
}
|
|
50
56
|
}
|
|
51
|
-
let
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
} else if (__normalize(error.status) === 404) {
|
|
70
|
-
status = 404;
|
|
57
|
+
let local = __normalize(__normalize(req.url.split("?"))[0]);
|
|
58
|
+
let decoded = null;
|
|
59
|
+
try {
|
|
60
|
+
decoded = __hostGlobalCall(["decodeURIComponent"], local);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
__call(failed, 400, "InvalidPath");
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
if (__requireBoolean(__requireBoolean(__normalize(decoded.includes("\\"))) || __requireBoolean(__normalize(decoded.includes(__normalize(__hostGlobal(["String"]).fromCharCode(0))))))) {
|
|
66
|
+
__call(failed, 400, "InvalidPath");
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
let segments = __normalize(decoded.split("/"));
|
|
70
|
+
let runtime = false;
|
|
71
|
+
for (const [index, segment] of __entries(segments)) {
|
|
72
|
+
if (__requireBoolean(__normalize(segment.startsWith(".")))) {
|
|
73
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(index === 1) && __requireBoolean(segment === ".lango")) && __requireBoolean(__normalize(this.#settings.runtime)))) {
|
|
74
|
+
runtime = true;
|
|
71
75
|
} else {
|
|
72
|
-
|
|
73
|
-
|
|
76
|
+
__call(failed, 403, "Forbidden");
|
|
77
|
+
return null;
|
|
74
78
|
}
|
|
75
79
|
}
|
|
76
|
-
|
|
80
|
+
}
|
|
81
|
+
let done = __withArity((error) => {
|
|
82
|
+
error = __boundary(error);
|
|
83
|
+
this.#failure(req, res, failed, error, decoded);
|
|
77
84
|
return null;
|
|
78
85
|
}, [0], "closure");
|
|
79
86
|
let serve = __normalize(this.#serve);
|
|
87
|
+
if (__requireBoolean(runtime)) {
|
|
88
|
+
serve = __normalize(this.#runtime);
|
|
89
|
+
}
|
|
80
90
|
__call(serve, req, res, done);
|
|
81
91
|
return null;
|
|
82
92
|
return null;
|
|
83
93
|
}
|
|
94
|
+
#failure(req, res, failed, error, pathname = null) {
|
|
95
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "failure");
|
|
96
|
+
req = __boundary(req);
|
|
97
|
+
res = __boundary(res);
|
|
98
|
+
failed = __boundary(failed);
|
|
99
|
+
error = __boundary(error);
|
|
100
|
+
pathname = __boundary(pathname);
|
|
101
|
+
if (__requireBoolean(__normalize(res.headersSent))) {
|
|
102
|
+
__normalize(res.destroy());
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
let status = 404;
|
|
106
|
+
let code = "NotFound";
|
|
107
|
+
if (__requireBoolean(error !== null)) {
|
|
108
|
+
if (__normalize(error.status) === 400) {
|
|
109
|
+
status = 400;
|
|
110
|
+
code = "InvalidPath";
|
|
111
|
+
} else if (__normalize(error.status) === 403) {
|
|
112
|
+
status = 403;
|
|
113
|
+
code = "Forbidden";
|
|
114
|
+
} else if (__normalize(error.status) === 416) {
|
|
115
|
+
status = 416;
|
|
116
|
+
code = "RangeNotSatisfiable";
|
|
117
|
+
} else if (__normalize(error.status) === 404) {
|
|
118
|
+
status = 404;
|
|
119
|
+
} else {
|
|
120
|
+
status = 500;
|
|
121
|
+
code = "InternalServerError";
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(status === 404) && __requireBoolean(pathname !== null)) && __requireBoolean(__normalize(this.#settings.fallback) !== null)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith("/.lango"))))) && __requireBoolean(__normalize(path.posix.extname(pathname)) === "")) && __requireBoolean(acceptsHTML(req.headers.accept)))) {
|
|
125
|
+
req.url = `/${__normalize(this.#settings.fallback)}`;
|
|
126
|
+
let done = __withArity((error) => {
|
|
127
|
+
error = __boundary(error);
|
|
128
|
+
this.#failure(req, res, failed, error);
|
|
129
|
+
return null;
|
|
130
|
+
}, [0], "closure");
|
|
131
|
+
let serve = __normalize(this.#serve);
|
|
132
|
+
__call(serve, req, res, done);
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
__call(failed, status, code);
|
|
136
|
+
return null;
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
84
139
|
}
|
|
85
140
|
export function staticOptions(root, spec) {
|
|
86
141
|
__requireArity(arguments.length, [0, 1], "staticOptions");
|
|
@@ -92,7 +147,7 @@ export function staticOptions(root, spec) {
|
|
|
92
147
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
|
|
93
148
|
throw "static must be a map";
|
|
94
149
|
}
|
|
95
|
-
let allowed = ["path", "directory", "index"];
|
|
150
|
+
let allowed = ["path", "directory", "index", "fallback", "runtime"];
|
|
96
151
|
for (const [key, value] of __entries(spec)) {
|
|
97
152
|
if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
|
|
98
153
|
throw `Unknown static option: ${key}`;
|
|
@@ -119,7 +174,48 @@ export function staticOptions(root, spec) {
|
|
|
119
174
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
|
|
120
175
|
throw "Static index must be a file name";
|
|
121
176
|
}
|
|
122
|
-
|
|
177
|
+
let fallback = __normalize(spec.fallback);
|
|
178
|
+
if (__requireBoolean(__requireBoolean(fallback !== null) && __requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(fallback))) || __requireBoolean(fallback === "")) || __requireBoolean(__normalize(fallback.startsWith(".")))) || __requireBoolean(__normalize(fallback.includes("/")))) || __requireBoolean(__normalize(fallback.includes("\\")))))) {
|
|
179
|
+
throw "Static fallback must be a file name";
|
|
180
|
+
}
|
|
181
|
+
let runtime = __normalize(spec.runtime);
|
|
182
|
+
if (__requireBoolean(__requireBoolean(runtime === null) || __requireBoolean(runtime === "false"))) {
|
|
183
|
+
runtime = false;
|
|
184
|
+
}
|
|
185
|
+
if (__requireBoolean(runtime === "true")) {
|
|
186
|
+
runtime = true;
|
|
187
|
+
}
|
|
188
|
+
if (__requireBoolean(!__requireBoolean(__isBool(runtime)))) {
|
|
189
|
+
throw "Static runtime must be boolean";
|
|
190
|
+
}
|
|
191
|
+
return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index, fallback: fallback, runtime: runtime };
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function acceptsHTML(value) {
|
|
196
|
+
__requireArity(arguments.length, [0], "acceptsHTML");
|
|
197
|
+
value = __boundary(value);
|
|
198
|
+
if (__requireBoolean(!__requireBoolean(__isString(value)))) {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
let zero = new (__hostGlobal(["RegExp"]))("^q\\s*=\\s*0(?:\\.0*)?$", "i");
|
|
202
|
+
for (const range of __normalize(value.split(","))) {
|
|
203
|
+
let parts = __normalize(range.split(";"));
|
|
204
|
+
let media = __normalize(parts[0]);
|
|
205
|
+
let type = __normalize(__normalize(media.trim()).toLowerCase());
|
|
206
|
+
if (__requireBoolean(__requireBoolean(type === "text/html") || __requireBoolean(type === "application/xhtml+xml"))) {
|
|
207
|
+
let allowed = true;
|
|
208
|
+
for (const parameter of __normalize(parts.slice(1))) {
|
|
209
|
+
if (__requireBoolean(__normalize(zero.test(__normalize(parameter.trim()))))) {
|
|
210
|
+
allowed = false;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (__requireBoolean(allowed)) {
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return false;
|
|
123
219
|
return null;
|
|
124
220
|
}
|
|
125
221
|
//# sourceMappingURL=static_files.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n done = (error)\n capture res\n capture failed\n if res.headersSent\n
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|