@lango-project/lango-server 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -634,6 +634,14 @@ runs without its normal freshness shortcut. Invalid/expired supplied JWTs still
634
634
  fail; Server never silently falls back to the cookie. Requests are not retried.
635
635
  There is no application identity-restoration event or cookie parser to implement.
636
636
 
637
+ Startup middleware may declare `bootstrap: true` (XML: `bootstrap="true"`).
638
+ It must serve exact anonymous endpoints. Updated Lango Client sends its cached
639
+ opaque token as a startup hint; managed deployments establish clean identity
640
+ from the live cookie and force Validate, while JWT-only deployments verify the
641
+ hint normally. Explicit Authorization headers remain strictly verified. See
642
+ [browser session startup and expiration](docs/browser-sessions.md) for the
643
+ protocol, application guard requirements and replica behavior.
644
+
637
645
  After login or password confirmation, the application requests credential renewal:
638
646
 
639
647
  ```lango
@@ -1088,8 +1096,9 @@ application handler. Browser modules subsequently POST / to bootstrap and POST
1088
1096
  /index (or the selected page path) to request the view. Verbose static logs show
1089
1097
  the serving directory and HTTP completion status. Invalid JWTs are rejected
1090
1098
  before handler invocation, with a verbose diagnostic identifying that stage.
1091
- A client with an expired/replaced stored token can therefore load HTML but fail
1092
- its bootstrap POST with 401 before any application log statement runs.
1099
+ A managed-client bootstrap uses the live cookie rather than an expired cached
1100
+ JWT. JWT-only deployments can still reject an expired startup hint before any
1101
+ application handler runs. The browser offers an explicit reload action.
1093
1102
 
1094
1103
 
1095
1104
  HTTP failures are visible without verbose mode: completed 4xx responses use
@@ -1097,9 +1106,10 @@ HTTP failures are visible without verbose mode: completed 4xx responses use
1097
1106
  path, status and dispatched request ID where available. Successful responses
1098
1107
  remain debug-only. JWT rejection reasons are warnings even before a handler is
1099
1108
  invoked; raw JWTs and unverified claims are not logged as client identity.
1100
- Expired or invalid tokens can occur during ordinary session lifetimes, but a
1101
- failed startup is still a logged rejection. Detailed internal failures retain
1102
- their existing exception and identity logs.
1109
+ Verified token expiration returns `SessionExpired` with `X-Lango-Session: expired`
1110
+ and produces one informational completion record. Other credential failures
1111
+ remain warnings; detailed internal failures retain their exception and identity
1112
+ logs. Raw credentials and unverified identity claims are never logged.
1103
1113
 
1104
1114
 
1105
1115
  ## Security policy example
@@ -1 +1 @@
1
- {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\n readDeployment(directory, credentials = true)\nimport \"./server\"\n class Server\nimport \"./queue_provider\"\n queueProvider(root, spec)\n\nexport class Builder(root = null)\n methods\n configure(settings)\n loadDeployment()\n addMiddleware(name, spec)\n provideQueue(spec)\n endpoint(spec)\n job(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @queueProvider = null\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:loadDeployment()\n return configure(readDeployment(@root))\n\nBuilder:addMiddleware(name, spec)\n @routes.addMiddleware(name, spec)\n return @this\n\nBuilder:provideQueue(spec)\n if @queueProvider != null\n throw \"Queue provider is already configured\"\n @queueProvider = queueProvider(@root, spec)\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:job(spec)\n @routes.job(spec)\n return @this\n\nBuilder:longpoll(spec)\n @routes.longpoll(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n jobs: @routes.jobs()\n events: @routes.events()\n middlewares: @routes.middlewares()\n queueProvider: @queueProvider\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"228de8f2f069cc49252f8ca279d104051e96432601da167e0674d9f1cbcc9cf5","outputHash":"46fbf6b4730b70906066d7820309044835c0375c3f8de08ece74ae029573f5c4","mapHash":"93ac2330c9050687cb7120c0bfc76ec154f4c91a6ad9d06bb95050b2a6ba692b"}}
1
+ {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\n readDeployment(directory, credentials = true)\nimport \"./server\"\n class Server\nimport \"./queue_provider\"\n queueProvider(root, spec)\n\nexport class Builder(root = null)\n methods\n configure(settings)\n loadDeployment()\n addMiddleware(name, spec)\n provideQueue(spec)\n endpoint(spec)\n job(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @queueProvider = null\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:loadDeployment()\n return configure(readDeployment(@root))\n\nBuilder:addMiddleware(name, spec)\n @routes.addMiddleware(name, spec)\n return @this\n\nBuilder:provideQueue(spec)\n if @queueProvider != null\n throw \"Queue provider is already configured\"\n @queueProvider = queueProvider(@root, spec)\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:job(spec)\n @routes.job(spec)\n return @this\n\nBuilder:longpoll(spec)\n @routes.longpoll(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n jobs: @routes.jobs()\n events: @routes.events()\n middlewares: @routes.middlewares()\n queueProvider: @queueProvider\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"58a6be5f8ba849d404492a3dbc1a4e61f2dc09c8876f2857241f309f751fbc7f","outputHash":"46fbf6b4730b70906066d7820309044835c0375c3f8de08ece74ae029573f5c4","mapHash":"93ac2330c9050687cb7120c0bfc76ec154f4c91a6ad9d06bb95050b2a6ba692b"}}
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./policy\"\n resolvePolicies(routes, registry)\nimport \"./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, root = null, client = null)\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 jobs: routes.jobs()\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 settings = @definition.settings\n resolvePolicies(@definition.routes, settings.policies)\n if @definition.jobs != null\n resolvePolicies(@definition.jobs, settings.policies)\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, settings.root, settings.client)\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":"","x_lango_build":{"fingerprint":"de62ec88f0ec0c1235f608ebf68a0e8fbac4703b820109cf2afb7e5a649217d1","outputHash":"6b6f36fe1077a8d61a692cb806bc036070d08a4f5cbfa63494d0ef1fa764b92c","mapHash":"b81357c91558d8cbb05368d0cf2fa638f64d45381b8f8ca53ef1dfce717c0ead"}}
1
+ {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./policy\"\n resolvePolicies(routes, registry)\nimport \"./trace\"\n trace(message)\n responseLog(id, method, path, status, session = null)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings, root = null, client = null)\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 jobs: routes.jobs()\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 settings = @definition.settings\n resolvePolicies(@definition.routes, settings.policies)\n if @definition.jobs != null\n resolvePolicies(@definition.jobs, settings.policies)\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, settings.root, settings.client)\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, res.langoSession)\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.langoSession = result.headers[\"x-lango-session\"]\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":"","x_lango_build":{"fingerprint":"1e18495f4e2c54c8082cc880a736d8e777d808acef2232c2af285f53580b656b","outputHash":"6b6f36fe1077a8d61a692cb806bc036070d08a4f5cbfa63494d0ef1fa764b92c","mapHash":"dc8db0e982258082e62faf7997fedd1663869fb2a4b3b9e55d6dbc2364e81b33"}}
@@ -1 +1 @@
1
- {"version":3,"file":"database_action.mjs","sources":["database_action.lango"],"sourcesContent":["import \"./database\"\n class Database\nimport \"./job_configuration\"\n readDatabaseConfiguration(directory)\nimport js \"node:path\" as path\nimport js global Promise\n\nexport withDatabase(directory, action)\n\nwithDatabase(directory, action)\n root = path/resolve(directory)\n database = new Database(readDatabaseConfiguration(root), root)\n return chain database.open()\n then(ignored)\n capture database\n context db = database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture action\n return action()\n then(result)\n if db != null and db.finish()\n throw \"UnclosedTransaction\"\n return result\n finally\n if db != null\n db.finish()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"3952d87106ed76c5b950ba919ac5e38585b59d863a548f094da985df289651cc","outputHash":"a2c872c070872ff53b384885090707be0fe6f526300130cfabcb3b4e6c7412e3","mapHash":"52031f084526db823d4fe34aa9b5c7a78566646b741693f53a5f1f5d03f9a63a"}}
1
+ {"version":3,"file":"database_action.mjs","sources":["database_action.lango"],"sourcesContent":["import \"./database\"\n class Database\nimport \"./job_configuration\"\n readDatabaseConfiguration(directory)\nimport js \"node:path\" as path\nimport js global Promise\n\nexport withDatabase(directory, action)\n\nwithDatabase(directory, action)\n root = path/resolve(directory)\n database = new Database(readDatabaseConfiguration(root), root)\n return chain database.open()\n then(ignored)\n capture database\n context db = database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture action\n return action()\n then(result)\n if db != null and db.finish()\n throw \"UnclosedTransaction\"\n return result\n finally\n if db != null\n db.finish()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"fa1056ec5d6208d4350f0f39e42e7801fb02157a911a4f00e33a488c9b02bc2a","outputHash":"a2c872c070872ff53b384885090707be0fe6f526300130cfabcb3b4e6c7412e3","mapHash":"52031f084526db823d4fe34aa9b5c7a78566646b741693f53a5f1f5d03f9a63a"}}
@@ -1 +1 @@
1
- {"version":3,"file":"execution_identity.mjs","sources":["execution_identity.lango"],"sourcesContent":["import \"./execution_failure\"\n class ExecutionFailure\nimport \"./token\"\n class Token\nimport js global Object\nimport js global Date\nimport js global Number\n\nexport executionSource(source)\nexport executionToken(identity, source, route)\n\nexecutionSource(source)\n if source == null or !is_object(source) or is_array(source)\n throw \"Execution source must be a map\"\n allowed = [\"kind\", \"clientId\", \"userId\", \"grantId\", \"identity\"]\n for source as key: value\n if !allowed.includes(key)\n throw \"Unknown execution source field: ${key}\"\n if key != \"kind\" and (!is_string(value) or value.trim() == \"\")\n throw \"Execution source references must be nonempty strings\"\n switch source.kind\n case \"user\"\n if source.clientId == null or source.identity != null\n throw \"User execution source requires clientId and cannot select a system identity\"\n case \"system\"\n if source.identity == null or source.clientId != null or source.userId != null or source.grantId != null\n throw \"System execution source requires only a configured identity\"\n else\n throw \"Execution source kind must be user or system\"\n return from_json(to_json(source))\n\nexecutionToken(identity, source, route)\n if identity == null or identity == false\n throw new ExecutionFailure(\"IdentityRejected\")\n if !is_object(identity) or is_array(identity)\n throw \"Identity provider must return a map or null\"\n allowed = [\"clientId\", \"userId\", \"grantId\", \"identity\", \"policies\", \"authenticatedAt\"]\n for identity as key: value\n if !allowed.includes(key)\n throw \"Unknown execution identity field: ${key}\"\n if !is_array(identity.policies)\n throw \"Execution identity requires a policies array\"\n if source.kind == \"user\"\n for [\"clientId\", \"userId\", \"grantId\"] as key\n if identity[key] != source[key]\n throw new ExecutionFailure(\"IdentityChanged\")\n if identity.identity != null\n throw new ExecutionFailure(\"IdentityChanged\")\n else\n if identity.identity != source.identity or identity.clientId != null or identity.userId != null or identity.grantId != null\n throw new ExecutionFailure(\"IdentityChanged\")\n now = Date/now()\n stamp = identity.authenticatedAt\n if stamp != null and (!Number/isSafeInteger(stamp) or stamp < 0 or stamp > now)\n throw \"Execution identity authenticatedAt must be a real past timestamp\"\n claims = {\n clientId: identity.clientId\n userId: identity.userId\n grantId: identity.grantId\n identity: identity.identity\n auth: \"\"\n authenticatedAt: stamp\n }\n token = new Token(claims)\n for identity.policies as policy\n token.addPolicy(policy)\n if route.policy != \"anonymous\" and !token.hasPolicy(route.policy)\n throw new ExecutionFailure(\"Forbidden\")\n if route.reauthSeconds > 0 and (stamp == null or now - stamp >= route.reauthSeconds * 1000)\n throw new ExecutionFailure(\"ReauthenticationRequired\")\n return new Token(token.snapshot(), true)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"cf0795373ad6c34a72d271100dfaf590afca3ca806c80364a6585d42343208e2","outputHash":"a92291f310b0ce8a20887c1ed6b7540f0c500087cee7b20c965e266badbb3970","mapHash":"fd10c9ca0d5301225a58a49739b967cc9499137330ae49cfd598ddf1aad4865a"}}
1
+ {"version":3,"file":"execution_identity.mjs","sources":["execution_identity.lango"],"sourcesContent":["import \"./execution_failure\"\n class ExecutionFailure\nimport \"./token\"\n class Token\nimport js global Object\nimport js global Date\nimport js global Number\n\nexport executionSource(source)\nexport executionToken(identity, source, route)\n\nexecutionSource(source)\n if source == null or !is_object(source) or is_array(source)\n throw \"Execution source must be a map\"\n allowed = [\"kind\", \"clientId\", \"userId\", \"grantId\", \"identity\"]\n for source as key: value\n if !allowed.includes(key)\n throw \"Unknown execution source field: ${key}\"\n if key != \"kind\" and (!is_string(value) or value.trim() == \"\")\n throw \"Execution source references must be nonempty strings\"\n switch source.kind\n case \"user\"\n if source.clientId == null or source.identity != null\n throw \"User execution source requires clientId and cannot select a system identity\"\n case \"system\"\n if source.identity == null or source.clientId != null or source.userId != null or source.grantId != null\n throw \"System execution source requires only a configured identity\"\n else\n throw \"Execution source kind must be user or system\"\n return from_json(to_json(source))\n\nexecutionToken(identity, source, route)\n if identity == null or identity == false\n throw new ExecutionFailure(\"IdentityRejected\")\n if !is_object(identity) or is_array(identity)\n throw \"Identity provider must return a map or null\"\n allowed = [\"clientId\", \"userId\", \"grantId\", \"identity\", \"policies\", \"authenticatedAt\"]\n for identity as key: value\n if !allowed.includes(key)\n throw \"Unknown execution identity field: ${key}\"\n if !is_array(identity.policies)\n throw \"Execution identity requires a policies array\"\n if source.kind == \"user\"\n for [\"clientId\", \"userId\", \"grantId\"] as key\n if identity[key] != source[key]\n throw new ExecutionFailure(\"IdentityChanged\")\n if identity.identity != null\n throw new ExecutionFailure(\"IdentityChanged\")\n else\n if identity.identity != source.identity or identity.clientId != null or identity.userId != null or identity.grantId != null\n throw new ExecutionFailure(\"IdentityChanged\")\n now = Date/now()\n stamp = identity.authenticatedAt\n if stamp != null and (!Number/isSafeInteger(stamp) or stamp < 0 or stamp > now)\n throw \"Execution identity authenticatedAt must be a real past timestamp\"\n claims = {\n clientId: identity.clientId\n userId: identity.userId\n grantId: identity.grantId\n identity: identity.identity\n auth: \"\"\n authenticatedAt: stamp\n }\n token = new Token(claims)\n for identity.policies as policy\n token.addPolicy(policy)\n if route.policy != \"anonymous\" and !token.hasPolicy(route.policy)\n throw new ExecutionFailure(\"Forbidden\")\n if route.reauthSeconds > 0 and (stamp == null or now - stamp >= route.reauthSeconds * 1000)\n throw new ExecutionFailure(\"ReauthenticationRequired\")\n return new Token(token.snapshot(), true)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"ecf4be1326c403a65b872e47a597c154abd57876f5b3e3451673516c2f85bc9e","outputHash":"a92291f310b0ce8a20887c1ed6b7540f0c500087cee7b20c965e266badbb3970","mapHash":"fd10c9ca0d5301225a58a49739b967cc9499137330ae49cfd598ddf1aad4865a"}}
@@ -1 +1 @@
1
- {"version":3,"file":"execution_runtime.mjs","sources":["execution_runtime.lango"],"sourcesContent":["import \"./module_loader\"\n class ModuleLoader\nimport \"./database\"\n class Database\nimport \"./execution_identity\"\n executionSource(source)\n executionToken(identity, source, route)\nimport \"./execution_failure\"\n class ExecutionFailure\nimport \"./job_context\"\n class JobContext\nimport \"./execution_log\"\n class ExecutionLog\nimport \"./error_details\"\n errorDetails(error)\nimport js global Promise\nimport js global Object\n\nexport class ExecutionRuntime(definition)\n methods\n preload()\n execute(task)\n close()\n\nExecutionRuntime(definition)\n @definition = definition\n @loader = new ModuleLoader()\n @database = new Database(definition.database, definition.root)\n @handlers = Object/create(null)\n @identity = null\n @queueFactory = null\n\nExecutionRuntime:preload()\n pending = @database.open()\n for @definition.targets as route\n pending = prepare(pending, route)\n return chain pending\n then(ignored)\n return @loader.target(@definition.identity)\n then(handler)\n @identity = handler\n if @definition.queueProvider != null\n return @loader.target(@definition.queueProvider)\n return null\n then(factory)\n @queueFactory = factory\n return null\n catch(error)\n close()\n throw error\n\nExecutionRuntime:prepare(pending, route)\n return chain pending\n then(ignored)\n capture route\n return @loader.target(route)\n then(handler)\n capture route\n @handlers[route.path] = handler\n return null\n\nExecutionRuntime:execute(task)\n context db = @database.scope()\n context log\n route = null\n for @definition.targets as target\n if target.path == task.path\n route = target\n if route == null\n if db != null\n db.finish()\n throw \"Unregistered execution path\"\n context job = new JobContext(task, route)\n sink = log\n context log = new ExecutionLog(sink, job)\n return chain Promise/resolve(null)\n then(ignored)\n capture task\n capture route\n source = executionSource(task.source)\n Object/freeze(source)\n target = Object/freeze({\n path: route.path\n queue: route.queue\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n })\n handler = @identity\n return handler({\n source: source\n route: target\n })\n then(identity)\n capture task\n capture route\n context token = executionToken(identity, task.source, route)\n if task.authorize == true\n return null\n sender = null\n if @queueFactory != null\n factory = @queueFactory\n sender = factory(@definition.queueProvider.options)\n context queue = sender\n handler = @handlers[route.path]\n return handler(task.input)\n then(output)\n body = to_json(output)\n if !is_string(body)\n throw \"Execution output is not JSON serializable\"\n if db != null and db.finish()\n throw \"UnclosedTransaction\"\n return {\n ok: true\n output: from_json(body)\n }\n catch(error)\n capture ExecutionFailure\n permanent = is_kindof(error, ExecutionFailure)\n code = \"ExecutionFailed\"\n if permanent\n code = error.code?\n log.err(\"code=${code}: ${errorDetails(error)}\")\n return {\n ok: false\n code: code\n permanent: permanent\n message: errorDetails(error)\n }\n finally\n if db != null\n db.finish()\n\nExecutionRuntime:close()\n @database.close()\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"8206a4ec90bbf74a729aaa54bd55077b09ef6d6862dc6c74851c094461775428","outputHash":"bc9082abb7c7d2d5812a97a6ad8ccc9363c68901c5bfec5945f3c0ecde2cb347","mapHash":"d6aa9fb37e87200908873628ca752ea0d8287af787534ae7692eaa0af874cda0"}}
1
+ {"version":3,"file":"execution_runtime.mjs","sources":["execution_runtime.lango"],"sourcesContent":["import \"./module_loader\"\n class ModuleLoader\nimport \"./database\"\n class Database\nimport \"./execution_identity\"\n executionSource(source)\n executionToken(identity, source, route)\nimport \"./execution_failure\"\n class ExecutionFailure\nimport \"./job_context\"\n class JobContext\nimport \"./execution_log\"\n class ExecutionLog\nimport \"./error_details\"\n errorDetails(error)\nimport js global Promise\nimport js global Object\n\nexport class ExecutionRuntime(definition)\n methods\n preload()\n execute(task)\n close()\n\nExecutionRuntime(definition)\n @definition = definition\n @loader = new ModuleLoader()\n @database = new Database(definition.database, definition.root)\n @handlers = Object/create(null)\n @identity = null\n @queueFactory = null\n\nExecutionRuntime:preload()\n pending = @database.open()\n for @definition.targets as route\n pending = prepare(pending, route)\n return chain pending\n then(ignored)\n return @loader.target(@definition.identity)\n then(handler)\n @identity = handler\n if @definition.queueProvider != null\n return @loader.target(@definition.queueProvider)\n return null\n then(factory)\n @queueFactory = factory\n return null\n catch(error)\n close()\n throw error\n\nExecutionRuntime:prepare(pending, route)\n return chain pending\n then(ignored)\n capture route\n return @loader.target(route)\n then(handler)\n capture route\n @handlers[route.path] = handler\n return null\n\nExecutionRuntime:execute(task)\n context db = @database.scope()\n context log\n route = null\n for @definition.targets as target\n if target.path == task.path\n route = target\n if route == null\n if db != null\n db.finish()\n throw \"Unregistered execution path\"\n context job = new JobContext(task, route)\n sink = log\n context log = new ExecutionLog(sink, job)\n return chain Promise/resolve(null)\n then(ignored)\n capture task\n capture route\n source = executionSource(task.source)\n Object/freeze(source)\n target = Object/freeze({\n path: route.path\n queue: route.queue\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n })\n handler = @identity\n return handler({\n source: source\n route: target\n })\n then(identity)\n capture task\n capture route\n context token = executionToken(identity, task.source, route)\n if task.authorize == true\n return null\n sender = null\n if @queueFactory != null\n factory = @queueFactory\n sender = factory(@definition.queueProvider.options)\n context queue = sender\n handler = @handlers[route.path]\n return handler(task.input)\n then(output)\n body = to_json(output)\n if !is_string(body)\n throw \"Execution output is not JSON serializable\"\n if db != null and db.finish()\n throw \"UnclosedTransaction\"\n return {\n ok: true\n output: from_json(body)\n }\n catch(error)\n capture ExecutionFailure\n permanent = is_kindof(error, ExecutionFailure)\n code = \"ExecutionFailed\"\n if permanent\n code = error.code?\n log.err(\"code=${code}: ${errorDetails(error)}\")\n return {\n ok: false\n code: code\n permanent: permanent\n message: errorDetails(error)\n }\n finally\n if db != null\n db.finish()\n\nExecutionRuntime:close()\n @database.close()\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"a73feaab1bcf8e96a9a0e1c5dadcc97b5b20cb609e280e6ac6b9ae19f7ca6ca1","outputHash":"bc9082abb7c7d2d5812a97a6ad8ccc9363c68901c5bfec5945f3c0ecde2cb347","mapHash":"d6aa9fb37e87200908873628ca752ea0d8287af787534ae7692eaa0af874cda0"}}
@@ -1 +1 @@
1
- {"version":3,"file":"execution_worker.mjs","sources":["execution_worker.lango"],"sourcesContent":["import \"./execution_runtime\"\n class ExecutionRuntime\nimport js \"node:worker_threads\" as threads\nimport js global process\n\nexport global execute\n\nglobal runtime = new ExecutionRuntime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n return workerHandler()\n\nworkerHandler()\n return run\n\nrun(task)\n global runtime\n return runtime.execute(task)\n"],"names":[],"mappings":";;;;;;;;;;;AAOA;;AACA;AAEA;;;;;;;;;;;;;;;AAgBA;;;;;AAGA;;;;;;;","x_lango_build":{"fingerprint":"7dbc9e2444c7d6ef70e697efa133e7c26fcf208a674c53f4425401f494e478f7","outputHash":"cd86946a7992331bc108c786892523e4351d9f6c310d273b6267fdf02984f2f6","mapHash":"675fa2caa6ac99dd1f222270d5ca7fd7db8e0469c4b23a8b89c9379eb4790358"}}
1
+ {"version":3,"file":"execution_worker.mjs","sources":["execution_worker.lango"],"sourcesContent":["import \"./execution_runtime\"\n class ExecutionRuntime\nimport js \"node:worker_threads\" as threads\nimport js global process\n\nexport global execute\n\nglobal runtime = new ExecutionRuntime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n return workerHandler()\n\nworkerHandler()\n return run\n\nrun(task)\n global runtime\n return runtime.execute(task)\n"],"names":[],"mappings":";;;;;;;;;;;AAOA;;AACA;AAEA;;;;;;;;;;;;;;;AAgBA;;;;;AAGA;;;;;;;","x_lango_build":{"fingerprint":"283da670bed2766ff172c5f66bfdae9a433503ba7420ab8860cbd25bb9cdb9cc","outputHash":"cd86946a7992331bc108c786892523e4351d9f6c310d273b6267fdf02984f2f6","mapHash":"675fa2caa6ac99dd1f222270d5ca7fd7db8e0469c4b23a8b89c9379eb4790358"}}
@@ -1 +1 @@
1
- {"version":3,"file":"executor.mjs","sources":["executor.lango"],"sourcesContent":["import \"./job_configuration\"\n readDatabaseConfiguration(directory)\n readJobRoutes(directory)\nimport \"./execution_identity\"\n executionSource(source)\nimport \"./queue_provider\"\n queueProvider(root, spec)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"piscina\" as piscina\nimport js global Object\nimport js global Number\nimport js global Promise\nimport js global Error\nimport js global AbortController\nimport js global AbortSignal\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class Executor(directory, settings)\n methods\n start()\n execute(task, options = null)\n authorize(task, options = null)\n close()\n\nExecutor(directory, settings)\n if !is_string(directory) or directory == \"\"\n throw \"Executor requires an application directory\"\n if settings == null or !is_object(settings) or is_array(settings)\n throw \"Executor requires settings and an identity provider\"\n allowed = [\"identity\", \"workers\", \"maxQueue\", \"timeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"queueProvider\"]\n for settings as key: value\n if !allowed.includes(key)\n throw \"Unknown executor option: ${key}\"\n root = path/resolve(directory)\n @definition = {\n root: root\n database: readDatabaseConfiguration(root)\n targets: readJobRoutes(root)\n identity: provider(root, settings.identity)\n queueProvider: queueProvider(root, settings.queueProvider)\n }\n @workers = limit(settings.workers, 2, 1, 128, \"workers\")\n @maxQueue = limit(settings.maxQueue, 64, 0, 2147483647, \"maxQueue\")\n @timeout = limit(settings.timeoutMs, 900000, 1, 2147483647, \"timeoutMs\")\n @startupTimeout = limit(settings.startupTimeoutMs, 30000, 1, 2147483647, \"startupTimeoutMs\")\n @shutdownTimeout = limit(settings.shutdownTimeoutMs, 30000, 1, 2147483647, \"shutdownTimeoutMs\")\n @state = \"new\"\n @pool = null\n @closing = null\n @closeError = null\n @ready = Promise/withResolvers()\n @readyIds = []\n\nprovider(root, spec)\n if spec == null or !is_object(spec) or is_array(spec)\n throw \"Executor identity provider requires module and handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\"\n throw \"Unknown identity provider option: ${key}\"\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\"node:\") or !is_string(spec.handler) or spec.handler == \"\"\n throw \"Executor identity provider requires module and handler\"\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Identity provider must resolve to an application module\"\n return {\n module: file\n handler: spec.handler\n }\n\nlimit(value, fallback, minimum, maximum, name)\n if value == null\n return fallback\n if !Number/isSafeInteger(value) or value < minimum or value > maximum\n throw \"Invalid executor option: ${name}\"\n return value\n\nExecutor:start()\n if @state != \"new\"\n return Promise/reject(\"Executor can only be started once\")\n @state = \"starting\"\n try\n resolver = modules/createRequire(path/join(@definition.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"execution_worker.mjs\")\n name: \"execute\"\n minThreads: @workers\n maxThreads: @workers\n maxQueue: @maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: @shutdownTimeout\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n if message.kind == \"ready\" and !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length == @workers\n @ready.resolve(null)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n if @state == \"closing\"\n @closeError = error\n context log\n log.err(\"Execution worker error: ${errorDetails(error)}\")\n )\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n expire = ()\n @ready.reject(\"Executor startup timed out\")\n timer = setTimeout(expire, @startupTimeout)\n return chain @ready.promise\n then(ignored)\n if @state != \"starting\"\n throw \"Executor closed during startup\"\n @state = \"running\"\n return null\n catch(error)\n return chain destroy()\n then(ignored)\n capture error\n @state = \"closed\"\n throw error\n finally\n capture timer\n clearTimeout(timer)\n\nExecutor:execute(task, options = null)\n return run(task, options, false)\n\nExecutor:authorize(task, options = null)\n return run(task, options, true)\n\nExecutor:run(task, options, authorize)\n if @state != \"running\"\n return Promise/reject(\"Executor is not running\")\n try\n task = validateTask(task, @definition.targets)\n task.authorize = authorize\n options = executionOptions(options, @timeout)\n catch error\n return Promise/reject(error)\n controller = new AbortController()\n status = {\n expired: false\n }\n signal = options.signal\n abort = ()\n capture controller\n controller.abort()\n if signal != null\n signal.addEventListener(\"abort\", abort, {\n once: true\n })\n if signal.aborted\n controller.abort()\n expire = ()\n capture controller\n capture status\n if status.expired\n return null\n status.expired = true\n controller.abort()\n timer = setTimeout(expire, options.timeoutMs)\n return chain @pool.run(task, {\n signal: controller.signal\n })\n then(result)\n if !result.ok\n error = new Error(result.message)\n error.code = result.code\n error.permanent = result.permanent\n error.logged = true\n throw error\n return result.output\n catch(error)\n capture status\n capture task\n capture signal\n if status.expired\n error = new Error(\"Execution attempt timed out\")\n error.code = \"ExecutionTimeout\"\n error.permanent = false\n else\n if signal != null and signal.aborted\n error = new Error(\"Execution attempt was aborted\")\n error.code = \"ExecutionAborted\"\n error.permanent = false\n if !is_object(error)\n error = new Error(\"${error}\")\n if error.permanent != true\n error.permanent = false\n context log\n if error.logged != true\n source = task.source\n log.err(\"[jobId=${task.id}] path=${task.path} attempt=${task.attempt} clientId=${source.clientId} userId=${source.userId} identity=${source.identity}: ${errorDetails(error)}\")\n throw error\n finally\n capture timer\n capture signal\n capture abort\n clearTimeout(timer)\n if signal != null\n signal.removeEventListener(\"abort\", abort)\n\nexecutionOptions(options, timeout)\n if options == null\n options = {}\n if !is_object(options) or is_array(options)\n throw \"Execution options must be a map\"\n for options as key: value\n if key != \"signal\" and key != \"timeoutMs\"\n throw \"Unknown execution option: ${key}\"\n if options.signal != null and !is_kindof(options.signal, AbortSignal)\n throw \"Execution signal must be an AbortSignal\"\n return {\n signal: options.signal\n timeoutMs: limit(options.timeoutMs, timeout, 1, 2147483647, \"timeoutMs\")\n }\n\nvalidateTask(task, targets)\n if task == null or !is_object(task) or is_array(task)\n throw \"Execution task must be a map\"\n allowed = [\"id\", \"path\", \"input\", \"source\", \"attempt\"]\n for task as key: value\n if !allowed.includes(key)\n throw \"Unknown execution task option: ${key}\"\n if !is_string(task.id) or task.id == \"\" or task.id.length > 200\n throw \"Execution task requires a job id\"\n found = false\n for targets as route\n if route.path == task.path\n found = true\n if !found\n throw \"Unregistered execution path\"\n if task.input == null or !is_object(task.input) or is_array(task.input)\n throw \"Execution input must be a JSON map\"\n return {\n id: task.id\n path: task.path\n input: from_json(to_json(task.input))\n source: executionSource(task.source)\n attempt: limit(task.attempt, 1, 1, 2147483647, \"attempt\")\n }\n\nExecutor:close()\n if @closing != null\n return @closing\n if @state == \"closed\" or @state == \"new\"\n @state = \"closed\"\n return Promise/resolve(null)\n state = @state\n @state = \"closing\"\n if state == \"starting\"\n @ready.reject(\"Executor closed during startup\")\n @closing = destroy()\n else\n @closing = drain()\n return @closing\n\nExecutor:drain()\n return chain @pool.close()\n then(ignored)\n if @closeError != null\n throw @closeError\n return null\n finally\n return destroy()\n finally\n @state = \"closed\"\n\nExecutor:destroy()\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n @pool = null\n return pool.destroy()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;;;;;AA0IA;;;;;;;;;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"9b79b4002c95b68c8f567c3b9b13513a2f2dabef62561f5e39a7e1227a5b6619","outputHash":"9d3249297fbdba4c809ace5ca6bad54136934de93723358eccf8f69d9cd0af2c","mapHash":"59c6fd6c30de302e9420291c886df83643fb2ce5441a65e5e2491d9865e268b2"}}
1
+ {"version":3,"file":"executor.mjs","sources":["executor.lango"],"sourcesContent":["import \"./job_configuration\"\n readDatabaseConfiguration(directory)\n readJobRoutes(directory)\nimport \"./execution_identity\"\n executionSource(source)\nimport \"./queue_provider\"\n queueProvider(root, spec)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"piscina\" as piscina\nimport js global Object\nimport js global Number\nimport js global Promise\nimport js global Error\nimport js global AbortController\nimport js global AbortSignal\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class Executor(directory, settings)\n methods\n start()\n execute(task, options = null)\n authorize(task, options = null)\n close()\n\nExecutor(directory, settings)\n if !is_string(directory) or directory == \"\"\n throw \"Executor requires an application directory\"\n if settings == null or !is_object(settings) or is_array(settings)\n throw \"Executor requires settings and an identity provider\"\n allowed = [\"identity\", \"workers\", \"maxQueue\", \"timeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"queueProvider\"]\n for settings as key: value\n if !allowed.includes(key)\n throw \"Unknown executor option: ${key}\"\n root = path/resolve(directory)\n @definition = {\n root: root\n database: readDatabaseConfiguration(root)\n targets: readJobRoutes(root)\n identity: provider(root, settings.identity)\n queueProvider: queueProvider(root, settings.queueProvider)\n }\n @workers = limit(settings.workers, 2, 1, 128, \"workers\")\n @maxQueue = limit(settings.maxQueue, 64, 0, 2147483647, \"maxQueue\")\n @timeout = limit(settings.timeoutMs, 900000, 1, 2147483647, \"timeoutMs\")\n @startupTimeout = limit(settings.startupTimeoutMs, 30000, 1, 2147483647, \"startupTimeoutMs\")\n @shutdownTimeout = limit(settings.shutdownTimeoutMs, 30000, 1, 2147483647, \"shutdownTimeoutMs\")\n @state = \"new\"\n @pool = null\n @closing = null\n @closeError = null\n @ready = Promise/withResolvers()\n @readyIds = []\n\nprovider(root, spec)\n if spec == null or !is_object(spec) or is_array(spec)\n throw \"Executor identity provider requires module and handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\"\n throw \"Unknown identity provider option: ${key}\"\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\"node:\") or !is_string(spec.handler) or spec.handler == \"\"\n throw \"Executor identity provider requires module and handler\"\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n file = resolver.resolve(spec.module)\n if !path/isAbsolute(file)\n throw \"Identity provider must resolve to an application module\"\n return {\n module: file\n handler: spec.handler\n }\n\nlimit(value, fallback, minimum, maximum, name)\n if value == null\n return fallback\n if !Number/isSafeInteger(value) or value < minimum or value > maximum\n throw \"Invalid executor option: ${name}\"\n return value\n\nExecutor:start()\n if @state != \"new\"\n return Promise/reject(\"Executor can only be started once\")\n @state = \"starting\"\n try\n resolver = modules/createRequire(path/join(@definition.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"execution_worker.mjs\")\n name: \"execute\"\n minThreads: @workers\n maxThreads: @workers\n maxQueue: @maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: @shutdownTimeout\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n if message.kind == \"ready\" and !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length == @workers\n @ready.resolve(null)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n if @state == \"closing\"\n @closeError = error\n context log\n log.err(\"Execution worker error: ${errorDetails(error)}\")\n )\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n expire = ()\n @ready.reject(\"Executor startup timed out\")\n timer = setTimeout(expire, @startupTimeout)\n return chain @ready.promise\n then(ignored)\n if @state != \"starting\"\n throw \"Executor closed during startup\"\n @state = \"running\"\n return null\n catch(error)\n return chain destroy()\n then(ignored)\n capture error\n @state = \"closed\"\n throw error\n finally\n capture timer\n clearTimeout(timer)\n\nExecutor:execute(task, options = null)\n return run(task, options, false)\n\nExecutor:authorize(task, options = null)\n return run(task, options, true)\n\nExecutor:run(task, options, authorize)\n if @state != \"running\"\n return Promise/reject(\"Executor is not running\")\n try\n task = validateTask(task, @definition.targets)\n task.authorize = authorize\n options = executionOptions(options, @timeout)\n catch error\n return Promise/reject(error)\n controller = new AbortController()\n status = {\n expired: false\n }\n signal = options.signal\n abort = ()\n capture controller\n controller.abort()\n if signal != null\n signal.addEventListener(\"abort\", abort, {\n once: true\n })\n if signal.aborted\n controller.abort()\n expire = ()\n capture controller\n capture status\n if status.expired\n return null\n status.expired = true\n controller.abort()\n timer = setTimeout(expire, options.timeoutMs)\n return chain @pool.run(task, {\n signal: controller.signal\n })\n then(result)\n if !result.ok\n error = new Error(result.message)\n error.code = result.code\n error.permanent = result.permanent\n error.logged = true\n throw error\n return result.output\n catch(error)\n capture status\n capture task\n capture signal\n if status.expired\n error = new Error(\"Execution attempt timed out\")\n error.code = \"ExecutionTimeout\"\n error.permanent = false\n else\n if signal != null and signal.aborted\n error = new Error(\"Execution attempt was aborted\")\n error.code = \"ExecutionAborted\"\n error.permanent = false\n if !is_object(error)\n error = new Error(\"${error}\")\n if error.permanent != true\n error.permanent = false\n context log\n if error.logged != true\n source = task.source\n log.err(\"[jobId=${task.id}] path=${task.path} attempt=${task.attempt} clientId=${source.clientId} userId=${source.userId} identity=${source.identity}: ${errorDetails(error)}\")\n throw error\n finally\n capture timer\n capture signal\n capture abort\n clearTimeout(timer)\n if signal != null\n signal.removeEventListener(\"abort\", abort)\n\nexecutionOptions(options, timeout)\n if options == null\n options = {}\n if !is_object(options) or is_array(options)\n throw \"Execution options must be a map\"\n for options as key: value\n if key != \"signal\" and key != \"timeoutMs\"\n throw \"Unknown execution option: ${key}\"\n if options.signal != null and !is_kindof(options.signal, AbortSignal)\n throw \"Execution signal must be an AbortSignal\"\n return {\n signal: options.signal\n timeoutMs: limit(options.timeoutMs, timeout, 1, 2147483647, \"timeoutMs\")\n }\n\nvalidateTask(task, targets)\n if task == null or !is_object(task) or is_array(task)\n throw \"Execution task must be a map\"\n allowed = [\"id\", \"path\", \"input\", \"source\", \"attempt\"]\n for task as key: value\n if !allowed.includes(key)\n throw \"Unknown execution task option: ${key}\"\n if !is_string(task.id) or task.id == \"\" or task.id.length > 200\n throw \"Execution task requires a job id\"\n found = false\n for targets as route\n if route.path == task.path\n found = true\n if !found\n throw \"Unregistered execution path\"\n if task.input == null or !is_object(task.input) or is_array(task.input)\n throw \"Execution input must be a JSON map\"\n return {\n id: task.id\n path: task.path\n input: from_json(to_json(task.input))\n source: executionSource(task.source)\n attempt: limit(task.attempt, 1, 1, 2147483647, \"attempt\")\n }\n\nExecutor:close()\n if @closing != null\n return @closing\n if @state == \"closed\" or @state == \"new\"\n @state = \"closed\"\n return Promise/resolve(null)\n state = @state\n @state = \"closing\"\n if state == \"starting\"\n @ready.reject(\"Executor closed during startup\")\n @closing = destroy()\n else\n @closing = drain()\n return @closing\n\nExecutor:drain()\n return chain @pool.close()\n then(ignored)\n if @closeError != null\n throw @closeError\n return null\n finally\n return destroy()\n finally\n @state = \"closed\"\n\nExecutor:destroy()\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n @pool = null\n return pool.destroy()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;;;;;AA0IA;;;;;;;;;;;;;;;;;;;;;;AAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"b80f5bd486ec022b19ec8805472cf177a783de44a4d61b9411b1d9579cacfcdb","outputHash":"9d3249297fbdba4c809ace5ca6bad54136934de93723358eccf8f69d9cd0af2c","mapHash":"59c6fd6c30de302e9420291c886df83643fb2ce5441a65e5e2491d9865e268b2"}}
@@ -1 +1 @@
1
- {"version":3,"file":"job_configuration.mjs","sources":["job_configuration.lango"],"sourcesContent":["import \"./options\"\n readDeployment(directory, credentials = true)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./routes\"\n class Routes\nimport \"./policy\"\n policyRegistry(spec)\n resolvePolicies(routes, registry)\nimport js \"node:path\" as path\nimport js global Number\n\nexport readDatabaseConfiguration(directory)\nexport readJobRoutes(directory)\n\nreadDatabaseConfiguration(directory)\n root = path/resolve(directory)\n settings = readDeployment(root, false)\n workers = 2\n if settings.workers != null\n workers = Number(settings.workers)\n return databaseOptions(root, settings.database, workers)\n\nreadJobRoutes(directory)\n root = path/resolve(directory)\n settings = readDeployment(root, false)\n routes = new Routes(root)\n routes.xml(path/join(root, \"routes.xml\"))\n return resolvePolicies(routes.jobs(), policyRegistry(settings.policies))\n"],"names":[],"mappings":";;;;;;;;;;;;;AAeA;;;;;;;;;;;;;AAQA;;;;;;;;;;;","x_lango_build":{"fingerprint":"c1cd5d1e6ae0bbdd595b433c524059744c6683db3e9f615ffe0e77f6be699192","outputHash":"2dee9fb653491ea9fa095988ce01e36acab613710725b05d5a5b514deb4070c7","mapHash":"2a3d582a9d1c731374cbb495cb59b65a3a3c066465f1a446028b3b92b73991c2"}}
1
+ {"version":3,"file":"job_configuration.mjs","sources":["job_configuration.lango"],"sourcesContent":["import \"./options\"\n readDeployment(directory, credentials = true)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./routes\"\n class Routes\nimport \"./policy\"\n policyRegistry(spec)\n resolvePolicies(routes, registry)\nimport js \"node:path\" as path\nimport js global Number\n\nexport readDatabaseConfiguration(directory)\nexport readJobRoutes(directory)\n\nreadDatabaseConfiguration(directory)\n root = path/resolve(directory)\n settings = readDeployment(root, false)\n workers = 2\n if settings.workers != null\n workers = Number(settings.workers)\n return databaseOptions(root, settings.database, workers)\n\nreadJobRoutes(directory)\n root = path/resolve(directory)\n settings = readDeployment(root, false)\n routes = new Routes(root)\n routes.xml(path/join(root, \"routes.xml\"))\n return resolvePolicies(routes.jobs(), policyRegistry(settings.policies))\n"],"names":[],"mappings":";;;;;;;;;;;;;AAeA;;;;;;;;;;;;;AAQA;;;;;;;;;;;","x_lango_build":{"fingerprint":"bb89873533dff54820119a7727b7ea8d265b53e4e14b4929b399fb9ba1e25f90","outputHash":"2dee9fb653491ea9fa095988ce01e36acab613710725b05d5a5b514deb4070c7","mapHash":"2a3d582a9d1c731374cbb495cb59b65a3a3c066465f1a446028b3b92b73991c2"}}
@@ -1 +1 @@
1
- {"version":3,"file":"library.mjs","sources":["library.lango"],"sourcesContent":["import \"./server\"\n alias ServerClass = class Server\nimport \"./builder\"\n alias BuilderClass = class Builder\nimport \"./executor\"\n alias ExecutorClass = class Executor\nimport \"./database_action\"\n alias databaseAction = withDatabase(directory, action)\nimport \"./job_configuration\"\n alias databaseConfig = readDatabaseConfiguration(directory)\n alias jobRoutes = readJobRoutes(directory)\n\nexport global Server\nexport global Builder\nexport global Executor\nexport readDatabaseConfiguration(directory)\nexport readJobRoutes(directory)\nexport withDatabase(directory, action)\n\nglobal Server = ServerClass\nglobal Builder = BuilderClass\nglobal Executor = ExecutorClass\n\nreadDatabaseConfiguration(directory)\n return databaseConfig(directory)\n\nreadJobRoutes(directory)\n return jobRoutes(directory)\n\nwithDatabase(directory, action)\n return databaseAction(directory, action)\n"],"names":[],"mappings":";;;;;;;;;;AAmBA;;AACA;;AACA;AAEA;;;;;;;AAGA;;;;;;;AAGA;;;;;;;;","x_lango_build":{"fingerprint":"eac8c6b43092a37fe896941966402abedfef9275ba521f0ac5aeb34dc5134638","outputHash":"b6181148ec7d5e5879f8c0e7f0d37fb50b36d9a232f5a05d27a1972e7618cd44","mapHash":"fd2ce25041c5caefaf615924fcf0a370a2aaa195749ff1cda8f897097e7c93a2"}}
1
+ {"version":3,"file":"library.mjs","sources":["library.lango"],"sourcesContent":["import \"./server\"\n alias ServerClass = class Server\nimport \"./builder\"\n alias BuilderClass = class Builder\nimport \"./executor\"\n alias ExecutorClass = class Executor\nimport \"./database_action\"\n alias databaseAction = withDatabase(directory, action)\nimport \"./job_configuration\"\n alias databaseConfig = readDatabaseConfiguration(directory)\n alias jobRoutes = readJobRoutes(directory)\n\nexport global Server\nexport global Builder\nexport global Executor\nexport readDatabaseConfiguration(directory)\nexport readJobRoutes(directory)\nexport withDatabase(directory, action)\n\nglobal Server = ServerClass\nglobal Builder = BuilderClass\nglobal Executor = ExecutorClass\n\nreadDatabaseConfiguration(directory)\n return databaseConfig(directory)\n\nreadJobRoutes(directory)\n return jobRoutes(directory)\n\nwithDatabase(directory, action)\n return databaseAction(directory, action)\n"],"names":[],"mappings":";;;;;;;;;;AAmBA;;AACA;;AACA;AAEA;;;;;;;AAGA;;;;;;;AAGA;;;;;;;;","x_lango_build":{"fingerprint":"6496755494cbde80361dd53760c479b7c0544be3e30f2dfd716d10dc858bc990","outputHash":"b6181148ec7d5e5879f8c0e7f0d37fb50b36d9a232f5a05d27a1972e7618cd44","mapHash":"fd2ce25041c5caefaf615924fcf0a370a2aaa195749ff1cda8f897097e7c93a2"}}
@@ -1 +1 @@
1
- {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./policy\"\n policyRegistry(spec)\nimport \"./client_identity\"\n clientOptions(spec, database, origin)\nimport \"./origin\"\n originOptions(spec)\nimport \"./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)\nexport readDeployment(directory, credentials = true)\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 origin: null\n client: null\n policies: 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.policies = policyRegistry(result.policies)\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 result.origin = originOptions(result.origin)\n result.client = clientOptions(result.client, result.database, result.origin)\n return result\n\ndeployment(directory)\n return options(directory, readDeployment(directory))\n\nreadDeployment(directory, credentials = true)\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 (name != \"policies\" and 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 \"policies\"\n attributes(tag, [\"reauthSeconds\"])\n items = []\n for tag.children() as child\n if child.tag() != \"policy\" or child.children().length != 0 or child.innerText().trim() != \"\"\n throw \"Policies may contain only empty policy elements\"\n attributes(child, [\"name\", \"reauthSeconds\"])\n items.add(child.attributes())\n settings.policies = {\n reauthSeconds: tag.reauthSeconds\n items: items\n }\n continue\n case \"client\"\n attributes(tag, [\"maxAgeSeconds\"])\n settings.client = tag.attributes()\n continue\n case \"origin\"\n attributes(tag, [\"url\", \"urlEnv\", \"required\"])\n settings.origin = tag.attributes()\n continue\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 if !credentials\n continue\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 settings\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EA;;;;;;;;","x_lango_build":{"fingerprint":"6ef90d96e3672ee0281e3179b2670ad3c7ba482253b5d733bbaf70a847ae1e8a","outputHash":"8cc5a7c400ab56773c84475bb34591d1aa10a354b966debd4e07a13d6eb137fa","mapHash":"d91a7578eafb53cbc3c2e9ef45f9379655636ec5bba62b113bd86c67498e9592"}}
1
+ {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./policy\"\n policyRegistry(spec)\nimport \"./client_identity\"\n clientOptions(spec, database, origin)\nimport \"./origin\"\n originOptions(spec)\nimport \"./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)\nexport readDeployment(directory, credentials = true)\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 origin: null\n client: null\n policies: 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.policies = policyRegistry(result.policies)\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 result.origin = originOptions(result.origin)\n result.client = clientOptions(result.client, result.database, result.origin)\n return result\n\ndeployment(directory)\n return options(directory, readDeployment(directory))\n\nreadDeployment(directory, credentials = true)\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 (name != \"policies\" and 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 \"policies\"\n attributes(tag, [\"reauthSeconds\"])\n items = []\n for tag.children() as child\n if child.tag() != \"policy\" or child.children().length != 0 or child.innerText().trim() != \"\"\n throw \"Policies may contain only empty policy elements\"\n attributes(child, [\"name\", \"reauthSeconds\"])\n items.add(child.attributes())\n settings.policies = {\n reauthSeconds: tag.reauthSeconds\n items: items\n }\n continue\n case \"client\"\n attributes(tag, [\"maxAgeSeconds\"])\n settings.client = tag.attributes()\n continue\n case \"origin\"\n attributes(tag, [\"url\", \"urlEnv\", \"required\"])\n settings.origin = tag.attributes()\n continue\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 if !credentials\n continue\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 settings\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EA;;;;;;;;","x_lango_build":{"fingerprint":"c6f3e7382614b5f0deedac2b69df376944029c5e00f3ae803de00bcfcabaab46","outputHash":"8cc5a7c400ab56773c84475bb34591d1aa10a354b966debd4e07a13d6eb137fa","mapHash":"d91a7578eafb53cbc3c2e9ef45f9379655636ec5bba62b113bd86c67498e9592"}}
package/dist/response.mjs CHANGED
@@ -41,7 +41,7 @@ export class Response {
41
41
  throw "Header name and value must be strings";
42
42
  }
43
43
  name = __normalize(name.toLowerCase());
44
- if (__requireBoolean(contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name))) {
44
+ if (__requireBoolean(contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "x-lango-session", "content-length", "transfer-encoding", "connection", "content-type"], name))) {
45
45
  throw `Reserved response header: ${name}`;
46
46
  }
47
47
  if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(name.includes("\\r"))) || __requireBoolean(__normalize(name.includes("\n")))) || __requireBoolean(__normalize(value.includes("\\r")))) || __requireBoolean(__normalize(value.includes("\n"))))) {
@@ -1 +1 @@
1
- {"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nimport \"./http_failure\"\n class HttpFailure\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n reject(status, code)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-auth-change\", \"x-lango-need-login\", \"x-lango-token\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n\nResponse:reject(status, code)\n throw new HttpFailure(status, code, @headers)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"e0f08a0617bb7e4a14ddd7a82724f4a3d50ca4927eaf9b611bcf3abf8515259d","outputHash":"925375a1a0db2d99d816d7ef9e018e2ae1edf0783ab71de8b0af92d3cbeb4518","mapHash":"506e2c7050fbe6236d22b9e0cbf64e1aed113a7ff954104c224c64f5e05933fc"}}
1
+ {"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nimport \"./http_failure\"\n class HttpFailure\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n reject(status, code)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-auth-change\", \"x-lango-need-login\", \"x-lango-token\", \"x-lango-session\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n\nResponse:reject(status, code)\n throw new HttpFailure(status, code, @headers)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"1cc3420f05e291892d6d4df63acd13f025a33271534cf74f6a0e4e762fd579e9","outputHash":"3e25c50560446ee1efd48dceb212babbf812457232cb3c998b8912e75d91ffde","mapHash":"be06a96b4971a740c4f2bf0aec388b05b16b2673906cc7a7e3819608c4f5b409"}}
@@ -14,7 +14,11 @@ export function routeInfo(definitions) {
14
14
  if (__requireBoolean(kind === null)) {
15
15
  kind = "endpoint";
16
16
  }
17
- result.push({ path: __normalize(route.path), kind: kind, auth: __normalize(route.auth), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), middleware: __normalize(route.middleware) });
17
+ let info = { path: __normalize(route.path), kind: kind, auth: __normalize(route.auth), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), middleware: __normalize(route.middleware) };
18
+ if (__requireBoolean(__normalize(route.bootstrap) === true)) {
19
+ info.bootstrap = true;
20
+ }
21
+ result.push(info);
18
22
  }
19
23
  return result;
20
24
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"route_info.mjs","sources":["route_info.lango"],"sourcesContent":["export routeInfo(definitions)\n\nrouteInfo(definitions)\n result = []\n for definitions as route\n kind = route.kind\n if kind == null\n kind = \"endpoint\"\n result.add({\n path: route.path\n kind: kind\n auth: route.auth\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n middleware: route.middleware\n })\n return result\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"0cdab7de4d68736bedcc5c4c4a93f73bd5a436a7259a52b21eb017846896651f","outputHash":"c9a0a89a04b6619c0b764d2a19b93f7dd790a7d1a649a3f6cf597e4a8ce82d40","mapHash":"52b97867041a573580ac49e6e230d8cc683a7560ac5350653f45345f195d61ce"}}
1
+ {"version":3,"file":"route_info.mjs","sources":["route_info.lango"],"sourcesContent":["export routeInfo(definitions)\n\nrouteInfo(definitions)\n result = []\n for definitions as route\n kind = route.kind\n if kind == null\n kind = \"endpoint\"\n info = {\n path: route.path\n kind: kind\n auth: route.auth\n policy: route.policy\n reauthSeconds: route.reauthSeconds\n middleware: route.middleware\n }\n if route.bootstrap == true\n info.bootstrap = true\n result.add(info)\n return result\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"acab80471472ca17afa36f1f72d80013da4495bf4bf9aef41d2fe5ea6fe03a0d","outputHash":"83a4bccf04719bedbe9e9d0399c6f52a36c0f30d986ca62e3acc1119cb7827c8","mapHash":"830c3ea1a77b0f063f82c6fc526684fa164dbe9a3662b010f7d92a8a62f173f0"}}
package/dist/routes.mjs CHANGED
@@ -108,7 +108,7 @@ export class Routes {
108
108
  throw "Middleware requires a module and exported handler";
109
109
  }
110
110
  for (const [key, value] of __entries(spec)) {
111
- if (__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate"))) {
111
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate")) && __requireBoolean(key !== "bootstrap"))) {
112
112
  throw `Unknown middleware option: ${key}`;
113
113
  }
114
114
  }
@@ -118,7 +118,21 @@ export class Routes {
118
118
  if (__requireBoolean(__requireBoolean(__normalize(spec.validate) !== null) && __requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.validate)))) || __requireBoolean(__normalize(spec.validate) === "")))) {
119
119
  throw "Middleware validate must name an exported function";
120
120
  }
121
+ let bootstrap = __normalize(spec.bootstrap);
122
+ if (__requireBoolean(bootstrap === "true")) {
123
+ bootstrap = true;
124
+ }
125
+ if (__requireBoolean(bootstrap === "false")) {
126
+ bootstrap = false;
127
+ }
128
+ if (__requireBoolean(__requireBoolean(bootstrap !== null) && __requireBoolean(!__requireBoolean(__isBool(bootstrap))))) {
129
+ throw "Middleware bootstrap must be boolean";
130
+ }
121
131
  this.#middlewares[name] = { module: resolveModule(__normalize(spec.module), __normalize(this.#root)), handler: __normalize(spec.handler), validate: __normalize(spec.validate) };
132
+ if (__requireBoolean(bootstrap === true)) {
133
+ let middleware = __normalize(this.#middlewares[name]);
134
+ middleware.bootstrap = true;
135
+ }
122
136
  return this;
123
137
  return null;
124
138
  }
@@ -169,7 +183,16 @@ export class Routes {
169
183
  return null;
170
184
  }
171
185
  definitions() {
172
- return __fromJson(__toJson(__normalize(this.#items)));
186
+ let definitions = __fromJson(__toJson(__normalize(this.#items)));
187
+ for (const route of definitions) {
188
+ if (__requireBoolean(__requireBoolean(__normalize(route.middleware) !== null) && __requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#middlewares), __normalize(route.middleware)))))) {
189
+ let spec = __normalize(this.#middlewares[__normalize(route.middleware)]);
190
+ if (__requireBoolean(__normalize(spec.bootstrap) === true)) {
191
+ route.bootstrap = true;
192
+ }
193
+ }
194
+ }
195
+ return definitions;
173
196
  return null;
174
197
  }
175
198
  events() {
@@ -292,12 +315,12 @@ export class Routes {
292
315
  leaf(tag);
293
316
  this.#includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds);
294
317
  } else if (__normalize(tag.tag()) === "middleware") {
295
- attributes(tag, ["name", "module", "handler", "validate"]);
318
+ attributes(tag, ["name", "module", "handler", "validate", "bootstrap"]);
296
319
  leaf(tag);
297
320
  if (__requireBoolean(!__requireBoolean(allowEvents))) {
298
321
  throw "Middleware declarations are only allowed in the application's root routes.xml";
299
322
  }
300
- this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate) });
323
+ this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate), bootstrap: __normalize(spec.bootstrap) });
301
324
  } else if (__normalize(tag.tag()) === "event") {
302
325
  attributes(tag, ["name", "module", "handler"]);
303
326
  leaf(tag);
@@ -1 +1 @@
1
- {"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n job(spec)\n jobs()\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null, policy = null, reauthSeconds = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @jobs = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n policy: item.policy\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:job(spec)\n allowed = [\"path\", \"module\", \"handler\", \"queue\", \"policy\", \"auth\", \"reauthSeconds\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown job route option: ${key}\"\n item = new Endpoint(spec)\n if item.path.includes(\"*\") or item.path.includes(\"{\") or item.path.includes(\"}\")\n throw \"Job routes require an exact path\"\n if !is_string(spec.queue) or spec.queue.trim() != spec.queue or spec.queue == \"\"\n throw \"Job route requires a queue name\"\n for @jobs as other\n if other.path == item.path\n throw \"Duplicate job route: ${item.path}\"\n @jobs.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n queue: spec.queue\n policy: item.policy\n auth: item.auth\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n })\n return @this\n\nRoutes:jobs()\n return from_json(to_json(@jobs))\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null, policy = null, reauthSeconds = null)\n includeAt(spec, @root, \"\", [], auth, policy, reauthSeconds)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n return from_json(to_json(@items))\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents, inheritedPolicy = null, inheritedReauthSeconds = null)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n policy = spec.policy\n reauthSeconds = spec.reauthSeconds\n if mod == null\n mod = inheritedModule\n if auth == null and policy == null\n auth = inheritedAuth\n policy = inheritedPolicy\n if reauthSeconds == null\n reauthSeconds = inheritedReauthSeconds\n switch tag.tag()\n case \"job\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"queue\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n job({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n queue: spec.queue\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"policy\", \"reauthSeconds\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n spec.policy = policy\n spec.reauthSeconds = reauthSeconds\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\", \"policy\", \"reauthSeconds\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false, policy, reauthSeconds)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoIA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AAoIA;;;;;;;;;;","x_lango_build":{"fingerprint":"ebd91827536b531bc59778347087e4a23854cea16863740a9d40b80e8a34b1dc","outputHash":"c651315b01b7dcbcafa78ecacf7221a3dbe99ee942cf3935677497ef06c561a0","mapHash":"7445f646e4e9daa829b9e3ade7c89f0dfaaf5da5ffc1bdacc4d7912a4319db66"}}
1
+ {"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n job(spec)\n jobs()\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null, policy = null, reauthSeconds = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @jobs = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n policy: item.policy\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:job(spec)\n allowed = [\"path\", \"module\", \"handler\", \"queue\", \"policy\", \"auth\", \"reauthSeconds\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown job route option: ${key}\"\n item = new Endpoint(spec)\n if item.path.includes(\"*\") or item.path.includes(\"{\") or item.path.includes(\"}\")\n throw \"Job routes require an exact path\"\n if !is_string(spec.queue) or spec.queue.trim() != spec.queue or spec.queue == \"\"\n throw \"Job route requires a queue name\"\n for @jobs as other\n if other.path == item.path\n throw \"Duplicate job route: ${item.path}\"\n @jobs.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n queue: spec.queue\n policy: item.policy\n auth: item.auth\n reauthSeconds: item.reauthSeconds\n reauthExplicit: item.reauthExplicit\n legacyAuth: item.legacyAuth\n })\n return @this\n\nRoutes:jobs()\n return from_json(to_json(@jobs))\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\" and key != \"bootstrap\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n bootstrap = spec.bootstrap\n if bootstrap == \"true\"\n bootstrap = true\n if bootstrap == \"false\"\n bootstrap = false\n if bootstrap != null and !is_bool(bootstrap)\n throw \"Middleware bootstrap must be boolean\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n if bootstrap == true\n middleware = @middlewares[name]\n middleware.bootstrap = true\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null, policy = null, reauthSeconds = null)\n includeAt(spec, @root, \"\", [], auth, policy, reauthSeconds)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n definitions = from_json(to_json(@items))\n for definitions as route\n if route.middleware != null and Object/hasOwn(@middlewares, route.middleware)\n spec = @middlewares[route.middleware]\n if spec.bootstrap == true\n route.bootstrap = true\n return definitions\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents, inheritedPolicy, inheritedReauthSeconds)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents, inheritedPolicy = null, inheritedReauthSeconds = null)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n policy = spec.policy\n reauthSeconds = spec.reauthSeconds\n if mod == null\n mod = inheritedModule\n if auth == null and policy == null\n auth = inheritedAuth\n policy = inheritedPolicy\n if reauthSeconds == null\n reauthSeconds = inheritedReauthSeconds\n switch tag.tag()\n case \"job\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"queue\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n job({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n queue: spec.queue\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"policy\", \"reauthSeconds\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n spec.policy = policy\n spec.reauthSeconds = reauthSeconds\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\", \"policy\", \"reauthSeconds\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false, policy, reauthSeconds)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\", \"bootstrap\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n bootstrap: spec.bootstrap\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\", \"policy\", \"reauthSeconds\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n policy: policy\n reauthSeconds: reauthSeconds\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoJA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AAqIA;;;;;;;;;;","x_lango_build":{"fingerprint":"1d613ef75a657663394f6ab0fd067983304089a4d797c8b9417d0a0ffee4dc77","outputHash":"fc94fee8e5fcee173be1983460f3e78a072204c860e29a0880b70d5b607be14b","mapHash":"eb129adabe08566fdbe32c54593e363ef211ecd635b49f4f44927e900e031bfc"}}