@lango-project/lango-server 0.1.2 → 0.2.2

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 (50) hide show
  1. package/README.md +115 -12
  2. package/dist/.lango/localization.mjs +108 -0
  3. package/dist/.lango/runtime.mjs +33 -7
  4. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  5. package/dist/.lango/vendor/i18next.mjs +2434 -0
  6. package/dist/cli/.lango/localization.mjs +108 -0
  7. package/dist/cli/.lango/runtime.mjs +33 -7
  8. package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
  9. package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
  10. package/dist/cli/error_details.mjs +45 -0
  11. package/dist/cli/error_details.mjs.map +1 -0
  12. package/dist/cli/options.mjs +2 -2
  13. package/dist/cli/options.mjs.map +1 -1
  14. package/dist/cli/server.mjs +64 -21
  15. package/dist/cli/server.mjs.map +1 -1
  16. package/dist/cli/static_files.mjs +123 -25
  17. package/dist/cli/static_files.mjs.map +1 -1
  18. package/dist/cli/trace.mjs +53 -0
  19. package/dist/cli/trace.mjs.map +1 -0
  20. package/dist/error_details.mjs +45 -0
  21. package/dist/error_details.mjs.map +1 -0
  22. package/dist/options.mjs +2 -2
  23. package/dist/options.mjs.map +1 -1
  24. package/dist/request_identity.mjs +22 -0
  25. package/dist/request_identity.mjs.map +1 -0
  26. package/dist/runtime.mjs +99 -10
  27. package/dist/runtime.mjs.map +1 -1
  28. package/dist/server.mjs +64 -21
  29. package/dist/server.mjs.map +1 -1
  30. package/dist/server_context.mjs +14 -1
  31. package/dist/server_context.mjs.map +1 -1
  32. package/dist/static_files.mjs +123 -25
  33. package/dist/static_files.mjs.map +1 -1
  34. package/dist/token.mjs +26 -13
  35. package/dist/token.mjs.map +1 -1
  36. package/dist/trace.mjs +53 -0
  37. package/dist/trace.mjs.map +1 -0
  38. package/dist/worker.mjs +1 -0
  39. package/dist/worker.mjs.map +1 -1
  40. package/package.json +2 -2
  41. package/src/error_details.lango +21 -0
  42. package/src/options.lango +2 -2
  43. package/src/request_identity.lango +9 -0
  44. package/src/runtime.lango +88 -5
  45. package/src/server.lango +42 -5
  46. package/src/server_context.lango +10 -2
  47. package/src/static_files.lango +102 -23
  48. package/src/token.lango +13 -3
  49. package/src/trace.lango +23 -0
  50. package/src/worker.lango +1 -0
