@lango-project/lango-server 0.2.2 → 0.2.4

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 (158) hide show
  1. package/README.md +252 -29
  2. package/dist/.lango/runtime.mjs +16 -0
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/builder.mjs +26 -2
  6. package/dist/builder.mjs.map +1 -1
  7. package/dist/cli/.lango/runtime.mjs +16 -0
  8. package/dist/cli/body_reader.mjs +15 -14
  9. package/dist/cli/body_reader.mjs.map +1 -1
  10. package/dist/cli/client_identity.mjs +250 -0
  11. package/dist/cli/client_identity.mjs.map +1 -0
  12. package/dist/cli/database.mjs +23 -8
  13. package/dist/cli/database.mjs.map +1 -1
  14. package/dist/cli/database_scope.mjs +11 -0
  15. package/dist/cli/database_scope.mjs.map +1 -1
  16. package/dist/cli/endpoint.mjs +11 -7
  17. package/dist/cli/endpoint.mjs.map +1 -1
  18. package/dist/cli/longpoll_broker.mjs +9 -8
  19. package/dist/cli/longpoll_broker.mjs.map +1 -1
  20. package/dist/cli/longpoll_options.mjs +8 -7
  21. package/dist/cli/longpoll_options.mjs.map +1 -1
  22. package/dist/cli/longpoll_session.mjs +11 -10
  23. package/dist/cli/longpoll_session.mjs.map +1 -1
  24. package/dist/cli/middleware.mjs +1 -1
  25. package/dist/cli/middleware.mjs.map +1 -1
  26. package/dist/cli/options.mjs +41 -4
  27. package/dist/cli/options.mjs.map +1 -1
  28. package/dist/cli/origin.mjs +87 -0
  29. package/dist/cli/origin.mjs.map +1 -0
  30. package/dist/cli/policy.mjs +121 -0
  31. package/dist/cli/policy.mjs.map +1 -0
  32. package/dist/cli/postgres_adapter.mjs +15 -3
  33. package/dist/cli/postgres_adapter.mjs.map +1 -1
  34. package/dist/cli/routes.mjs +69 -18
  35. package/dist/cli/routes.mjs.map +1 -1
  36. package/dist/cli/server.mjs +88 -81
  37. package/dist/cli/server.mjs.map +1 -1
  38. package/dist/cli/static_files.mjs +5 -4
  39. package/dist/cli/static_files.mjs.map +1 -1
  40. package/dist/client_identity.mjs +250 -0
  41. package/dist/client_identity.mjs.map +1 -0
  42. package/dist/database.mjs +23 -8
  43. package/dist/database.mjs.map +1 -1
  44. package/dist/database_action.mjs +71 -0
  45. package/dist/database_action.mjs.map +1 -0
  46. package/dist/database_scope.mjs +11 -0
  47. package/dist/database_scope.mjs.map +1 -1
  48. package/dist/endpoint.mjs +11 -7
  49. package/dist/endpoint.mjs.map +1 -1
  50. package/dist/execution_failure.mjs +30 -0
  51. package/dist/execution_failure.mjs.map +1 -0
  52. package/dist/execution_identity.mjs +103 -0
  53. package/dist/execution_identity.mjs.map +1 -0
  54. package/dist/execution_log.mjs +47 -0
  55. package/dist/execution_log.mjs.map +1 -0
  56. package/dist/execution_runtime.mjs +201 -0
  57. package/dist/execution_runtime.mjs.map +1 -0
  58. package/dist/execution_worker.mjs +41 -0
  59. package/dist/execution_worker.mjs.map +1 -0
  60. package/dist/executor.mjs +384 -0
  61. package/dist/executor.mjs.map +1 -0
  62. package/dist/group.mjs +49 -16
  63. package/dist/group.mjs.map +1 -1
  64. package/dist/http_failure.mjs +9 -2
  65. package/dist/http_failure.mjs.map +1 -1
  66. package/dist/job_configuration.mjs +37 -0
  67. package/dist/job_configuration.mjs.map +1 -0
  68. package/dist/job_context.mjs +61 -0
  69. package/dist/job_context.mjs.map +1 -0
  70. package/dist/library.mjs +31 -0
  71. package/dist/library.mjs.map +1 -1
  72. package/dist/longpoll_broker.mjs +9 -8
  73. package/dist/longpoll_broker.mjs.map +1 -1
  74. package/dist/longpoll_options.mjs +8 -7
  75. package/dist/longpoll_options.mjs.map +1 -1
  76. package/dist/longpoll_session.mjs +11 -10
  77. package/dist/longpoll_session.mjs.map +1 -1
  78. package/dist/middleware.mjs +1 -1
  79. package/dist/middleware.mjs.map +1 -1
  80. package/dist/module_loader.mjs +44 -0
  81. package/dist/module_loader.mjs.map +1 -0
  82. package/dist/options.mjs +41 -4
  83. package/dist/options.mjs.map +1 -1
  84. package/dist/origin.mjs +87 -0
  85. package/dist/origin.mjs.map +1 -0
  86. package/dist/policy.mjs +121 -0
  87. package/dist/policy.mjs.map +1 -0
  88. package/dist/postgres_adapter.mjs +15 -3
  89. package/dist/postgres_adapter.mjs.map +1 -1
  90. package/dist/postgres_worker.mjs +82 -19
  91. package/dist/postgres_worker.mjs.map +1 -1
  92. package/dist/queue_provider.mjs +52 -0
  93. package/dist/queue_provider.mjs.map +1 -0
  94. package/dist/response.mjs +1 -1
  95. package/dist/response.mjs.map +1 -1
  96. package/dist/route_info.mjs +1 -1
  97. package/dist/route_info.mjs.map +1 -1
  98. package/dist/routes.mjs +69 -18
  99. package/dist/routes.mjs.map +1 -1
  100. package/dist/runtime.mjs +287 -132
  101. package/dist/runtime.mjs.map +1 -1
  102. package/dist/server.mjs +88 -81
  103. package/dist/server.mjs.map +1 -1
  104. package/dist/server_context.mjs +21 -9
  105. package/dist/server_context.mjs.map +1 -1
  106. package/dist/static_files.mjs +5 -4
  107. package/dist/static_files.mjs.map +1 -1
  108. package/dist/token.mjs +34 -7
  109. package/dist/token.mjs.map +1 -1
  110. package/dist/tokens.mjs +11 -2
  111. package/dist/tokens.mjs.map +1 -1
  112. package/dist/worker.mjs +7 -6
  113. package/dist/worker.mjs.map +1 -1
  114. package/docs/jobs.md +123 -0
  115. package/docs/security.md +420 -0
  116. package/examples/security/README.md +160 -0
  117. package/examples/security/deploy.xml +12 -0
  118. package/examples/security/handlers.lango +610 -0
  119. package/examples/security/package.json +19 -0
  120. package/examples/security/passwords.lango +61 -0
  121. package/examples/security/routes.xml +14 -0
  122. package/examples/security/schema.lango +91 -0
  123. package/examples/security/setup.lango +30 -0
  124. package/package.json +14 -6
  125. package/src/builder.lango +22 -0
  126. package/src/client_identity.lango +184 -0
  127. package/src/database.lango +15 -4
  128. package/src/database_action.lango +30 -0
  129. package/src/database_scope.lango +7 -0
  130. package/src/endpoint.lango +12 -5
  131. package/src/execution_failure.lango +14 -0
  132. package/src/execution_identity.lango +71 -0
  133. package/src/execution_log.lango +28 -0
  134. package/src/execution_runtime.lango +135 -0
  135. package/src/execution_worker.lango +32 -0
  136. package/src/executor.lango +284 -0
  137. package/src/group.lango +36 -21
  138. package/src/http_failure.lango +9 -5
  139. package/src/job_configuration.lango +29 -0
  140. package/src/job_context.lango +44 -0
  141. package/src/library.lango +21 -0
  142. package/src/longpoll_options.lango +11 -5
  143. package/src/middleware.lango +1 -1
  144. package/src/module_loader.lango +25 -0
  145. package/src/options.lango +41 -2
  146. package/src/origin.lango +56 -0
  147. package/src/policy.lango +84 -0
  148. package/src/postgres_adapter.lango +12 -0
  149. package/src/postgres_worker.lango +54 -3
  150. package/src/queue_provider.lango +30 -0
  151. package/src/response.lango +1 -1
  152. package/src/route_info.lango +2 -0
  153. package/src/routes.lango +74 -15
  154. package/src/runtime.lango +173 -94
  155. package/src/server.lango +9 -2
  156. package/src/server_context.lango +10 -2
  157. package/src/token.lango +26 -5
  158. package/src/tokens.lango +10 -3
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport \"./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\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\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 trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\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 trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\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 log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\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 trace(\"${requestIdentity(request.id, token)} Matched route ${matched.route.path}; fresh=${fresh}\")\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 trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != 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 trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\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 trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n capture token\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 log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\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 trace(\"${requestIdentity(request.id, token)} Running event ${name}\")\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 logIdentity: requestIdentity(id, token)\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 capture request\n capture token\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;;AAmVA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport \"./module_loader\"\n class ModuleLoader\nimport \"./route_info\"\n routeInfo(definitions)\nimport js global Number\nimport \"./client_identity\"\n class ClientIdentity\nimport \"./origin\"\n originAllowed(spec, request)\nimport \"./trace\"\n trace(message)\nimport \"./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\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\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 rotate = ()\n return rotateClient()\n @serverContext = new ServerContext(definition.routes, refresh, rotate)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @loader = new ModuleLoader()\n @queueFactory = null\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n @clients = null\n if definition.settings.client != null\n @clients = new ClientIdentity(definition.settings.client, @database)\n\nRuntime:preload()\n trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\n definitions = @definition.routes\n pending = @database.open()\n if @definition.queueProvider != null\n pending = prepareQueue(pending)\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:prepareQueue(pending)\n return chain pending\n then(ignored)\n return @loader.target(@definition.queueProvider)\n then(factory)\n @queueFactory = factory\n return null\n\nRuntime:queueSender()\n if @queueFactory == null\n return null\n factory = @queueFactory\n return factory(@definition.queueProvider.options)\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 policy: route.policy\n reauthSeconds: route.reauthSeconds\n legacyAuth: route.legacyAuth\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 trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\n return @loader.target(spec)\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 if !originAllowed(@definition.settings.origin, request)\n return failure(403, \"OriginRejected\")\n fresh = request.headers.authorization == null\n claims = null\n try\n if !fresh\n claims = @tokens.read(request.headers.authorization)\n catch error\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n metadata = routeInfo([route])\n selected = Object/freeze(metadata[0])\n context request = Object/freeze(Object/assign({}, request, {\n route: selected\n }))\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 db = @database.scope()\n context clientIdentity = null\n restored = false\n try\n if @clients != null\n context clientIdentity = @clients.begin(claims, @tokens)\n claims = clientIdentity.claims\n fresh = clientIdentity.fresh\n restored = clientIdentity.restored\n if claims == null\n claims = @tokens.create()\n catch error\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n log.err(\"[${request.id}] Client identity failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n return process(task, route, input, claims, fresh, restored)\n\nRuntime:rotateClient()\n context clientIdentity\n if @clients == null or clientIdentity == null\n throw \"Managed client identity is unavailable\"\n if clientIdentity.closed\n throw \"Client identity scope is closed\"\n clientIdentity.rotate = true\n return null\n\nRuntime:signResponse(claims)\n context clientIdentity\n context response\n if @clients == null\n return @tokens.sign(claims)\n return @clients.publish(clientIdentity, claims, response, @tokens)\n\nRuntime:process(task, route, input, claims, fresh, restored)\n context request\n context response\n context log\n context db\n context token = new Token(claims)\n sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n closeClientScope()\n log.err(\"${requestIdentity(request.id, token)} Queue preparation failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n context queue = sender\n trace(\"${requestIdentity(request.id, token)} Matched route ${route.path}; fresh=${fresh}\")\n return chain Promise/resolve(null)\n then(ignored)\n capture fresh\n capture restored\n capture input\n if fresh\n registration = Object/assign({}, input, {\n ip: request.remoteAddress\n userAgent: request.headers[\"user-agent\"]\n })\n return event(\"register\", registration)\n return validate(restored)\n then(validatedAt)\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.policy != \"anonymous\" and !token.hasPolicy(route.policy)\n if route.legacyAuth\n response.reject(401, \"Unauthorized\")\n if route.policy == \"login\" or !token.hasPolicy(\"login\")\n needLogin(route, 401, \"LoginRequired\")\n response.reject(403, \"Forbidden\")\n if route.reauthSeconds > 0\n authenticatedAt = token.get(\"authenticatedAt\")\n now = Date/now()\n if !Number/isSafeInteger(authenticatedAt) or authenticatedAt < 0 or authenticatedAt > now\n needLogin(route, 403, \"ReauthenticationRequired\")\n if now - authenticatedAt >= route.reauthSeconds * 1000\n needLogin(route, 403, \"ReauthenticationRequired\")\n expected = request.headers[\"x-lango-expected-user\"]\n if expected != null and expected != to_json(token.get(\"userId\"))\n response.reject(409, \"IdentityChanged\")\n if route.kind == \"longpoll\"\n return null\n trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != 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 crypto\n capture task\n capture claims\n encoded = null\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = signResponse(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 trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\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 encoded = signResponse(updated)\n result = response.result(body)\n result.headers[\"x-lango-token\"] = encoded\n if result.status < 400 and authenticationChanged(claims, updated)\n result.headers[\"x-lango-auth-change\"] = \"v1:${crypto/randomUUID()}\"\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\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 log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n finally\n closeClientScope()\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 request\n context token\n identity = \"[${request.id}]\"\n if token != null\n identity = requestIdentity(request.id, token)\n trace(\"${identity} Running event ${name}\")\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 handler\n capture input\n return handler(input)\n finally\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate(force = false)\n context token\n claims = token.snapshot()\n if !force and 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 return event(\"validate\", null)\n then(valid)\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 request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n sender = null\n try\n sender = queueSender()\n catch error\n closeScope(db, false)\n log.err(\"${requestIdentity(id, token)} Request event queue preparation failed: ${errorDetails(error)}\")\n return result\n context queue = sender\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n logIdentity: requestIdentity(id, token)\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n closeScope(db, true)\n return null\n catch(error)\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\n return null\n then(ignored)\n capture result\n return result\n finally\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\ncloseClientScope()\n context clientIdentity\n if clientIdentity != null\n clientIdentity.closed = true\n return null\n\nneedLogin(route, status, reason)\n context request\n context token\n throw new HttpFailure(status, reason, {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n \"x-lango-need-login\": \"1\"\n }, {\n reason: reason\n path: request.path\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n userId: token.get(\"userId\")\n })\n\nauthenticationChanged(previous, current)\n context clientIdentity\n if clientIdentity != null and clientIdentity.rotate\n return true\n for [\"auth\", \"userId\", \"grantId\", \"authenticatedAt\"] as name\n if to_json(previous[name]) != to_json(current[name])\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAueA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;"}
package/dist/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { resolvePolicies } from "./policy.mjs";
1
2
  import { trace, responseLog } from "./trace.mjs";
