@lango-project/lango-server 0.2.4 → 0.2.5
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 +8 -0
- package/dist/body_reader.mjs.map +1 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/server.mjs +3 -838
- package/dist/cli/server.mjs.map +1 -1
- package/dist/client_identity.mjs.map +1 -1
- package/dist/database.mjs.map +1 -1
- package/dist/database_action.mjs.map +1 -1
- package/dist/database_options.mjs.map +1 -1
- package/dist/database_scope.mjs.map +1 -1
- package/dist/endpoint.mjs.map +1 -1
- package/dist/error_details.mjs.map +1 -1
- package/dist/execution_failure.mjs.map +1 -1
- package/dist/execution_identity.mjs.map +1 -1
- package/dist/execution_log.mjs.map +1 -1
- package/dist/execution_runtime.mjs.map +1 -1
- package/dist/execution_worker.mjs.map +1 -1
- package/dist/executor.mjs.map +1 -1
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs.map +1 -1
- package/dist/job_configuration.mjs.map +1 -1
- package/dist/job_context.mjs.map +1 -1
- package/dist/library.mjs.map +1 -1
- package/dist/longpoll_broker.mjs.map +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/longpoll_session.mjs.map +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/module_loader.mjs.map +1 -1
- package/dist/options.mjs.map +1 -1
- package/dist/origin.mjs.map +1 -1
- package/dist/policy.mjs.map +1 -1
- package/dist/postgres_adapter.mjs.map +1 -1
- package/dist/postgres_worker.mjs.map +1 -1
- package/dist/queue_provider.mjs.map +1 -1
- package/dist/request_identity.mjs.map +1 -1
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs.map +1 -1
- package/dist/route_pattern.mjs.map +1 -1
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs.map +1 -1
- package/dist/sqlite_adapter.mjs.map +1 -1
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs.map +1 -1
- package/dist/trace.mjs.map +1 -1
- package/dist/worker.mjs.map +1 -1
- package/examples/security/package.json +1 -1
- package/package.json +6 -4
- package/dist/cli/.lango/bignumber.mjs +0 -3119
- package/dist/cli/.lango/localization.mjs +0 -108
- package/dist/cli/.lango/runtime.mjs +0 -725
- package/dist/cli/.lango/vendor/i18next.LICENSE +0 -21
- package/dist/cli/.lango/vendor/i18next.mjs +0 -2434
- package/dist/cli/.lango/xmldom/conventions.js +0 -429
- package/dist/cli/.lango/xmldom/dom-parser.js +0 -591
- package/dist/cli/.lango/xmldom/dom.js +0 -3759
- package/dist/cli/.lango/xmldom/entities.js +0 -2171
- package/dist/cli/.lango/xmldom/errors.js +0 -205
- package/dist/cli/.lango/xmldom/grammar.js +0 -559
- package/dist/cli/.lango/xmldom/index.js +0 -41
- package/dist/cli/.lango/xmldom/package.json +0 -1
- package/dist/cli/.lango/xmldom/sax.js +0 -983
- package/dist/cli/.lango/xmldom.LICENSE.md +0 -8
- package/dist/cli/body_reader.mjs +0 -180
- package/dist/cli/body_reader.mjs.map +0 -1
- package/dist/cli/client_identity.mjs +0 -250
- package/dist/cli/client_identity.mjs.map +0 -1
- package/dist/cli/database.mjs +0 -116
- package/dist/cli/database.mjs.map +0 -1
- package/dist/cli/database_options.mjs +0 -83
- package/dist/cli/database_options.mjs.map +0 -1
- package/dist/cli/database_scope.mjs +0 -93
- package/dist/cli/database_scope.mjs.map +0 -1
- package/dist/cli/endpoint.mjs +0 -50
- package/dist/cli/endpoint.mjs.map +0 -1
- package/dist/cli/error_details.mjs +0 -45
- package/dist/cli/error_details.mjs.map +0 -1
- package/dist/cli/longpoll_broker.mjs +0 -215
- package/dist/cli/longpoll_broker.mjs.map +0 -1
- package/dist/cli/longpoll_options.mjs +0 -103
- package/dist/cli/longpoll_options.mjs.map +0 -1
- package/dist/cli/longpoll_session.mjs +0 -136
- package/dist/cli/longpoll_session.mjs.map +0 -1
- package/dist/cli/middleware.mjs +0 -25
- package/dist/cli/middleware.mjs.map +0 -1
- package/dist/cli/options.mjs +0 -214
- package/dist/cli/options.mjs.map +0 -1
- package/dist/cli/origin.mjs +0 -87
- package/dist/cli/origin.mjs.map +0 -1
- package/dist/cli/policy.mjs +0 -121
- package/dist/cli/policy.mjs.map +0 -1
- package/dist/cli/postgres_adapter.mjs +0 -178
- package/dist/cli/postgres_adapter.mjs.map +0 -1
- package/dist/cli/route_pattern.mjs +0 -129
- package/dist/cli/route_pattern.mjs.map +0 -1
- package/dist/cli/routes.mjs +0 -360
- package/dist/cli/routes.mjs.map +0 -1
- package/dist/cli/sqlite_adapter.mjs +0 -163
- package/dist/cli/sqlite_adapter.mjs.map +0 -1
- package/dist/cli/static_files.mjs +0 -224
- package/dist/cli/static_files.mjs.map +0 -1
- package/dist/cli/trace.mjs +0 -53
- package/dist/cli/trace.mjs.map +0 -1
package/dist/cli/server.mjs.map
CHANGED
|
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;"}
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"39e33b1699569551a2b65fa66cac03a1136cddcb710042ba600d85563151c227","outputHash":"6fa4c393c85359193e41814354b0497eb2e70330969e459682dffc9b3524c853","mapHash":"59af2402d3c4dc1288b158bc0eeca43a346e651b8d743e4f296b8a8b64b4bcba"}}
|
package/dist/database.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"d6d7f3491aa14ab670541d06dbbcf73f6c7a663600fe5b74f877eb283a6dbebd","outputHash":"ad3db2b9a18feb34fd580438120cab8a663f03da82ee871f4581de800a0cf3fd","mapHash":"cf9dbae30a6362ca76f7cb4bb230e0add08a76a9b71f8166da8c9dd79a6225b5"}}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database_options.mjs","sources":["database_options.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport databaseOptions(root, spec, workers)\n\ndatabaseOptions(root, spec, workers)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Database configuration must be a map\"\n allowed = []\n switch spec.type\n case \"sqlite\"\n allowed = [\"type\", \"file\", \"busyTimeoutMs\"]\n case \"postgresql\"\n allowed = [\"type\", \"connectionEnv\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"]\n else\n throw \"Database type must be sqlite or postgresql\"\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown database option: ${key}\"\n if spec.type == \"sqlite\"\n if !is_string(spec.file) or spec.file == \"\"\n throw \"SQLite database file is required\"\n file = spec.file\n if file == \":memory:\" and workers != 1\n throw \"An in-memory SQLite database requires exactly one worker\"\n if file != \":memory:\"\n file = path/resolve(root, file)\n return {\n type: \"sqlite\"\n file: file\n busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)\n }\n name = spec.connectionEnv\n if !is_string(name) or name == \"\" or !Object/hasOwn(process.env, name)\n throw \"PostgreSQL connectionEnv must name an existing environment variable\"\n connection = process.env[name]\n if !is_string(connection) or (!connection.startsWith(\"postgresql://\") and !connection.startsWith(\"postgres://\"))\n throw \"PostgreSQL connectionEnv must contain a PostgreSQL connection URL\"\n return {\n type: \"postgresql\"\n connection: connection\n queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)\n connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)\n }\n\npositive(value, fallback)\n if value == null\n return fallback\n if is_string(value)\n value = Number(value)\n if !Number/isSafeInteger(value) or value < 1 or value > 2147483647\n throw \"Database timeout must be a positive integer within the timer limit\"\n return value\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"database_options.mjs","sources":["database_options.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport databaseOptions(root, spec, workers)\n\ndatabaseOptions(root, spec, workers)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Database configuration must be a map\"\n allowed = []\n switch spec.type\n case \"sqlite\"\n allowed = [\"type\", \"file\", \"busyTimeoutMs\"]\n case \"postgresql\"\n allowed = [\"type\", \"connectionEnv\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"]\n else\n throw \"Database type must be sqlite or postgresql\"\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown database option: ${key}\"\n if spec.type == \"sqlite\"\n if !is_string(spec.file) or spec.file == \"\"\n throw \"SQLite database file is required\"\n file = spec.file\n if file == \":memory:\" and workers != 1\n throw \"An in-memory SQLite database requires exactly one worker\"\n if file != \":memory:\"\n file = path/resolve(root, file)\n return {\n type: \"sqlite\"\n file: file\n busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)\n }\n name = spec.connectionEnv\n if !is_string(name) or name == \"\" or !Object/hasOwn(process.env, name)\n throw \"PostgreSQL connectionEnv must name an existing environment variable\"\n connection = process.env[name]\n if !is_string(connection) or (!connection.startsWith(\"postgresql://\") and !connection.startsWith(\"postgres://\"))\n throw \"PostgreSQL connectionEnv must contain a PostgreSQL connection URL\"\n return {\n type: \"postgresql\"\n connection: connection\n queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)\n connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)\n }\n\npositive(value, fallback)\n if value == null\n return fallback\n if is_string(value)\n value = Number(value)\n if !Number/isSafeInteger(value) or value < 1 or value > 2147483647\n throw \"Database timeout must be a positive integer within the timer limit\"\n return value\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"3a6b3dfcf8ae5f0e5f4f767f22b625c8fc2c99bdebb08df4257971c365036db0","outputHash":"57558a28568c8d59d0e4d77d6254601e655cdfc2230f1ab01acfd3475ba698e9","mapHash":"c82d1dc145002785804fefefd9d8981beb984b8c33c7b71abc1e68a919605afe"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database_scope.mjs","sources":["database_scope.lango"],"sourcesContent":["import js global Error\nimport js global Object\nimport js global process\n\nexport class DatabaseScope(adapter)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n invoke(spec, input)\n begin()\n commit()\n rollback()\n transactionState()\n finish()\n\nDatabaseScope(adapter)\n @adapter = adapter\n @closed = false\n @parameterStyle = adapter.parameterStyle\n\nDatabaseScope:execute(sql, parameters)\n requireOpen()\n return @adapter.execute(sql, parameters)\n\nDatabaseScope:invoke(spec, input)\n requireOpen()\n if @parameterStyle != \"postgresql\"\n throw \"Database extensions require PostgreSQL\"\n return @adapter.invoke(spec, input)\n\nDatabaseScope:begin()\n requireOpen()\n return @adapter.begin()\n\nDatabaseScope:commit()\n requireOpen()\n return @adapter.commit()\n\nDatabaseScope:rollback()\n requireOpen()\n return @adapter.rollback()\n\nDatabaseScope:transactionState()\n requireOpen()\n return @adapter.transactionState()\n\nDatabaseScope:requireOpen()\n if @closed\n throw new Error(\"DatabaseScopeClosed\")\n return null\n\nDatabaseScope:finish()\n if @closed\n return false\n @closed = true\n dirty = false\n try\n loop while @adapter.transactionState() != null\n dirty = true\n @adapter.rollback()\n catch error\n context log\n log.err(\"Database cleanup failed; retiring worker\")\n process.exit(1)\n return dirty\n"],"names":[],"mappings":";;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"database_scope.mjs","sources":["database_scope.lango"],"sourcesContent":["import js global Error\nimport js global Object\nimport js global process\n\nexport class DatabaseScope(adapter)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n invoke(spec, input)\n begin()\n commit()\n rollback()\n transactionState()\n finish()\n\nDatabaseScope(adapter)\n @adapter = adapter\n @closed = false\n @parameterStyle = adapter.parameterStyle\n\nDatabaseScope:execute(sql, parameters)\n requireOpen()\n return @adapter.execute(sql, parameters)\n\nDatabaseScope:invoke(spec, input)\n requireOpen()\n if @parameterStyle != \"postgresql\"\n throw \"Database extensions require PostgreSQL\"\n return @adapter.invoke(spec, input)\n\nDatabaseScope:begin()\n requireOpen()\n return @adapter.begin()\n\nDatabaseScope:commit()\n requireOpen()\n return @adapter.commit()\n\nDatabaseScope:rollback()\n requireOpen()\n return @adapter.rollback()\n\nDatabaseScope:transactionState()\n requireOpen()\n return @adapter.transactionState()\n\nDatabaseScope:requireOpen()\n if @closed\n throw new Error(\"DatabaseScopeClosed\")\n return null\n\nDatabaseScope:finish()\n if @closed\n return false\n @closed = true\n dirty = false\n try\n loop while @adapter.transactionState() != null\n dirty = true\n @adapter.rollback()\n catch error\n context log\n log.err(\"Database cleanup failed; retiring worker\")\n process.exit(1)\n return dirty\n"],"names":[],"mappings":";;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"24678d1eedc77e4ba68a3cb7b492dc0b067121976eef53288ca90dede6c0d64d","outputHash":"f7f8c6ce5bfcac35c174d43f2ec8d4eff86de246c23a38080d405780a7dd4568","mapHash":"d377c4efb750308a3c550ebe61a53c57a420d77b9d5f8337e4f91d5bfbf6f213"}}
|
package/dist/endpoint.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"64c587ae02cd691106a0fb4709752665ea4aa1d3481903804b66c7ee27ef4c13","outputHash":"d6b25f561f031eb3fafa39ec0cc7836c2e15aeccb4a00433f6a64c96cea07f30","mapHash":"730ee2cb10af9bacd9ccd7ad49fbec0712b0a1bcfde307bcc98a09cd18cb7293"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"56260c44066373eae7cb4ea0d7f520d5bed136bc75dc7373c4b550034731a35b","outputHash":"88d565014463c929f62d84e67c35e583032b7ab2e8a633759ef9ede2180152a8","mapHash":"1f0d3f5239b5e47e933b07849c9a6bc636fd17ca6e440713c7e269e31271c1d1"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution_failure.mjs","sources":["execution_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class ExecutionFailure(code)\n properties\n code?\n\nExecutionFailure(code)\n pattern = new RegExp(\"^[A-Za-z][A-Za-z0-9_]{0,63}$\")\n if !is_string(code) or !pattern.test(code)\n throw \"Execution rejection requires an error code\"\n @code = code\n\nExecutionFailure:code?\n return @code\n"],"names":[],"mappings":";;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"execution_failure.mjs","sources":["execution_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class ExecutionFailure(code)\n properties\n code?\n\nExecutionFailure(code)\n pattern = new RegExp(\"^[A-Za-z][A-Za-z0-9_]{0,63}$\")\n if !is_string(code) or !pattern.test(code)\n throw \"Execution rejection requires an error code\"\n @code = code\n\nExecutionFailure:code?\n return @code\n"],"names":[],"mappings":";;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"687ab9370e500e1bc0630490c2fcac4dc34f78ddb861a5567c8c8562d3cfbcba","outputHash":"8e3b16aea405b4b3a7459f50aea1d5429b0e8dc402c8fa7cc9a0e38242e305bc","mapHash":"f842e3513be81b8eade958f7e7dc11ab91e2ffdade0b95b421ea014ef2c17441"}}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution_log.mjs","sources":["execution_log.lango"],"sourcesContent":["export class ExecutionLog(sink, job)\n properties\n verbose?\n methods\n debug(message)\n info(message)\n warn(message)\n err(message)\n\nExecutionLog(sink, job)\n @sink = sink\n source = job.source?\n @prefix = \"[jobId=${job.id?}] path=${job.path?} queue=${job.queue?} attempt=${job.attempt?} clientId=${source.clientId} userId=${source.userId} grantId=${source.grantId} identity=${source.identity}\"\n\nExecutionLog:verbose?\n return @sink.verbose?\n\nExecutionLog:debug(message)\n return @sink.debug(\"${@prefix} ${message}\")\n\nExecutionLog:info(message)\n return @sink.info(\"${@prefix} ${message}\")\n\nExecutionLog:warn(message)\n return @sink.warn(\"${@prefix} ${message}\")\n\nExecutionLog:err(message)\n return @sink.err(\"${@prefix} ${message}\")\n"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"execution_log.mjs","sources":["execution_log.lango"],"sourcesContent":["export class ExecutionLog(sink, job)\n properties\n verbose?\n methods\n debug(message)\n info(message)\n warn(message)\n err(message)\n\nExecutionLog(sink, job)\n @sink = sink\n source = job.source?\n @prefix = \"[jobId=${job.id?}] path=${job.path?} queue=${job.queue?} attempt=${job.attempt?} clientId=${source.clientId} userId=${source.userId} grantId=${source.grantId} identity=${source.identity}\"\n\nExecutionLog:verbose?\n return @sink.verbose?\n\nExecutionLog:debug(message)\n return @sink.debug(\"${@prefix} ${message}\")\n\nExecutionLog:info(message)\n return @sink.info(\"${@prefix} ${message}\")\n\nExecutionLog:warn(message)\n return @sink.warn(\"${@prefix} ${message}\")\n\nExecutionLog:err(message)\n return @sink.err(\"${@prefix} ${message}\")\n"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"49cdc4b54921b4fb073637bd35128178261c8bfadc2326ab3bfb188a78138694","outputHash":"8e0aee8ae0a2311c18e302e463856e0636d2b81adc4eb9c9173baa7776151fa8","mapHash":"7e959f03f4d42947c9cfd1a215828cca2e59b70920b2b40d3d057a552a9319db"}}
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
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 +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;;;;;;;"}
|
|
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"}}
|
package/dist/executor.mjs.map
CHANGED
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
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"}}
|
package/dist/group.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"group.mjs","sources":["group.lango"],"sourcesContent":["import js global Object\n\nexport class Group(routes, spec, prefix = \"\", inheritedModule = null, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n methods\n endpoint(spec)\n job(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n\nGroup(routes, spec, prefix = \"\", inheritedModule = null, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.path) or !spec.path.startsWith(\"/\") or spec.path.endsWith(\"/\") or spec.path.includes(\"*\")\n throw \"Group requires a path without a trailing slash or wildcard\"\n @routes = routes\n @prefix = \"${prefix}${spec.path}\"\n @module = spec.module\n @auth = spec.auth\n @policy = spec.policy\n @reauthSeconds = spec.reauthSeconds\n if @module == null\n @module = inheritedModule\n if @auth == null and @policy == null\n @auth = inheritedAuth\n @policy = inheritedPolicy\n if @reauthSeconds == null\n @reauthSeconds = inheritedReauthSeconds\n\nGroup:endpoint(spec)\n if !is_string(spec.path) or !spec.path.startsWith(\"/\")\n throw \"Endpoint path must begin with /\"\n item = merged(spec)\n item.path = \"${@prefix}${spec.path}\"\n if item.module == null\n item.module = @module\n @routes.endpoint(item)\n return @this\n\nGroup:longpoll(spec)\n item = merged(spec)\n item.path = \"${@prefix}${spec.path}\"\n if item.fallback != null\n item.fallback = \"${@prefix}${item.fallback}\"\n @routes.longpoll(item)\n return @this\n\nGroup:job(spec)\n item = merged(spec)\n if !is_string(item.path) or !item.path.startsWith(\"/\")\n throw \"Job path must begin with /\"\n item.path = \"${@prefix}${item.path}\"\n if item.module == null\n item.module = @module\n @routes.job(item)\n return @this\n\nGroup:group(spec)\n return new Group(@routes, spec, @prefix, @module, @auth, @policy, @reauthSeconds)\n\nGroup:include(spec)\n mount = spec.path\n if mount == null\n mount = \"/\"\n @routes.include({\n module: spec.module\n path: \"${@prefix}${mount}\"\n }, @auth, @policy, @reauthSeconds)\n return @this\n\nGroup:merged(spec)\n item = Object/assign({}, spec)\n if item.auth == null and item.policy == null\n item.auth = @auth\n item.policy = @policy\n if item.reauthSeconds == null\n item.reauthSeconds = @reauthSeconds\n return item\n"],"names":[],"mappings":";;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"group.mjs","sources":["group.lango"],"sourcesContent":["import js global Object\n\nexport class Group(routes, spec, prefix = \"\", inheritedModule = null, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n methods\n endpoint(spec)\n job(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n\nGroup(routes, spec, prefix = \"\", inheritedModule = null, inheritedAuth = null, inheritedPolicy = null, inheritedReauthSeconds = null)\n if !is_string(spec.path) or !spec.path.startsWith(\"/\") or spec.path.endsWith(\"/\") or spec.path.includes(\"*\")\n throw \"Group requires a path without a trailing slash or wildcard\"\n @routes = routes\n @prefix = \"${prefix}${spec.path}\"\n @module = spec.module\n @auth = spec.auth\n @policy = spec.policy\n @reauthSeconds = spec.reauthSeconds\n if @module == null\n @module = inheritedModule\n if @auth == null and @policy == null\n @auth = inheritedAuth\n @policy = inheritedPolicy\n if @reauthSeconds == null\n @reauthSeconds = inheritedReauthSeconds\n\nGroup:endpoint(spec)\n if !is_string(spec.path) or !spec.path.startsWith(\"/\")\n throw \"Endpoint path must begin with /\"\n item = merged(spec)\n item.path = \"${@prefix}${spec.path}\"\n if item.module == null\n item.module = @module\n @routes.endpoint(item)\n return @this\n\nGroup:longpoll(spec)\n item = merged(spec)\n item.path = \"${@prefix}${spec.path}\"\n if item.fallback != null\n item.fallback = \"${@prefix}${item.fallback}\"\n @routes.longpoll(item)\n return @this\n\nGroup:job(spec)\n item = merged(spec)\n if !is_string(item.path) or !item.path.startsWith(\"/\")\n throw \"Job path must begin with /\"\n item.path = \"${@prefix}${item.path}\"\n if item.module == null\n item.module = @module\n @routes.job(item)\n return @this\n\nGroup:group(spec)\n return new Group(@routes, spec, @prefix, @module, @auth, @policy, @reauthSeconds)\n\nGroup:include(spec)\n mount = spec.path\n if mount == null\n mount = \"/\"\n @routes.include({\n module: spec.module\n path: \"${@prefix}${mount}\"\n }, @auth, @policy, @reauthSeconds)\n return @this\n\nGroup:merged(spec)\n item = Object/assign({}, spec)\n if item.auth == null and item.policy == null\n item.auth = @auth\n item.policy = @policy\n if item.reauthSeconds == null\n item.reauthSeconds = @reauthSeconds\n return item\n"],"names":[],"mappings":";;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"1896e5f0aaba61aa3a5b25866e7d6a74a0375b243997b61d2e1f8979a843ee66","outputHash":"01e971cedc68329978f494d8969b68e080e81c3cd377208ab947f6ef3dff7ef8","mapHash":"f36ef1b37d33c5202fbe9d79c3b7aa8a4a6878fa26495b1d5622ee4b665e54b3"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_failure.mjs","sources":["http_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class HttpFailure(status, code, headers, details = null)\n methods\n result()\n\nHttpFailure(status, code, headers, details = null)\n if !is_number(status) or status % 1 != 0 or status < 400 or status > 599\n throw \"Rejected response requires an error status\"\n pattern = new RegExp(\"^[A-Za-z][A-Za-z0-9_]{0,63}$\")\n if !is_string(code) or !pattern.test(code)\n throw \"Rejected response requires an error code\"\n @details = details\n @status = status\n @code = code\n @headers = from_json(to_json(headers))\n if status == 401\n @headers[\"www-authenticate\"] = \"Bearer\"\n\nHttpFailure:result()\n body = {\n error: @code\n }\n if @details != null\n body.needLogin = @details\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: to_json(body)\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"http_failure.mjs","sources":["http_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class HttpFailure(status, code, headers, details = null)\n methods\n result()\n\nHttpFailure(status, code, headers, details = null)\n if !is_number(status) or status % 1 != 0 or status < 400 or status > 599\n throw \"Rejected response requires an error status\"\n pattern = new RegExp(\"^[A-Za-z][A-Za-z0-9_]{0,63}$\")\n if !is_string(code) or !pattern.test(code)\n throw \"Rejected response requires an error code\"\n @details = details\n @status = status\n @code = code\n @headers = from_json(to_json(headers))\n if status == 401\n @headers[\"www-authenticate\"] = \"Bearer\"\n\nHttpFailure:result()\n body = {\n error: @code\n }\n if @details != null\n body.needLogin = @details\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: to_json(body)\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"27bf4949d8254e0e3b9ad6f1b2dbec24cd53246ca82121b35bb97a527da3bea6","outputHash":"117f8ad9e45f7e19015c7b6d09c5ec74c0319f44013f2a3f69aefc23e5081a8c","mapHash":"bd5784a1a45f1f8e01469edc5bcee77afc9ffc63dd91bf5bd71fd02b94910117"}}
|
|
@@ -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;;;;;;;;;;;"}
|
|
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"}}
|
package/dist/job_context.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job_context.mjs","sources":["job_context.lango"],"sourcesContent":["import \"./execution_failure\"\n class ExecutionFailure\nimport js global Object\n\nexport class JobContext(task, route)\n properties\n id?\n path?\n queue?\n attempt?\n source?\n checking?\n methods\n reject(code)\n\nJobContext(task, route)\n @id = task.id\n @path = route.path\n @queue = route.queue\n @attempt = task.attempt\n @source = from_json(to_json(task.source))\n @checking = task.authorize == true\n Object/freeze(@this)\n\nJobContext:id?\n return @id\n\nJobContext:path?\n return @path\n\nJobContext:queue?\n return @queue\n\nJobContext:attempt?\n return @attempt\n\nJobContext:source?\n return from_json(to_json(@source))\n\nJobContext:checking?\n return @checking\n\nJobContext:reject(code)\n throw new ExecutionFailure(code)\n"],"names":[],"mappings":";;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"job_context.mjs","sources":["job_context.lango"],"sourcesContent":["import \"./execution_failure\"\n class ExecutionFailure\nimport js global Object\n\nexport class JobContext(task, route)\n properties\n id?\n path?\n queue?\n attempt?\n source?\n checking?\n methods\n reject(code)\n\nJobContext(task, route)\n @id = task.id\n @path = route.path\n @queue = route.queue\n @attempt = task.attempt\n @source = from_json(to_json(task.source))\n @checking = task.authorize == true\n Object/freeze(@this)\n\nJobContext:id?\n return @id\n\nJobContext:path?\n return @path\n\nJobContext:queue?\n return @queue\n\nJobContext:attempt?\n return @attempt\n\nJobContext:source?\n return from_json(to_json(@source))\n\nJobContext:checking?\n return @checking\n\nJobContext:reject(code)\n throw new ExecutionFailure(code)\n"],"names":[],"mappings":";;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"f1ff20c8ed9cd25f37b820c52c20d681401d748d64abcd105106dee3e671c653","outputHash":"4d4a079ab03f8781796aa5b233a6debe2d6b5ac76907364afb31affb9b3d2d32","mapHash":"59e986c40d0fd842903785e288cd23c23c13f49793a73e15e67a47806e123d5a"}}
|
package/dist/library.mjs.map
CHANGED
|
@@ -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;;;;;;;;"}
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"longpoll_broker.mjs","sources":["longpoll_broker.lango"],"sourcesContent":["import js \"redis\" as redis\nimport js \"node:crypto\" as crypto\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js global Buffer\nimport js global Promise\nimport js global process\nimport js global JSON\nimport js global RegExp\nimport js global Object\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollBroker(settings, routes)\n methods\n open()\n close()\n route(path)\n publish(path, key, data)\n cursor(path, key)\n read(path, key, cursor)\n\nLongpollBroker(settings, routes)\n @routes = Object/create(null)\n for routes as item\n if item.kind == \"longpoll\"\n @routes[item.path] = item\n @settings = settings.redis\n @client = null\n @script = null\n if Object/keys(@routes).length > 0 and @settings == null\n throw \"Longpoll routes require Redis configuration\"\n @root = settings.root\n\nLongpollBroker:route(path)\n if Object/hasOwn(@routes, path)\n return @routes[path]\n return null\n\nLongpollBroker:open()\n if Object/keys(@routes).length == 0\n return Promise/resolve(null)\n resolver = modules/createRequire(path/join(@root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @script = fs/readFileSync(path/join(path/dirname(entry), \"../src/longpoll.lua\"), \"utf8\")\n config = @settings\n name = config.connectionEnv\n @client = redis/createClient({\n url: process.env[name]\n disableOfflineQueue: true\n commandsQueueMaxLength: 2048\n socket: {\n connectTimeout: 2000\n reconnectStrategy: 500\n }\n })\n client = @client\n client.on(\"error\", (error)\n return null\n )\n return bounded(client.connect(), 3000)\n\nLongpollBroker:close()\n if @client != null and @client.isOpen\n @client.destroy()\n return null\n\nLongpollBroker:publish(path, key, data)\n body = JSON/stringify(data)\n if !is_string(body) or Buffer/byteLength(body) > 262144\n return Promise/reject(\"Longpoll message must be JSON within 262144 bytes\")\n return execute(\"publish\", path, key, null, body)\n\nLongpollBroker:cursor(path, key)\n return execute(\"cursor\", path, key, null, \"\")\n\nLongpollBroker:read(path, key, cursor)\n return execute(\"read\", path, key, cursor, \"\")\n\nLongpollBroker:execute(operation, path, key, cursor, body)\n item = route(path)\n if item == null\n return Promise/reject(\"Unknown longpoll path\")\n if !is_string(key) or key == \"\" or Buffer/byteLength(key) > 1024\n return Promise/reject(\"Longpoll key must contain 1 to 1024 bytes\")\n if @client == null or !@client.isReady\n return Promise/reject(\"RedisUnavailable\")\n hash = crypto/createHash(\"sha256\")\n hash.update(to_json([@settings.namespace, path, key]))\n channel = hash.digest(\"hex\")\n prefix = \"lango:longpoll:{${channel}}\"\n position = {\n generation: \"\"\n id: \"0-0\"\n }\n if cursor != null\n position = decode(cursor, channel)\n if position == null\n return Promise/resolve({\n resyncRequired: true\n })\n pending = @client.eval(@script, {\n keys: [\"${prefix}:stream\", \"${prefix}:meta\"]\n arguments: [operation, crypto/randomUUID(), \"${item.retentionMs}\", \"${item.maxMessages}\", position.generation, position.id, body]\n })\n return chain bounded(pending, 3000)\n then(raw)\n capture channel\n capture operation\n result = JSON/parse(raw)\n if result.resyncRequired == true\n return result\n result.cursor = encode(channel, result.generation, result.id)\n if operation != \"read\"\n return result.cursor\n messages = []\n if is_array(result.messages)\n for result.messages as message\n messages.add({\n id: encode(channel, result.generation, message.id)\n data: JSON/parse(message.data)\n })\n return {\n messages: messages\n cursor: result.cursor\n resyncRequired: false\n }\n\nencode(channel, generation, id)\n buffer = Buffer/from(to_json([channel, generation, id]))\n return buffer.toString(\"base64url\")\n\ndecode(cursor, channel)\n if !is_string(cursor) or cursor.length > 512\n return null\n try\n buffer = Buffer/from(cursor, \"base64url\")\n parts = from_json(buffer.toString(\"utf8\"))\n if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])\n return null\n pattern = new RegExp(\"^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$\")\n if !pattern.test(parts[2]) or parts[2].length > 40\n return null\n return {\n generation: parts[1]\n id: parts[2]\n }\n catch error\n return null\n\nbounded(pending, ms)\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"RedisUnavailable\")\n timer = setTimeout(fail, ms)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"longpoll_broker.mjs","sources":["longpoll_broker.lango"],"sourcesContent":["import js \"redis\" as redis\nimport js \"node:crypto\" as crypto\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js global Buffer\nimport js global Promise\nimport js global process\nimport js global JSON\nimport js global RegExp\nimport js global Object\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollBroker(settings, routes)\n methods\n open()\n close()\n route(path)\n publish(path, key, data)\n cursor(path, key)\n read(path, key, cursor)\n\nLongpollBroker(settings, routes)\n @routes = Object/create(null)\n for routes as item\n if item.kind == \"longpoll\"\n @routes[item.path] = item\n @settings = settings.redis\n @client = null\n @script = null\n if Object/keys(@routes).length > 0 and @settings == null\n throw \"Longpoll routes require Redis configuration\"\n @root = settings.root\n\nLongpollBroker:route(path)\n if Object/hasOwn(@routes, path)\n return @routes[path]\n return null\n\nLongpollBroker:open()\n if Object/keys(@routes).length == 0\n return Promise/resolve(null)\n resolver = modules/createRequire(path/join(@root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @script = fs/readFileSync(path/join(path/dirname(entry), \"../src/longpoll.lua\"), \"utf8\")\n config = @settings\n name = config.connectionEnv\n @client = redis/createClient({\n url: process.env[name]\n disableOfflineQueue: true\n commandsQueueMaxLength: 2048\n socket: {\n connectTimeout: 2000\n reconnectStrategy: 500\n }\n })\n client = @client\n client.on(\"error\", (error)\n return null\n )\n return bounded(client.connect(), 3000)\n\nLongpollBroker:close()\n if @client != null and @client.isOpen\n @client.destroy()\n return null\n\nLongpollBroker:publish(path, key, data)\n body = JSON/stringify(data)\n if !is_string(body) or Buffer/byteLength(body) > 262144\n return Promise/reject(\"Longpoll message must be JSON within 262144 bytes\")\n return execute(\"publish\", path, key, null, body)\n\nLongpollBroker:cursor(path, key)\n return execute(\"cursor\", path, key, null, \"\")\n\nLongpollBroker:read(path, key, cursor)\n return execute(\"read\", path, key, cursor, \"\")\n\nLongpollBroker:execute(operation, path, key, cursor, body)\n item = route(path)\n if item == null\n return Promise/reject(\"Unknown longpoll path\")\n if !is_string(key) or key == \"\" or Buffer/byteLength(key) > 1024\n return Promise/reject(\"Longpoll key must contain 1 to 1024 bytes\")\n if @client == null or !@client.isReady\n return Promise/reject(\"RedisUnavailable\")\n hash = crypto/createHash(\"sha256\")\n hash.update(to_json([@settings.namespace, path, key]))\n channel = hash.digest(\"hex\")\n prefix = \"lango:longpoll:{${channel}}\"\n position = {\n generation: \"\"\n id: \"0-0\"\n }\n if cursor != null\n position = decode(cursor, channel)\n if position == null\n return Promise/resolve({\n resyncRequired: true\n })\n pending = @client.eval(@script, {\n keys: [\"${prefix}:stream\", \"${prefix}:meta\"]\n arguments: [operation, crypto/randomUUID(), \"${item.retentionMs}\", \"${item.maxMessages}\", position.generation, position.id, body]\n })\n return chain bounded(pending, 3000)\n then(raw)\n capture channel\n capture operation\n result = JSON/parse(raw)\n if result.resyncRequired == true\n return result\n result.cursor = encode(channel, result.generation, result.id)\n if operation != \"read\"\n return result.cursor\n messages = []\n if is_array(result.messages)\n for result.messages as message\n messages.add({\n id: encode(channel, result.generation, message.id)\n data: JSON/parse(message.data)\n })\n return {\n messages: messages\n cursor: result.cursor\n resyncRequired: false\n }\n\nencode(channel, generation, id)\n buffer = Buffer/from(to_json([channel, generation, id]))\n return buffer.toString(\"base64url\")\n\ndecode(cursor, channel)\n if !is_string(cursor) or cursor.length > 512\n return null\n try\n buffer = Buffer/from(cursor, \"base64url\")\n parts = from_json(buffer.toString(\"utf8\"))\n if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])\n return null\n pattern = new RegExp(\"^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$\")\n if !pattern.test(parts[2]) or parts[2].length > 40\n return null\n return {\n generation: parts[1]\n id: parts[2]\n }\n catch error\n return null\n\nbounded(pending, ms)\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"RedisUnavailable\")\n timer = setTimeout(fail, ms)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"5ebf17dce85e355d34708776bf0765790de340a6386f9fe5a8482ac76f51cd90","outputHash":"30e19fe75f51fb8ac48fecc7e6dec5bfbd36c1333eedc7acf15d88624cd08b19","mapHash":"af20743f7c15bf4472f4c08d33aee5ea6895a4303a5de814d09e9c0ab9156979"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport js global Number\nimport js global Object\nimport js global process\nimport js global URL\n\nexport longpollOptions(spec)\nexport redisOptions(spec)\n\nlongpollOptions(spec)\n result = {\n kind: \"longpoll\"\n path: spec.path\n auth: null\n policy: null\n reauthSeconds: 0\n waitTimeoutMs: 20000\n retentionMs: 300000\n maxMessages: 1000\n fallback: null\n }\n for spec as key: value\n if !Object/hasOwn(result, key) or key == \"kind\"\n throw \"Unknown longpoll option: ${key}\"\n result[key] = value\n selected = policyOptions(result)\n result.policy = selected.name\n result.auth = selected.name\n result.reauthSeconds = selected.reauthSeconds\n result.reauthExplicit = spec.reauthSeconds != null\n result.legacyAuth = selected.legacy\n validPath(result.path)\n if result.fallback != null\n validPath(result.fallback)\n limits = {\n waitTimeoutMs: 60000\n retentionMs: 86400000\n maxMessages: 10000\n }\n for limits as key: limit\n if !is_number(result[key]) and !is_string(result[key])\n throw \"Invalid longpoll option: ${key}\"\n value = Number(result[key])\n if !Number/isSafeInteger(value) or value < 1 or value > limit\n throw \"Invalid longpoll option: ${key}\"\n result[key] = value\n return result\n\nvalidPath(value)\n if !is_string(value) or !value.startsWith(\"/\") or value.includes(\"*\") or value.includes(\"{\") or value.includes(\"}\") or value.includes(\"?\") or value.includes(\"#\") or value.includes(\"\\\\\") or value.includes(\"//\")\n throw \"Longpoll requires an exact absolute URL path\"\n return null\n\nredisOptions(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Redis configuration must be a map\"\n allowed = [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown Redis option: ${key}\"\n if !is_string(spec.connectionEnv) or spec.connectionEnv == \"\" or !is_string(spec.namespace) or spec.namespace == \"\" or spec.namespace.length > 128\n throw \"Redis requires connectionEnv and namespace\"\n name = spec.connectionEnv\n value = process.env[name]\n if !is_string(value) or value == \"\"\n throw \"Redis connection environment variable is missing\"\n url = new URL(value)\n protocols = [\"redis:\", \"rediss:\"]\n if !protocols.includes(url.protocol)\n throw \"Redis requires a redis:// or rediss:// URL\"\n maximum = 1024\n if spec.maxPendingPolls != null\n if !is_number(spec.maxPendingPolls) and !is_string(spec.maxPendingPolls)\n throw \"Invalid Redis maxPendingPolls\"\n maximum = Number(spec.maxPendingPolls)\n if !Number/isSafeInteger(maximum) or maximum < 1 or maximum > 10000\n throw \"Invalid Redis maxPendingPolls\"\n return {\n connectionEnv: spec.connectionEnv\n namespace: spec.namespace\n maxPendingPolls: maximum\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport js global Number\nimport js global Object\nimport js global process\nimport js global URL\n\nexport longpollOptions(spec)\nexport redisOptions(spec)\n\nlongpollOptions(spec)\n result = {\n kind: \"longpoll\"\n path: spec.path\n auth: null\n policy: null\n reauthSeconds: 0\n waitTimeoutMs: 20000\n retentionMs: 300000\n maxMessages: 1000\n fallback: null\n }\n for spec as key: value\n if !Object/hasOwn(result, key) or key == \"kind\"\n throw \"Unknown longpoll option: ${key}\"\n result[key] = value\n selected = policyOptions(result)\n result.policy = selected.name\n result.auth = selected.name\n result.reauthSeconds = selected.reauthSeconds\n result.reauthExplicit = spec.reauthSeconds != null\n result.legacyAuth = selected.legacy\n validPath(result.path)\n if result.fallback != null\n validPath(result.fallback)\n limits = {\n waitTimeoutMs: 60000\n retentionMs: 86400000\n maxMessages: 10000\n }\n for limits as key: limit\n if !is_number(result[key]) and !is_string(result[key])\n throw \"Invalid longpoll option: ${key}\"\n value = Number(result[key])\n if !Number/isSafeInteger(value) or value < 1 or value > limit\n throw \"Invalid longpoll option: ${key}\"\n result[key] = value\n return result\n\nvalidPath(value)\n if !is_string(value) or !value.startsWith(\"/\") or value.includes(\"*\") or value.includes(\"{\") or value.includes(\"}\") or value.includes(\"?\") or value.includes(\"#\") or value.includes(\"\\\\\") or value.includes(\"//\")\n throw \"Longpoll requires an exact absolute URL path\"\n return null\n\nredisOptions(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Redis configuration must be a map\"\n allowed = [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown Redis option: ${key}\"\n if !is_string(spec.connectionEnv) or spec.connectionEnv == \"\" or !is_string(spec.namespace) or spec.namespace == \"\" or spec.namespace.length > 128\n throw \"Redis requires connectionEnv and namespace\"\n name = spec.connectionEnv\n value = process.env[name]\n if !is_string(value) or value == \"\"\n throw \"Redis connection environment variable is missing\"\n url = new URL(value)\n protocols = [\"redis:\", \"rediss:\"]\n if !protocols.includes(url.protocol)\n throw \"Redis requires a redis:// or rediss:// URL\"\n maximum = 1024\n if spec.maxPendingPolls != null\n if !is_number(spec.maxPendingPolls) and !is_string(spec.maxPendingPolls)\n throw \"Invalid Redis maxPendingPolls\"\n maximum = Number(spec.maxPendingPolls)\n if !Number/isSafeInteger(maximum) or maximum < 1 or maximum > 10000\n throw \"Invalid Redis maxPendingPolls\"\n return {\n connectionEnv: spec.connectionEnv\n namespace: spec.namespace\n maxPendingPolls: maximum\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"b848ea68a34ab1b604ac91b94fe591f18c805cf7996a8afe39e51cfaaad742ec","outputHash":"979695cdd0b98c95d81056cc1a4b310fa3f79ec8ee69e8c9ed419d3c67c98ee6","mapHash":"6d8aae83b12acab200293774c5cf82c2d33da2c856910f0cb947099b1be98c55"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"longpoll_session.mjs","sources":["longpoll_session.lango"],"sourcesContent":["import js global Promise\nimport js global Buffer\nimport js global Date\nimport js global Math\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollSession(broker, route, authorize, body)\n methods\n run()\n cancel()\n\nLongpollSession(broker, route, authorize, body)\n @broker = broker\n @route = route\n @authorize = authorize\n @body = body\n @cancelled = false\n @timer = null\n @sleep = null\n @token = null\n @deadline = 0\n @input = null\n @cursor = null\n\nLongpollSession:cancel()\n @cancelled = true\n clearTimeout(@timer)\n if @sleep != null\n @sleep.resolve(null)\n return null\n\nLongpollSession:run()\n try\n @input = from_json(@body)\n input = @input\n if !is_object(input) or is_array(input) or !is_string(input.key) or input.key == \"\" or Buffer/byteLength(input.key) > 1024\n return Promise/resolve(failure(400, \"InvalidLongpollInput\"))\n if input.cursor != null and (!is_string(input.cursor) or input.cursor.length > 512)\n return Promise/resolve(failure(400, \"InvalidLongpollInput\"))\n @cursor = input.cursor\n catch error\n return Promise/resolve(failure(400, \"InvalidJson\"))\n auth = @authorize\n return chain auth(null, null)\n then(result)\n if result.status != 200\n return result\n @token = result.authorization\n @deadline = Date/now() + @route.waitTimeoutMs\n return poll()\n catch(error)\n return failure(503, \"LongpollUnavailable\")\n finally\n cancel()\n\nLongpollSession:poll()\n if @cancelled\n return Promise/resolve(failure(503, \"Unavailable\"))\n return chain @broker.read(@route.path, @input.key, @cursor)\n then(batch)\n if @cancelled\n return failure(503, \"Unavailable\")\n if batch.resyncRequired or batch.messages.length > 0 or Date/now() >= @deadline\n if batch.resyncRequired\n batch.fallback = @route.fallback\n auth = @authorize\n return auth(@token, batch)\n @cursor = batch.cursor\n @sleep = Promise/withResolvers()\n sleep = @sleep\n wake = ()\n capture sleep\n sleep.resolve(null)\n @timer = setTimeout(wake, Math/min(250, Math/max(1, @deadline - Date/now())))\n return chain sleep.promise\n then(ignored)\n return poll()\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"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"longpoll_session.mjs","sources":["longpoll_session.lango"],"sourcesContent":["import js global Promise\nimport js global Buffer\nimport js global Date\nimport js global Math\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollSession(broker, route, authorize, body)\n methods\n run()\n cancel()\n\nLongpollSession(broker, route, authorize, body)\n @broker = broker\n @route = route\n @authorize = authorize\n @body = body\n @cancelled = false\n @timer = null\n @sleep = null\n @token = null\n @deadline = 0\n @input = null\n @cursor = null\n\nLongpollSession:cancel()\n @cancelled = true\n clearTimeout(@timer)\n if @sleep != null\n @sleep.resolve(null)\n return null\n\nLongpollSession:run()\n try\n @input = from_json(@body)\n input = @input\n if !is_object(input) or is_array(input) or !is_string(input.key) or input.key == \"\" or Buffer/byteLength(input.key) > 1024\n return Promise/resolve(failure(400, \"InvalidLongpollInput\"))\n if input.cursor != null and (!is_string(input.cursor) or input.cursor.length > 512)\n return Promise/resolve(failure(400, \"InvalidLongpollInput\"))\n @cursor = input.cursor\n catch error\n return Promise/resolve(failure(400, \"InvalidJson\"))\n auth = @authorize\n return chain auth(null, null)\n then(result)\n if result.status != 200\n return result\n @token = result.authorization\n @deadline = Date/now() + @route.waitTimeoutMs\n return poll()\n catch(error)\n return failure(503, \"LongpollUnavailable\")\n finally\n cancel()\n\nLongpollSession:poll()\n if @cancelled\n return Promise/resolve(failure(503, \"Unavailable\"))\n return chain @broker.read(@route.path, @input.key, @cursor)\n then(batch)\n if @cancelled\n return failure(503, \"Unavailable\")\n if batch.resyncRequired or batch.messages.length > 0 or Date/now() >= @deadline\n if batch.resyncRequired\n batch.fallback = @route.fallback\n auth = @authorize\n return auth(@token, batch)\n @cursor = batch.cursor\n @sleep = Promise/withResolvers()\n sleep = @sleep\n wake = ()\n capture sleep\n sleep.resolve(null)\n @timer = setTimeout(wake, Math/min(250, Math/max(1, @deadline - Date/now())))\n return chain sleep.promise\n then(ignored)\n return poll()\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"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA;;;;;;;;","x_lango_build":{"fingerprint":"0cf102527804f5168ee6fbc4fd1614bec4e248adc19e3e24fa91f71645b195d8","outputHash":"f9ab2246c452536f330b55c20ab2a9b2b79343dc051d2daa4292d176881e246a","mapHash":"0f02e054d45d5014df0572ce58e6e8a61d7d0dba11d84754d38df91f3cf1b584"}}
|
package/dist/middleware.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.mjs","sources":["middleware.lango"],"sourcesContent":["import js global RegExp\n\nexport middlewareName(name)\n\nmiddlewareName(name)\n reserved = [\"routes\", \"endpoint\", \"longpoll\", \"job\", \"group\", \"include\", \"event\", \"middleware\"]\n pattern = new RegExp(\"^[A-Za-z_][A-Za-z0-9_-]*$\")\n if !is_string(name) or !pattern.test(name) or reserved.includes(name)\n throw \"Invalid or reserved middleware name: ${name}\"\n return name\n"],"names":[],"mappings":";;;;;;;;;;;;;AAIA;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"middleware.mjs","sources":["middleware.lango"],"sourcesContent":["import js global RegExp\n\nexport middlewareName(name)\n\nmiddlewareName(name)\n reserved = [\"routes\", \"endpoint\", \"longpoll\", \"job\", \"group\", \"include\", \"event\", \"middleware\"]\n pattern = new RegExp(\"^[A-Za-z_][A-Za-z0-9_-]*$\")\n if !is_string(name) or !pattern.test(name) or reserved.includes(name)\n throw \"Invalid or reserved middleware name: ${name}\"\n return name\n"],"names":[],"mappings":";;;;;;;;;;;;;AAIA;;;;;;;;;;;;","x_lango_build":{"fingerprint":"10ecd19f49d610950fe5226367e8e6875ac3e95d77671b9218c2944b218d5dae","outputHash":"f2b374149ea746d208728bff2d14b9d920b3c7240d3925f5dd0f44b82f6a91cf","mapHash":"6d4418532baeceb103cf175b1016dae86429ac997a4696bba43d628136b70295"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module_loader.mjs","sources":["module_loader.lango"],"sourcesContent":["import js global Object\nimport js global Promise\n\nexport class ModuleLoader()\n methods\n target(spec)\n\nModuleLoader()\n @modules = Object/create(null)\n\nModuleLoader:target(spec)\n file = spec.module\n if Object/hasOwn(@modules, file)\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"module_loader.mjs","sources":["module_loader.lango"],"sourcesContent":["import js global Object\nimport js global Promise\n\nexport class ModuleLoader()\n methods\n target(spec)\n\nModuleLoader()\n @modules = Object/create(null)\n\nModuleLoader:target(spec)\n file = spec.module\n if Object/hasOwn(@modules, file)\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;","x_lango_build":{"fingerprint":"f9363cd7297a749a496a3ad1829a00fa66ba5208fbb9c0b3e6d561fac9da858c","outputHash":"c285ca92d6ce26a9b146ecc0d52c068badd94eac781892882a93614af89a5ec8","mapHash":"637bc9be83171ba4f68772a221cc176e92360adcc105efc81945be72c42b5189"}}
|
package/dist/options.mjs.map
CHANGED
|
@@ -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;;;;;;;;"}
|
|
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"}}
|
package/dist/origin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"origin.mjs","sources":["origin.lango"],"sourcesContent":["import js global Object\nimport js global URL\nimport js global process\n\nexport originOptions(spec)\nexport originAllowed(spec, request)\n\noriginOptions(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Origin configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"url\" and name != \"urlEnv\" and name != \"required\"\n throw \"Unknown origin option: ${name}\"\n if spec.url != null and spec.urlEnv != null\n throw \"Origin requires either url or urlEnv, not both\"\n url = spec.url\n if spec.urlEnv != null\n if !is_string(spec.urlEnv) or spec.urlEnv == \"\"\n throw \"Origin urlEnv must name an environment variable\"\n envName = spec.urlEnv\n url = process.env[envName]\n if !is_string(url) or url == \"\"\n throw \"Origin URL is required\"\n parsed = null\n try\n parsed = new URL(url)\n catch error\n throw \"Origin requires an exact HTTP or HTTPS origin\"\n if (parsed.protocol != \"https:\" and parsed.protocol != \"http:\") or parsed.origin != url\n throw \"Origin requires an exact HTTP or HTTPS origin without credentials, path, query or fragment\"\n required = spec.required\n if required == null or required == \"true\"\n required = true\n if required == \"false\"\n required = false\n if !is_bool(required)\n throw \"Origin required must be true or false\"\n return {\n url: url\n required: required\n }\n\noriginAllowed(spec, request)\n if spec == null\n return true\n headers = request.headers\n value = headers.origin\n if value == null\n if spec.required\n return false\n if value != null and value != spec.url\n return false\n site = headers[\"sec-fetch-site\"]\n return site == null or site == \"same-origin\" or site == \"none\"\n"],"names":[],"mappings":";;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"origin.mjs","sources":["origin.lango"],"sourcesContent":["import js global Object\nimport js global URL\nimport js global process\n\nexport originOptions(spec)\nexport originAllowed(spec, request)\n\noriginOptions(spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Origin configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"url\" and name != \"urlEnv\" and name != \"required\"\n throw \"Unknown origin option: ${name}\"\n if spec.url != null and spec.urlEnv != null\n throw \"Origin requires either url or urlEnv, not both\"\n url = spec.url\n if spec.urlEnv != null\n if !is_string(spec.urlEnv) or spec.urlEnv == \"\"\n throw \"Origin urlEnv must name an environment variable\"\n envName = spec.urlEnv\n url = process.env[envName]\n if !is_string(url) or url == \"\"\n throw \"Origin URL is required\"\n parsed = null\n try\n parsed = new URL(url)\n catch error\n throw \"Origin requires an exact HTTP or HTTPS origin\"\n if (parsed.protocol != \"https:\" and parsed.protocol != \"http:\") or parsed.origin != url\n throw \"Origin requires an exact HTTP or HTTPS origin without credentials, path, query or fragment\"\n required = spec.required\n if required == null or required == \"true\"\n required = true\n if required == \"false\"\n required = false\n if !is_bool(required)\n throw \"Origin required must be true or false\"\n return {\n url: url\n required: required\n }\n\noriginAllowed(spec, request)\n if spec == null\n return true\n headers = request.headers\n value = headers.origin\n if value == null\n if spec.required\n return false\n if value != null and value != spec.url\n return false\n site = headers[\"sec-fetch-site\"]\n return site == null or site == \"same-origin\" or site == \"none\"\n"],"names":[],"mappings":";;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"fb26132791c00588edd62b0701c8b2c78308e429b5d9aeacf5387f7f28831bfc","outputHash":"1cf4b9c511dddfc6f11619596119b6fad4102fca9ca2d81cf2e5a0498d9bffd2","mapHash":"675adca206b9d46239e607ff8a48366634055da2ef0ac2a0933f43e7f573c7b2"}}
|