@@ -0,0 +1,45 @@
1
+ import {
2
+ isNumber as __isNumber,
3
+ isString as __isString,
4
+ isBool as __isBool,
5
+ isObject as __isObject,
6
+ isArray as __isArray,
7
+ requireBoolean as __requireBoolean,
8
+ normalize as __normalize,
9
+ boundary as __boundary,
10
+ requireArity as __requireArity,
11
+ } from "./.lango/runtime.mjs";
12
+
13
+ export function errorDetails(error) {
14
+ __requireArity(arguments.length, [0], "errorDetails");
15
+ error = __boundary(error);
16
+ if (__requireBoolean(__isObject(error))) {
17
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.stack))) && __requireBoolean(__normalize(error.stack) !== ""))) {
18
+ return __normalize(error.stack);
19
+ }
20
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
21
+ return __normalize(error.message);
22
+ }
23
+ if (__requireBoolean(__isString(__normalize(error.code)))) {
24
+ return __normalize(error.code);
25
+ }
26
+ }
27
+ return `${error}`;
28
+ return null;
29
+ }
30
+
31
+ export function errorMessage(error) {
32
+ __requireArity(arguments.length, [0], "errorMessage");
33
+ error = __boundary(error);
34
+ if (__requireBoolean(__isObject(error))) {
35
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
36
+ return __normalize(error.message);
37
+ }
38
+ if (__requireBoolean(__isString(__normalize(error.code)))) {
39
+ return __normalize(error.code);
40
+ }
41
+ }
42
+ return `${error}`;
43
+ return null;
44
+ }
45
+ //# sourceMappingURL=error_details.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
@@ -38,7 +38,7 @@ export function options(root, supplied = null) {
38
38
  __requireArity(arguments.length, [0], "options");
39
39
  root = __boundary(root);
40
40
  supplied = __boundary(supplied);
41
- let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 1048576, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
41
+ let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 2097152, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
42
42
  if (__requireBoolean(supplied !== null)) {
43
43
  for (const [key, value] of __entries(supplied)) {
44
44
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(result, key)))) || __requireBoolean(key === "root"))) {
@@ -115,7 +115,7 @@ export function deployment(directory) {
115
115
  }
116
116
  seen.push(name);
117
117
  if (name === "static") {
118
- attributes(tag, ["path", "directory", "index"]);
118
+ attributes(tag, ["path", "directory", "index", "fallback", "runtime"]);
119
119
  settings.static = __normalize(tag.attributes());
120
120
  continue;
121
121
  } else if (name === "http") {
@@ -1 +1 @@
1
- {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 1048576\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
1
+ {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 2097152\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import { trace, responseLog } from "./trace.mjs";
2
3
  import { LongpollBroker } from "./longpoll_broker.mjs";
3
4
  import { LongpollSession } from "./longpoll_session.mjs";
4
5
  import { prepareDatabase } from "./database.mjs";
6
+ import { errorDetails } from "./error_details.mjs";
5
7
  import { deployment } from "./options.mjs";
6
8
  import { Routes } from "./routes.mjs";
7
9
  import { BodyReader } from "./body_reader.mjs";
@@ -119,6 +121,7 @@ export class Server {
119
121
  }
120
122
  #launch() {
121
123
  let settings = __normalize(this.#definition.settings);
124
+ trace(`Server starting: ${__normalize(settings.root)}; workers=${__normalize(settings.workers)}`);
122
125
  if (__requireBoolean(__normalize(settings.static) !== null)) {
123
126
  try {
124
127
  this.#static = new StaticFiles(__normalize(settings.static));
@@ -147,7 +150,7 @@ export class Server {
147
150
  try {
148
151
  error = __boundary(error);
149
152
  __normalize(this.#ready.reject(error));
150
- __normalize(__contextGet("log").err("Worker pool error"));
153
+ __normalize(__contextGet("log").err(`Worker pool error: ${errorDetails(error)}`));
151
154
  return null;
152
155
  } finally {
153
156
  __contextRestore(__contextScope);
@@ -228,6 +231,7 @@ export class Server {
228
231
  let record = __normalize(this.#tasks[__normalize(message.id)]);
229
232
  if (__requireBoolean(__normalize(message.kind) === "prepared")) {
230
233
  record.result = __normalize(message.result);
234
+ record.logIdentity = __normalize(message.logIdentity);
231
235
  this.#resetDeadline(record, __normalize(this.#definition.settings.eventTimeoutMs));
232
236
  }
233
237
  if (__requireBoolean(__normalize(message.kind) === "event")) {
@@ -274,6 +278,7 @@ export class Server {
274
278
  __requireArity(arguments.length, [0, 1], "trackResponse");
275
279
  req = __boundary(req);
276
280
  res = __boundary(res);
281
+ let target = __normalize(__normalize(req.url.split("?"))[0]);
277
282
  for (const record of __normalize(this.#connections)) {
278
283
  if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
279
284
  record.active = __numericAdd(__normalize(record.active), 1);
@@ -283,6 +288,11 @@ export class Server {
283
288
  return null;
284
289
  }
285
290
  state.done = true;
291
+ if (__requireBoolean(__normalize(res.writableFinished))) {
292
+ responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode));
293
+ } else {
294
+ trace(`HTTP ${__normalize(req.method)} ${target} connection closed before response completed`);
295
+ }
286
296
  record.active = __finite(__normalize(record.active) - 1);
287
297
  if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
288
298
  __normalize(record.socket.end());
@@ -311,6 +321,7 @@ export class Server {
311
321
  if (__requireBoolean(__normalize(this.#state) !== "running")) {
312
322
  return rejectHttp(req, res, 503, "Unavailable");
313
323
  }
324
+ trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
314
325
  if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
315
326
  let failed = __withArity((status, code) => {
316
327
  status = __boundary(status);
@@ -378,10 +389,16 @@ export class Server {
378
389
  return null;
379
390
  return null;
380
391
  }, [0], "closure")).catch(__withArity((error) => {
381
- error = __boundary(error);
382
- this.#send(res, failure(500, "InternalServerError"));
383
- return null;
384
- return null;
392
+ const __contextScope = [];
393
+ try {
394
+ error = __boundary(error);
395
+ __normalize(__contextGet("log").err(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])} request failed: ${errorDetails(error)}`));
396
+ this.#send(res, failure(500, "InternalServerError"));
397
+ return null;
398
+ return null;
399
+ } finally {
400
+ __contextRestore(__contextScope);
401
+ }
385
402
  }, [0], "closure"));
386
403
  return null;
387
404
  }
@@ -458,6 +475,8 @@ export class Server {
458
475
  return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
459
476
  }
460
477
  let id = __normalize(crypto.randomUUID());
478
+ res.langoRequestId = id;
479
+ trace(`[${id}] Queued request ${__normalize(req.method)} ${__normalize(req.url)}`);
461
480
  let record = { id: id, task: { authorize: authorize, pollResult: pollResult, body: body, request: { id: id, method: __normalize(req.method), path: __normalize(req.url), headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(req.headers))), remoteAddress: req.socket.remoteAddress } }, completed: __normalize(__hostGlobal(["Promise"]).withResolvers()), controller: new (__hostGlobal(["AbortController"]))(), started: false, result: null, expired: false, deadline: __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __normalize(settings.requestTimeoutMs)), timer: null };
462
481
  if (__requireBoolean(token !== null)) {
463
482
  record.task.request.headers.authorization = `Bearer ${token}`;
@@ -517,6 +536,7 @@ export class Server {
517
536
  let record = __normalize(this.#waiting.shift());
518
537
  record.started = true;
519
538
  this.#active = __numericAdd(__normalize(this.#active), 1);
539
+ trace(`[${__normalize(record.id)}] Dispatching to worker`);
520
540
  let pending = __normalize(this.#pool.run(__normalize(record.task), { signal: record.controller.signal }));
521
541
  this.#settle(record, pending);
522
542
  }
@@ -537,7 +557,7 @@ export class Server {
537
557
  try {
538
558
  error = __boundary(error);
539
559
  if (__requireBoolean(__normalize(record.result) !== null)) {
540
- __normalize(__contextGet("log").err(`[${__normalize(record.id)}] Request event interrupted; preserving prepared result`));
560
+ __normalize(__contextGet("log").err(`${__normalize(record.logIdentity)} Request event interrupted; preserving prepared result`));
541
561
  }
542
562
  this.#finish(record, __normalize(record.result), error);
543
563
  return null;
@@ -658,6 +678,7 @@ export class Server {
658
678
  __requireArity(arguments.length, [0, 1], "send");
659
679
  res = __boundary(res);
660
680
  result = __boundary(result);
681
+ trace(`HTTP response status=${__normalize(result.status)}`);
661
682
  if (__requireBoolean(__normalize(this.#state) === "closing")) {
662
683
  result.headers.connection = "close";
663
684
  }
@@ -699,20 +720,26 @@ function failure(status, code) {
699
720
  }
700
721
 
701
722
  function write(res, result) {
702
- __requireArity(arguments.length, [0, 1], "write");
703
- res = __boundary(res);
704
- result = __boundary(result);
705
- if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
706
- return null;
707
- }
723
+ const __contextScope = [];
708
724
  try {
709
- __normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
710
- __normalize(res.end(__normalize(result.body)));
711
- } catch (error) {
712
- __normalize(res.destroy());
725
+ __requireArity(arguments.length, [0, 1], "write");
726
+ res = __boundary(res);
727
+ result = __boundary(result);
728
+ if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
729
+ return null;
730
+ }
731
+ try {
732
+ __normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
733
+ __normalize(res.end(__normalize(result.body)));
734
+ } catch (error) {
735
+ __normalize(__contextGet("log").err(`[${__normalize(res.langoRequestId)}] Response write failed: ${errorDetails(error)}`));
736
+ __normalize(res.destroy());
737
+ }
738
+ return null;
739
+ return null;
740
+ } finally {
741
+ __contextRestore(__contextScope);
713
742
  }
714
- return null;
715
- return null;
716
743
  }
717
744
 
718
745
  function rejectHttp(req, res, status, code) {
@@ -734,10 +761,26 @@ function rejectHttp(req, res, status, code) {
734
761
  export function main(args) {
735
762
  __requireArity(arguments.length, [0], "main");
736
763
  args = __boundary(args);
737
- if (__requireBoolean(__normalize(args.length) !== 1)) {
738
- throw "Usage: lango-server <application-directory>";
764
+ let directory = null;
765
+ let verbose = false;
766
+ for (const arg of args) {
767
+ if (__requireBoolean(arg === "--verbose")) {
768
+ verbose = true;
769
+ } else {
770
+ if (__requireBoolean(__requireBoolean(__normalize(arg.startsWith("--"))) || __requireBoolean(directory !== null))) {
771
+ throw "Usage: lango-server <application-directory> [--verbose]";
772
+ }
773
+ directory = arg;
774
+ }
775
+ }
776
+ if (__requireBoolean(directory === null)) {
777
+ throw "Usage: lango-server <application-directory> [--verbose]";
778
+ }
779
+ if (__requireBoolean(verbose)) {
780
+ __hostGlobal(["process"]).env.LANGO_VERBOSE = "1";
739
781
  }
740
- let server = new Server(__normalize(args[0]));
782
+ trace(`Loading server configuration: ${directory}`);
783
+ let server = new Server(directory);
741
784
  let stop = () => {
742
785
  return __normalize(server.close()).catch(__withArity((error) => {
743
786
  const __contextScope = [];
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n if state.done\n return null\n state.done = true\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"[${record.id}] Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAoGA;;;;;;;;;;;;;;;;;AAgXA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\n responseLog(id, method, path, status)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;"}
@@ -1,8 +1,10 @@
1
+ import { trace } from "./trace.mjs";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import * as files from "serve-static";
4
5
  import {
5
6
  hostGlobal as __hostGlobal,
7
+ hostGlobalCall as __hostGlobalCall,
6
8
  isNumber as __isNumber,
7
9
  isString as __isString,
8
10
  isBool as __isBool,
@@ -21,6 +23,7 @@ import {
21
23
  export class StaticFiles {
22
24
  #settings;
23
25
  #serve;
26
+ #runtime;
24
27
  constructor(settings) {
25
28
  __requireArity(arguments.length, [0], "constructor");
26
29
  settings = __boundary(settings);
@@ -28,7 +31,11 @@ export class StaticFiles {
28
31
  if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
29
32
  throw "Static directory must be a directory";
30
33
  }
34
+ if (__requireBoolean(__requireBoolean(__normalize(settings.fallback) !== null) && __requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(path.join(__normalize(settings.directory), __normalize(settings.fallback))))).isFile()))))) {
35
+ throw "Static fallback must be a file";
36
+ }
31
37
  this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
38
+ this.#runtime = __normalize(files.default(__normalize(settings.directory), { index: false, dotfiles: "allow", fallthrough: false, redirect: false }));
32
39
  }
33
40
  receive(req, res, failed) {
34
41
  __requireArity(arguments.length, [0, 1, 2], "receive");
@@ -48,39 +55,89 @@ export class StaticFiles {
48
55
  req.url = `/${__normalize(req.url)}`;
49
56
  }
50
57
  }
51
- let done = __withArity((error) => {
52
- error = __boundary(error);
53
- if (__requireBoolean(__normalize(res.headersSent))) {
54
- __normalize(res.destroy());
55
- return null;
56
- }
57
- let status = 404;
58
- let code = "NotFound";
59
- if (__requireBoolean(error !== null)) {
60
- if (__normalize(error.status) === 400) {
61
- status = 400;
62
- code = "InvalidPath";
63
- } else if (__normalize(error.status) === 403) {
64
- status = 403;
65
- code = "Forbidden";
66
- } else if (__normalize(error.status) === 416) {
67
- status = 416;
68
- code = "RangeNotSatisfiable";
69
- } else if (__normalize(error.status) === 404) {
70
- status = 404;
58
+ let local = __normalize(__normalize(req.url.split("?"))[0]);
59
+ let decoded = null;
60
+ try {
61
+ decoded = __hostGlobalCall(["decodeURIComponent"], local);
62
+ } catch (error) {
63
+ __call(failed, 400, "InvalidPath");
64
+ return null;
65
+ }
66
+ if (__requireBoolean(__requireBoolean(__normalize(decoded.includes("\\"))) || __requireBoolean(__normalize(decoded.includes(__normalize(__hostGlobal(["String"]).fromCharCode(0))))))) {
67
+ __call(failed, 400, "InvalidPath");
68
+ return null;
69
+ }
70
+ let segments = __normalize(decoded.split("/"));
71
+ let runtime = false;
72
+ for (const [index, segment] of __entries(segments)) {
73
+ if (__requireBoolean(__normalize(segment.startsWith(".")))) {
74
+ if (__requireBoolean(__requireBoolean(__requireBoolean(index === 1) && __requireBoolean(segment === ".lango")) && __requireBoolean(__normalize(this.#settings.runtime)))) {
75
+ runtime = true;
71
76
  } else {
72
- status = 500;
73
- code = "InternalServerError";
77
+ __call(failed, 403, "Forbidden");
78
+ return null;
74
79
  }
75
80
  }
76
- __call(failed, status, code);
81
+ }
82
+ let done = __withArity((error) => {
83
+ error = __boundary(error);
84
+ this.#failure(req, res, failed, error, decoded);
77
85
  return null;
78
86
  }, [0], "closure");
79
87
  let serve = __normalize(this.#serve);
88
+ if (__requireBoolean(runtime)) {
89
+ serve = __normalize(this.#runtime);
90
+ }
91
+ trace(`Static ${__normalize(req.method)} ${pathname}: directory=${__normalize(this.#settings.directory)}; index=${__normalize(this.#settings.index)}; runtime=${runtime}`);
80
92
  __call(serve, req, res, done);
81
93
  return null;
82
94
  return null;
83
95
  }
96
+ #failure(req, res, failed, error, pathname = null) {
97
+ __requireArity(arguments.length, [0, 1, 2, 3], "failure");
98
+ req = __boundary(req);
99
+ res = __boundary(res);
100
+ failed = __boundary(failed);
101
+ error = __boundary(error);
102
+ pathname = __boundary(pathname);
103
+ if (__requireBoolean(__normalize(res.headersSent))) {
104
+ __normalize(res.destroy());
105
+ return null;
106
+ }
107
+ let status = 404;
108
+ let code = "NotFound";
109
+ if (__requireBoolean(error !== null)) {
110
+ if (__normalize(error.status) === 400) {
111
+ status = 400;
112
+ code = "InvalidPath";
113
+ } else if (__normalize(error.status) === 403) {
114
+ status = 403;
115
+ code = "Forbidden";
116
+ } else if (__normalize(error.status) === 416) {
117
+ status = 416;
118
+ code = "RangeNotSatisfiable";
119
+ } else if (__normalize(error.status) === 404) {
120
+ status = 404;
121
+ } else {
122
+ status = 500;
123
+ code = "InternalServerError";
124
+ }
125
+ }
126
+ 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)))) {
127
+ req.url = `/${__normalize(this.#settings.fallback)}`;
128
+ let done = __withArity((error) => {
129
+ error = __boundary(error);
130
+ this.#failure(req, res, failed, error);
131
+ return null;
132
+ }, [0], "closure");
133
+ let serve = __normalize(this.#serve);
134
+ __call(serve, req, res, done);
135
+ return null;
136
+ }
137
+ __call(failed, status, code);
138
+ return null;
139
+ return null;
140
+ }
84
141
  }
85
142
  export function staticOptions(root, spec) {
86
143
  __requireArity(arguments.length, [0, 1], "staticOptions");
@@ -92,7 +149,7 @@ export function staticOptions(root, spec) {
92
149
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
93
150
  throw "static must be a map";
94
151
  }
95
- let allowed = ["path", "directory", "index"];
152
+ let allowed = ["path", "directory", "index", "fallback", "runtime"];
96
153
  for (const [key, value] of __entries(spec)) {
97
154
  if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
98
155
  throw `Unknown static option: ${key}`;
@@ -119,7 +176,48 @@ export function staticOptions(root, spec) {
119
176
  if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
120
177
  throw "Static index must be a file name";
121
178
  }
122
- return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
179
+ let fallback = __normalize(spec.fallback);
180
+ 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("\\")))))) {
181
+ throw "Static fallback must be a file name";
182
+ }
183
+ let runtime = __normalize(spec.runtime);
184
+ if (__requireBoolean(__requireBoolean(runtime === null) || __requireBoolean(runtime === "false"))) {
185
+ runtime = false;
186
+ }
187
+ if (__requireBoolean(runtime === "true")) {
188
+ runtime = true;
189
+ }
190
+ if (__requireBoolean(!__requireBoolean(__isBool(runtime)))) {
191
+ throw "Static runtime must be boolean";
192
+ }
193
+ return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index, fallback: fallback, runtime: runtime };
194
+ return null;
195
+ }
196
+
197
+ function acceptsHTML(value) {
198
+ __requireArity(arguments.length, [0], "acceptsHTML");
199
+ value = __boundary(value);
200
+ if (__requireBoolean(!__requireBoolean(__isString(value)))) {
201
+ return false;
202
+ }
203
+ let zero = new (__hostGlobal(["RegExp"]))("^q\\s*=\\s*0(?:\\.0*)?$", "i");
204
+ for (const range of __normalize(value.split(","))) {
205
+ let parts = __normalize(range.split(";"));
206
+ let media = __normalize(parts[0]);
207
+ let type = __normalize(__normalize(media.trim()).toLowerCase());
208
+ if (__requireBoolean(__requireBoolean(type === "text/html") || __requireBoolean(type === "application/xhtml+xml"))) {
209
+ let allowed = true;
210
+ for (const parameter of __normalize(parts.slice(1))) {
211
+ if (__requireBoolean(__normalize(zero.test(__normalize(parameter.trim()))))) {
212
+ allowed = false;
213
+ }
214
+ }
215
+ if (__requireBoolean(allowed)) {
216
+ return true;
217
+ }
218
+ }
219
+ }
220
+ return false;
123
221
  return null;
124
222
  }
125
223
  //# 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 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 failed(status, code)\n serve = @serve\n serve(req, res, done)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport 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 trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${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":";;;;;;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}