2
3
  import { LongpollBroker } from "./longpoll_broker.mjs";
3
4
  import { LongpollSession } from "./longpoll_session.mjs";
@@ -18,6 +19,7 @@ import {
18
19
  contextGet as __contextGet,
19
20
  contextSet as __contextSet,
20
21
  contextRestore as __contextRestore,
22
+ bindContexts as __bindContexts,
21
23
  fromJson as __fromJson,
22
24
  toJson as __toJson,
23
25
  isNumber as __isNumber,
@@ -66,12 +68,17 @@ export class Server {
66
68
  let directory = path;
67
69
  let routes = new Routes(directory);
68
70
  __normalize(routes.xml(pathJoin(directory, "routes.xml")));
69
- definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), events: __normalize(routes.events()), middlewares: __normalize(routes.middlewares()) };
71
+ definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), jobs: __normalize(routes.jobs()), events: __normalize(routes.events()), middlewares: __normalize(routes.middlewares()) };
70
72
  }
71
73
  if (__requireBoolean(definition === null)) {
72
74
  throw "Use Server(directory) or Builder.build()";
73
75
  }
74
76
  this.#definition = __fromJson(__toJson(definition));
77
+ let settings = __normalize(this.#definition.settings);
78
+ resolvePolicies(__normalize(this.#definition.routes), __normalize(settings.policies));
79
+ if (__requireBoolean(__normalize(this.#definition.jobs) !== null)) {
80
+ resolvePolicies(__normalize(this.#definition.jobs), __normalize(settings.policies));
81
+ }
75
82
  this.#broker = new LongpollBroker(__normalize(this.#definition.settings), __normalize(this.#definition.routes));
76
83
  this.#polls = __normalize(__hostGlobal(["Object"]).create(null));
77
84
  this.#state = "new";
@@ -129,22 +136,22 @@ export class Server {
129
136
  return __normalize(__hostGlobal(["Promise"]).reject(error));
130
137
  }
131
138
  }
132
- return __normalize(this.#broker.open()).then(__withArity((ignored) => {
139
+ return __normalize(this.#broker.open()).then(__withArity(__bindContexts((ignored) => {
133
140
  ignored = __boundary(ignored);
134
- return prepareDatabase(__normalize(settings.database));
141
+ return prepareDatabase(__normalize(settings.database), __normalize(settings.root), __normalize(settings.client));
135
142
  return null;
136
- }, [0], "closure")).then(__withArity((ignored) => {
143
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
137
144
  ignored = __boundary(ignored);
138
145
  let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(settings.root), "package.json"))));
139
146
  let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
140
147
  this.#pool = new piscina.Piscina({ filename: __normalize(path.join(__normalize(path.dirname(entry)), "worker.mjs")), name: "execute", minThreads: __normalize(settings.workers), maxThreads: __normalize(settings.workers), maxQueue: __normalize(settings.maxQueue), concurrentTasksPerWorker: 1, closeTimeout: __normalize(settings.shutdownTimeoutMs), workerData: __normalize(this.#definition) });
141
148
  let pool = __normalize(this.#pool);
142
- __normalize(pool.on("message", __withArity((message) => {
149
+ __normalize(pool.on("message", __withArity(__bindContexts((message) => {
143
150
  message = __boundary(message);
144
151
  this.#messageReceived(message);
145
152
  return null;
146
- }, [0], "closure")));
147
- __normalize(pool.on("error", __withArity((error) => {
153
+ }), [0], "closure")));
154
+ __normalize(pool.on("error", __withArity(__bindContexts((error) => {
148
155
  const __contextScope = [];
149
156
  try {
150
157
  error = __boundary(error);
@@ -154,33 +161,33 @@ export class Server {
154
161
  } finally {
155
162
  __contextRestore(__contextScope);
156
163
  }
157
- }, [0], "closure")));
164
+ }), [0], "closure")));
158
165
  return startupDeadline(__normalize(this.#ready.promise), __normalize(settings.startupTimeoutMs));
159
166
  return null;
160
- }, [0], "closure")).then(__withArity((ignored) => {
167
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
161
168
  ignored = __boundary(ignored);
162
169
  if (__requireBoolean(__normalize(this.#state) !== "starting")) {
163
170
  throw "Server closed during startup";
164
171
  }
165
- let server = new http.Server(__withArity((req, res) => {
172
+ let server = new http.Server(__withArity(__bindContexts((req, res) => {
166
173
  req = __boundary(req);
167
174
  res = __boundary(res);
168
175
  this.#receive(req, res);
169
176
  return null;
170
- }, [0, 1], "closure"));
177
+ }), [0, 1], "closure"));
171
178
  this.#server = server;
172
- __normalize(server.on("connection", __withArity((socket) => {
179
+ __normalize(server.on("connection", __withArity(__bindContexts((socket) => {
173
180
  socket = __boundary(socket);
174
181
  this.#connected(socket);
175
182
  return null;
176
- }, [0], "closure")));
183
+ }), [0], "closure")));
177
184
  server.headersTimeout = __normalize(settings.bodyTimeoutMs);
178
185
  server.requestTimeout = __normalize(settings.bodyTimeoutMs);
179
- let listening = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
186
+ let listening = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve, reject) => {
180
187
  resolve = __boundary(resolve);
181
188
  reject = __boundary(reject);
182
189
  __normalize(server.once("error", reject));
183
- __normalize(server.listen(__normalize(settings.port), __normalize(settings.host), () => {
190
+ __normalize(server.listen(__normalize(settings.port), __normalize(settings.host), __bindContexts(() => {
184
191
  __normalize(server.removeListener("error", reject));
185
192
  if (__requireBoolean(__normalize(this.#state) !== "starting")) {
186
193
  __call(reject, "Server closed during startup");
@@ -190,22 +197,22 @@ export class Server {
190
197
  let address = __normalize(server.address());
191
198
  __call(resolve, { host: __normalize(address.address), port: __normalize(address.port) });
192
199
  return null;
193
- }));
200
+ })));
194
201
  return null;
195
- }, [0, 1], "closure"));
202
+ }), [0, 1], "closure"));
196
203
  return listening;
197
204
  return null;
198
- }, [0], "closure")).catch(__withArity((error) => {
205
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
199
206
  error = __boundary(error);
200
207
  __normalize(this.#broker.close());
201
208
  this.#state = "closed";
202
- return this.#destroyPool().then(__withArity((ignored) => {
209
+ return this.#destroyPool().then(__withArity(__bindContexts((ignored) => {
203
210
  ignored = __boundary(ignored);
204
211
  throw error;
205
212
  return null;
206
- }, [0], "closure"));
213
+ }), [0], "closure"));
207
214
  return null;
208
- }, [0], "closure"));
215
+ }), [0], "closure"));
209
216
  return null;
210
217
  }
211
218
  #messageReceived(message) {
@@ -250,10 +257,10 @@ export class Server {
250
257
  if (__requireBoolean(__normalize(record.result) === null)) {
251
258
  duration = __normalize(__hostGlobal(["Math"]).min(duration, __finite(__normalize(record.deadline) - __normalize(__hostGlobal(["Date"]).now()))));
252
259
  }
253
- let expired = () => {
260
+ let expired = __bindContexts(() => {
254
261
  this.#expire(record);
255
262
  return null;
256
- };
263
+ });
257
264
  record.timer = __hostGlobalCall(["setTimeout"], expired, __normalize(__hostGlobal(["Math"]).max(1, duration)));
258
265
  return null;
259
266
  return null;
@@ -263,13 +270,13 @@ export class Server {
263
270
  socket = __boundary(socket);
264
271
  let record = { socket: socket, active: 0 };
265
272
  __add(this.#connections, record);
266
- __normalize(socket.once("close", () => {
273
+ __normalize(socket.once("close", __bindContexts(() => {
267
274
  let index = __normalize(this.#connections.indexOf(record));
268
275
  if (__requireBoolean(index >= 0)) {
269
276
  __normalize(this.#connections.splice(index, 1));
270
277
  }
271
278
  return null;
272
- }));
279
+ })));
273
280
  return null;
274
281
  return null;
275
282
  }
@@ -282,7 +289,7 @@ export class Server {
282
289
  if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
283
290
  record.active = __numericAdd(__normalize(record.active), 1);
284
291
  let state = { done: false };
285
- let complete = () => {
292
+ let complete = __bindContexts(() => {
286
293
  if (__requireBoolean(__normalize(state.done))) {
287
294
  return null;
288
295
  }
@@ -298,7 +305,7 @@ export class Server {
298
305
  }
299
306
  return null;
300
307
  return null;
301
- };
308
+ });
302
309
  __normalize(res.once("finish", complete));
303
310
  __normalize(res.once("close", complete));
304
311
  return null;
@@ -312,22 +319,22 @@ export class Server {
312
319
  req = __boundary(req);
313
320
  res = __boundary(res);
314
321
  this.#trackResponse(req, res);
315
- __normalize(req.on("error", __withArity((error) => {
322
+ __normalize(req.on("error", __withArity(__bindContexts((error) => {
316
323
  error = __boundary(error);
317
324
  return null;
318
325
  return null;
319
- }, [0], "closure")));
326
+ }), [0], "closure")));
320
327
  if (__requireBoolean(__normalize(this.#state) !== "running")) {
321
328
  return rejectHttp(req, res, 503, "Unavailable");
322
329
  }
323
330
  trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
324
331
  if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
325
- let failed = __withArity((status, code) => {
332
+ let failed = __withArity(__bindContexts((status, code) => {
326
333
  status = __boundary(status);
327
334
  code = __boundary(code);
328
335
  this.#send(res, failure(status, code));
329
336
  return null;
330
- }, [0, 1], "closure");
337
+ }), [0, 1], "closure");
331
338
  return __normalize(this.#static.receive(req, res, failed));
332
339
  }
333
340
  if (__requireBoolean(__normalize(req.method) !== "POST")) {
@@ -354,17 +361,17 @@ export class Server {
354
361
  if (__requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue)))) {
355
362
  return rejectHttp(req, res, 503, "QueueFull");
356
363
  }
357
- let complete = __withArity((body) => {
364
+ let complete = __withArity(__bindContexts((body) => {
358
365
  body = __boundary(body);
359
366
  this.#submit(req, res, body);
360
367
  return null;
361
- }, [0], "closure");
362
- let failed = __withArity((status, code) => {
368
+ }), [0], "closure");
369
+ let failed = __withArity(__bindContexts((status, code) => {
363
370
  status = __boundary(status);
364
371
  code = __boundary(code);
365
372
  this.#send(res, failure(status, code));
366
373
  return null;
367
- }, [0, 1], "closure");
374
+ }), [0, 1], "closure");
368
375
  let reader = new BodyReader(req, res, settings, complete, failed);
369
376
  __normalize(reader.start());
370
377
  return null;
@@ -382,12 +389,12 @@ export class Server {
382
389
  } else {
383
390
  pending = this.#longpoll(req, res, body, route);
384
391
  }
385
- return pending.then(__withArity((result) => {
392
+ return pending.then(__withArity(__bindContexts((result) => {
386
393
  result = __boundary(result);
387
394
  this.#send(res, result);
388
395
  return null;
389
396
  return null;
390
- }, [0], "closure")).catch(__withArity((error) => {
397
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
391
398
  const __contextScope = [];
392
399
  try {
393
400
  error = __boundary(error);
@@ -398,7 +405,7 @@ export class Server {
398
405
  } finally {
399
406
  __contextRestore(__contextScope);
400
407
  }
401
- }, [0], "closure"));
408
+ }), [0], "closure"));
402
409
  return null;
403
410
  }
404
411
  #longpoll(req, res, body, route) {
@@ -410,25 +417,25 @@ export class Server {
410
417
  if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#polls))).length) >= __normalize(this.#definition.settings.redis.maxPendingPolls))) {
411
418
  return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "PollLimit")));
412
419
  }
413
- let authorize = __withArity((token, result) => {
420
+ let authorize = __withArity(__bindContexts((token, result) => {
414
421
  token = __boundary(token);
415
422
  result = __boundary(result);
416
423
  return this.#dispatch(req, res, body, true, token, result);
417
424
  return null;
418
- }, [0, 1], "closure");
425
+ }), [0, 1], "closure");
419
426
  let session = new LongpollSession(__normalize(this.#broker), route, authorize, body);
420
427
  let id = __normalize(crypto.randomUUID());
421
428
  this.#polls[id] = session;
422
- let disconnected = () => {
429
+ let disconnected = __bindContexts(() => {
423
430
  __normalize(session.cancel());
424
431
  return null;
425
- };
432
+ });
426
433
  __normalize(res.once("close", disconnected));
427
- return __normalize(session.run()).finally(() => {
434
+ return __normalize(session.run()).finally(__bindContexts(() => {
428
435
  __normalize(res.removeListener("close", disconnected));
429
436
  __normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#polls), id));
430
437
  return null;
431
- });
438
+ }));
432
439
  return null;
433
440
  }
434
441
  #brokerMessage(message) {
@@ -447,18 +454,18 @@ export class Server {
447
454
  } catch (error) {
448
455
  pending = __normalize(__hostGlobal(["Promise"]).reject(error));
449
456
  }
450
- return pending.then(__withArity((value) => {
457
+ return pending.then(__withArity(__bindContexts((value) => {
451
458
  value = __boundary(value);
452
459
  brokerReply(port, { ok: true, value: value });
453
460
  return null;
454
- }, [0], "closure")).catch(__withArity((error) => {
461
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
455
462
  error = __boundary(error);
456
463
  brokerReply(port, { ok: false });
457
464
  return null;
458
- }, [0], "closure")).finally(() => {
465
+ }), [0], "closure")).finally(__bindContexts(() => {
459
466
  __normalize(port.close());
460
467
  return null;
461
- });
468
+ }));
462
469
  return null;
463
470
  }
464
471
  #dispatch(req, res, body, authorize = false, token = null, pollResult = null) {
@@ -483,25 +490,25 @@ export class Server {
483
490
  this.#tasks[id] = record;
484
491
  this.#resetDeadline(record, __normalize(settings.requestTimeoutMs));
485
492
  __add(this.#waiting, record);
486
- let disconnected = () => {
493
+ let disconnected = __bindContexts(() => {
487
494
  if (__requireBoolean(!__requireBoolean(__normalize(res.writableEnded)))) {
488
495
  this.#cancel(record);
489
496
  }
490
497
  return null;
491
- };
498
+ });
492
499
  __normalize(res.once("close", disconnected));
493
500
  this.#pump();
494
- return record.completed.promise.catch(__withArity((error) => {
501
+ return record.completed.promise.catch(__withArity(__bindContexts((error) => {
495
502
  error = __boundary(error);
496
503
  if (__requireBoolean(__normalize(record.expired))) {
497
504
  return failure(504, "RequestTimeout");
498
505
  }
499
506
  return failure(500, "InternalServerError");
500
507
  return null;
501
- }, [0], "closure")).finally(() => {
508
+ }), [0], "closure")).finally(__bindContexts(() => {
502
509
  __normalize(res.removeListener("close", disconnected));
503
510
  return null;
504
- });
511
+ }));
505
512
  return null;
506
513
  }
507
514
  #expire(record) {
@@ -546,12 +553,12 @@ export class Server {
546
553
  __requireArity(arguments.length, [0, 1], "settle");
547
554
  record = __boundary(record);
548
555
  pending = __boundary(pending);
549
- return pending.then(__withArity((result) => {
556
+ return pending.then(__withArity(__bindContexts((result) => {
550
557
  result = __boundary(result);
551
558
  this.#finish(record, result, null);
552
559
  return null;
553
560
  return null;
554
- }, [0], "closure")).catch(__withArity((error) => {
561
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
555
562
  const __contextScope = [];
556
563
  try {
557
564
  error = __boundary(error);
@@ -564,11 +571,11 @@ export class Server {
564
571
  } finally {
565
572
  __contextRestore(__contextScope);
566
573
  }
567
- }, [0], "closure")).finally(() => {
574
+ }), [0], "closure")).finally(__bindContexts(() => {
568
575
  this.#active = __finite(__normalize(this.#active) - 1);
569
576
  this.#pump();
570
577
  return null;
571
- });
578
+ }));
572
579
  return null;
573
580
  }
574
581
  #finish(record, result, error) {
@@ -612,21 +619,21 @@ export class Server {
612
619
  for (const [id, session] of __entries(__normalize(this.#polls))) {
613
620
  __normalize(session.cancel());
614
621
  }
615
- let drained = new (__hostGlobal(["Promise"]))(__withArity((resolve) => {
622
+ let drained = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve) => {
616
623
  resolve = __boundary(resolve);
617
624
  let server = __normalize(this.#server);
618
625
  if (__requireBoolean(__requireBoolean(server === null) || __requireBoolean(!__requireBoolean(__normalize(server.listening))))) {
619
626
  __call(resolve, null);
620
627
  } else {
621
- server.close(() => {
628
+ server.close(__bindContexts(() => {
622
629
  __call(resolve, null);
623
630
  return null;
624
- });
631
+ }));
625
632
  }
626
633
  return null;
627
- }, [0], "closure"));
634
+ }), [0], "closure"));
628
635
  let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
629
- let force = () => {
636
+ let force = __bindContexts(() => {
630
637
  this.#destroying = true;
631
638
  for (const record of __normalize(this.#waiting)) {
632
639
  this.#finish(record, null, "Server closed");
@@ -637,17 +644,17 @@ export class Server {
637
644
  }
638
645
  __normalize(expired.reject("Server shutdown timed out"));
639
646
  return null;
640
- };
647
+ });
641
648
  let timer = __hostGlobalCall(["setTimeout"], force, __normalize(this.#definition.settings.shutdownTimeoutMs));
642
- return __normalize(__hostGlobal(["Promise"]).race([drained, __normalize(expired.promise)])).finally(() => {
649
+ return __normalize(__hostGlobal(["Promise"]).race([drained, __normalize(expired.promise)])).finally(__bindContexts(() => {
643
650
  __hostGlobalCall(["clearTimeout"], timer);
644
651
  return this.#destroyPool();
645
652
  return null;
646
- }).finally(() => {
653
+ })).finally(__bindContexts(() => {
647
654
  __normalize(this.#broker.close());
648
655
  this.#state = "closed";
649
656
  return null;
650
- });
657
+ }));
651
658
  return null;
652
659
  }
653
660
  #destroyPool() {
@@ -667,10 +674,10 @@ export class Server {
667
674
  pending = startupDeadline(__normalize(__hostGlobal(["Promise"]).all(tasks)), remaining);
668
675
  }
669
676
  }
670
- return pending.finally(() => {
677
+ return pending.finally(__bindContexts(() => {
671
678
  return __normalize(pool.destroy());
672
679
  return null;
673
- });
680
+ }));
674
681
  return null;
675
682
  }
676
683
  #send(res, result) {
@@ -698,15 +705,15 @@ function startupDeadline(pending, timeout) {
698
705
  pending = __boundary(pending);
699
706
  timeout = __boundary(timeout);
700
707
  let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
701
- let expire = () => {
708
+ let expire = __bindContexts(() => {
702
709
  __normalize(expired.reject("Worker startup timed out"));
703
710
  return null;
704
- };
711
+ });
705
712
  let timer = __hostGlobalCall(["setTimeout"], expire, timeout);
706
- return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
713
+ return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(__bindContexts(() => {
707
714
  __hostGlobalCall(["clearTimeout"], timer);
708
715
  return null;
709
- });
716
+ }));
710
717
  return null;
711
718
  }
712
719
 
@@ -748,10 +755,10 @@ function rejectHttp(req, res, status, code) {
748
755
  status = __boundary(status);
749
756
  code = __boundary(code);
750
757
  __normalize(res.setHeader("Connection", "close"));
751
- __normalize(res.once("finish", () => {
758
+ __normalize(res.once("finish", __bindContexts(() => {
752
759
  __normalize(req.destroy());
753
760
  return null;
754
- }));
761
+ })));
755
762
  __normalize(req.resume());
756
763
  return write(res, failure(status, code));
757
764
  return null;
@@ -780,8 +787,8 @@ export function main(args) {
780
787
  }
781
788
  trace(`Loading server configuration: ${directory}`);
782
789
  let server = new Server(directory);
783
- let stop = () => {
784
- return __normalize(server.close()).catch(__withArity((error) => {
790
+ let stop = __bindContexts(() => {
791
+ return __normalize(server.close()).catch(__withArity(__bindContexts((error) => {
785
792
  const __contextScope = [];
786
793
  try {
787
794
  error = __boundary(error);
@@ -791,12 +798,12 @@ export function main(args) {
791
798
  } finally {
792
799
  __contextRestore(__contextScope);
793
800
  }
794
- }, [0], "closure"));
801
+ }), [0], "closure"));
795
802
  return null;
796
- };
803
+ });
797
804
  __normalize(__hostGlobal(["process"]).once("SIGTERM", stop));
798
805
  __normalize(__hostGlobal(["process"]).once("SIGINT", stop));
799
- return __normalize(server.start()).then(__withArity((address) => {
806
+ return __normalize(server.start()).then(__withArity(__bindContexts((address) => {
800
807
  const __contextScope = [];
801
808
  try {
802
809
  address = __boundary(address);
@@ -806,13 +813,13 @@ export function main(args) {
806
813
  } finally {
807
814
  __contextRestore(__contextScope);
808
815
  }
809
- }, [0], "closure")).catch(__withArity((error) => {
816
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
810
817
  error = __boundary(error);
811
818
  __normalize(__hostGlobal(["process"]).removeListener("SIGTERM", stop));
812
819
  __normalize(__hostGlobal(["process"]).removeListener("SIGINT", stop));
813
820
  throw error;
814
821
  return null;
815
- }, [0], "closure"));
822
+ }), [0], "closure"));
816
823
  return null;
817
824
  }
818
825