@lango-project/lango-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +431 -2
  4. package/dist/.lango/bignumber.mjs +3119 -0
  5. package/dist/.lango/runtime.mjs +683 -0
  6. package/dist/.lango/xmldom/conventions.js +429 -0
  7. package/dist/.lango/xmldom/dom-parser.js +591 -0
  8. package/dist/.lango/xmldom/dom.js +3759 -0
  9. package/dist/.lango/xmldom/entities.js +2171 -0
  10. package/dist/.lango/xmldom/errors.js +205 -0
  11. package/dist/.lango/xmldom/grammar.js +559 -0
  12. package/dist/.lango/xmldom/index.js +41 -0
  13. package/dist/.lango/xmldom/package.json +1 -0
  14. package/dist/.lango/xmldom/sax.js +983 -0
  15. package/dist/.lango/xmldom.LICENSE.md +8 -0
  16. package/dist/body_reader.mjs +179 -0
  17. package/dist/body_reader.mjs.map +1 -0
  18. package/dist/builder.mjs +69 -0
  19. package/dist/builder.mjs.map +1 -0
  20. package/dist/cli/.lango/bignumber.mjs +3119 -0
  21. package/dist/cli/.lango/runtime.mjs +683 -0
  22. package/dist/cli/.lango/xmldom/conventions.js +429 -0
  23. package/dist/cli/.lango/xmldom/dom-parser.js +591 -0
  24. package/dist/cli/.lango/xmldom/dom.js +3759 -0
  25. package/dist/cli/.lango/xmldom/entities.js +2171 -0
  26. package/dist/cli/.lango/xmldom/errors.js +205 -0
  27. package/dist/cli/.lango/xmldom/grammar.js +559 -0
  28. package/dist/cli/.lango/xmldom/index.js +41 -0
  29. package/dist/cli/.lango/xmldom/package.json +1 -0
  30. package/dist/cli/.lango/xmldom/sax.js +983 -0
  31. package/dist/cli/.lango/xmldom.LICENSE.md +8 -0
  32. package/dist/cli/body_reader.mjs +179 -0
  33. package/dist/cli/body_reader.mjs.map +1 -0
  34. package/dist/cli/database.mjs +101 -0
  35. package/dist/cli/database.mjs.map +1 -0
  36. package/dist/cli/database_options.mjs +83 -0
  37. package/dist/cli/database_options.mjs.map +1 -0
  38. package/dist/cli/database_scope.mjs +82 -0
  39. package/dist/cli/database_scope.mjs.map +1 -0
  40. package/dist/cli/endpoint.mjs +44 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/options.mjs +165 -0
  43. package/dist/cli/options.mjs.map +1 -0
  44. package/dist/cli/postgres_adapter.mjs +166 -0
  45. package/dist/cli/postgres_adapter.mjs.map +1 -0
  46. package/dist/cli/routes.mjs +233 -0
  47. package/dist/cli/routes.mjs.map +1 -0
  48. package/dist/cli/server.mjs +572 -0
  49. package/dist/cli/server.mjs.map +1 -0
  50. package/dist/cli/sqlite_adapter.mjs +163 -0
  51. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  52. package/dist/database.mjs +101 -0
  53. package/dist/database.mjs.map +1 -0
  54. package/dist/database_options.mjs +83 -0
  55. package/dist/database_options.mjs.map +1 -0
  56. package/dist/database_scope.mjs +82 -0
  57. package/dist/database_scope.mjs.map +1 -0
  58. package/dist/endpoint.mjs +44 -0
  59. package/dist/endpoint.mjs.map +1 -0
  60. package/dist/group.mjs +75 -0
  61. package/dist/group.mjs.map +1 -0
  62. package/dist/library.mjs +6 -0
  63. package/dist/library.mjs.map +1 -0
  64. package/dist/options.mjs +165 -0
  65. package/dist/options.mjs.map +1 -0
  66. package/dist/postgres_adapter.mjs +166 -0
  67. package/dist/postgres_adapter.mjs.map +1 -0
  68. package/dist/postgres_worker.mjs +119 -0
  69. package/dist/postgres_worker.mjs.map +1 -0
  70. package/dist/response.mjs +62 -0
  71. package/dist/response.mjs.map +1 -0
  72. package/dist/routes.mjs +233 -0
  73. package/dist/routes.mjs.map +1 -0
  74. package/dist/runtime.mjs +475 -0
  75. package/dist/runtime.mjs.map +1 -0
  76. package/dist/server.mjs +568 -0
  77. package/dist/server.mjs.map +1 -0
  78. package/dist/sqlite_adapter.mjs +163 -0
  79. package/dist/sqlite_adapter.mjs.map +1 -0
  80. package/dist/token.mjs +106 -0
  81. package/dist/token.mjs.map +1 -0
  82. package/dist/tokens.mjs +76 -0
  83. package/dist/tokens.mjs.map +1 -0
  84. package/dist/worker.mjs +57 -0
  85. package/dist/worker.mjs.map +1 -0
  86. package/package.json +39 -4
  87. package/src/body_reader.lango +113 -0
  88. package/src/builder.lango +53 -0
  89. package/src/database.lango +66 -0
  90. package/src/database_options.lango +57 -0
  91. package/src/database_scope.lango +59 -0
  92. package/src/endpoint.lango +23 -0
  93. package/src/group.lango +47 -0
  94. package/src/library.lango +10 -0
  95. package/src/options.lango +128 -0
  96. package/src/postgres_adapter.lango +138 -0
  97. package/src/postgres_worker.lango +114 -0
  98. package/src/response.lango +42 -0
  99. package/src/routes.lango +160 -0
  100. package/src/runtime.lango +320 -0
  101. package/src/server.lango +432 -0
  102. package/src/sqlite_adapter.lango +127 -0
  103. package/src/token.lango +70 -0
  104. package/src/tokens.lango +70 -0
  105. package/src/worker.lango +43 -0
@@ -0,0 +1,165 @@
1
+ import { databaseOptions } from "./database_options.mjs";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ hostGlobalCall as __hostGlobalCall,
7
+ xml2obj as __xml2obj,
8
+ fromJson as __fromJson,
9
+ toJson as __toJson,
10
+ isNumber as __isNumber,
11
+ isString as __isString,
12
+ isBool as __isBool,
13
+ isObject as __isObject,
14
+ isArray as __isArray,
15
+ entries as __entries,
16
+ requireBoolean as __requireBoolean,
17
+ normalize as __normalize,
18
+ boundary as __boundary,
19
+ requireArity as __requireArity,
20
+ } from "./.lango/runtime.mjs";
21
+
22
+ export function attributes(tag, allowed) {
23
+ __requireArity(arguments.length, [0, 1], "attributes");
24
+ tag = __boundary(tag);
25
+ allowed = __boundary(allowed);
26
+ for (const [key, value] of __entries(__normalize(tag.attributes()))) {
27
+ if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
28
+ throw `Unknown ${__normalize(tag.tag())} attribute: ${key}`;
29
+ }
30
+ }
31
+ return null;
32
+ return null;
33
+ }
34
+
35
+ export function options(root, supplied = null) {
36
+ __requireArity(arguments.length, [0], "options");
37
+ root = __boundary(root);
38
+ supplied = __boundary(supplied);
39
+ let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 1048576, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null };
40
+ if (__requireBoolean(supplied !== null)) {
41
+ for (const [key, value] of __entries(supplied)) {
42
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(result, key)))) || __requireBoolean(key === "root"))) {
43
+ throw `Unknown server option: ${key}`;
44
+ }
45
+ result[key] = value;
46
+ }
47
+ }
48
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(result.host)))) || __requireBoolean(__normalize(result.host) === ""))) {
49
+ throw "Host must be a nonempty string";
50
+ }
51
+ for (const key of ["port", "workers", "maxQueue", "bodyLimit", "bodyTimeoutMs", "requestTimeoutMs", "eventTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs", "ttlSeconds"]) {
52
+ let value = __normalize(result[key]);
53
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isNumber(value))) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(value))))) || __requireBoolean(value < 0))) {
54
+ throw `Invalid server option: ${key}`;
55
+ }
56
+ if (__requireBoolean(__requireBoolean(__requireBoolean(key !== "port") && __requireBoolean(key !== "maxQueue")) && __requireBoolean(value === 0))) {
57
+ throw `Server option must be positive: ${key}`;
58
+ }
59
+ if (__requireBoolean(__requireBoolean(__normalize(key.endsWith("Ms"))) && __requireBoolean(value > 2147483647))) {
60
+ throw `Timeout exceeds timer limit: ${key}`;
61
+ }
62
+ }
63
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(result.port) > 65535) || __requireBoolean(__normalize(result.workers) > 128)) || __requireBoolean(__normalize(result.ttlSeconds) > 86400))) {
64
+ throw "Server option exceeds supported limit";
65
+ }
66
+ if (__requireBoolean(!__requireBoolean(__isBool(__normalize(result.requestEvent))))) {
67
+ throw "requestEvent must be boolean";
68
+ }
69
+ for (const key of ["issuer", "audience", "activeKeyId"]) {
70
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(result[key])))) || __requireBoolean(__normalize(result[key]) === ""))) {
71
+ throw `Missing JWT option: ${key}`;
72
+ }
73
+ }
74
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(__normalize(result.keys)))) || __requireBoolean(__isArray(__normalize(result.keys))))) {
75
+ throw "JWT keys must be a map";
76
+ }
77
+ let keys = __normalize(__hostGlobal(["Object"]).assign(__normalize(__hostGlobal(["Object"]).create(null)), __normalize(result.keys)));
78
+ if (__requireBoolean(__normalize(result.key) !== null)) {
79
+ keys[__normalize(result.activeKeyId)] = __normalize(result.key);
80
+ }
81
+ if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(keys, __normalize(result.activeKeyId)))))) {
82
+ throw "JWT signing key is required";
83
+ }
84
+ for (const [id, secret] of __entries(keys)) {
85
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(secret))) || __requireBoolean(__normalize(secret.length) < 32))) {
86
+ throw "JWT keys must contain at least 32 characters";
87
+ }
88
+ }
89
+ result.keys = keys;
90
+ result.key = null;
91
+ result.database = databaseOptions(__normalize(result.root), __normalize(result.database), __normalize(result.workers));
92
+ return result;
93
+ return null;
94
+ }
95
+
96
+ export function deployment(directory) {
97
+ __requireArity(arguments.length, [0], "deployment");
98
+ directory = __boundary(directory);
99
+ let file = __normalize(path.join(directory, "deploy.xml"));
100
+ let root = __xml2obj(__normalize(fs.readFileSync(file, "utf8")));
101
+ if (__requireBoolean(__normalize(root.tag()) !== "deploy")) {
102
+ throw "Expected deploy root";
103
+ }
104
+ attributes(root, []);
105
+ let settings = { };
106
+ let seen = [];
107
+ for (const tag of __normalize(root.children())) {
108
+ let name = __normalize(tag.tag());
109
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(seen.includes(name))) || __requireBoolean(__normalize(__normalize(tag.children()).length) !== 0)) || __requireBoolean(__normalize(__normalize(tag.innerText()).trim()) !== ""))) {
110
+ throw `Duplicate or nonempty deployment section: ${name}`;
111
+ }
112
+ seen.push(name);
113
+ if (name === "http") {
114
+ attributes(tag, ["host", "port", "bodyLimit", "bodyTimeoutMs"]);
115
+ } else if (name === "workers") {
116
+ attributes(tag, ["workers", "maxQueue", "requestTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs"]);
117
+ } else if (name === "events") {
118
+ attributes(tag, ["requestEvent", "eventTimeoutMs"]);
119
+ } else if (name === "database") {
120
+ attributes(tag, ["type", "file", "connectionEnv", "busyTimeoutMs", "queryTimeoutMs", "connectTimeoutSeconds"]);
121
+ settings.database = __normalize(tag.attributes());
122
+ continue;
123
+ } else if (name === "jwt") {
124
+ attributes(tag, ["issuer", "audience", "ttlSeconds", "keyEnv", "keysFile", "activeKeyId"]);
125
+ } else {
126
+ throw `Unknown deployment section: ${name}`;
127
+ }
128
+ for (const [key, value] of __entries(__normalize(tag.attributes()))) {
129
+ if (__requireBoolean(key === "keyEnv")) {
130
+ settings.key = __normalize(__hostGlobal(["process"]).env[value]);
131
+ if (__requireBoolean(__normalize(settings.key) === null)) {
132
+ throw `JWT key environment variable is missing: ${value}`;
133
+ }
134
+ } else {
135
+ if (__requireBoolean(key === "keysFile")) {
136
+ settings.keys = __fromJson(__normalize(fs.readFileSync(__normalize(path.resolve(directory, value)), "utf8")));
137
+ } else {
138
+ if (__requireBoolean(contains(["host", "issuer", "audience", "activeKeyId"], key))) {
139
+ settings[key] = value;
140
+ } else {
141
+ if (__requireBoolean(key === "requestEvent")) {
142
+ if (__requireBoolean(__requireBoolean(value !== "true") && __requireBoolean(value !== "false"))) {
143
+ throw "requestEvent must be true or false";
144
+ }
145
+ settings[key] = value === "true";
146
+ } else {
147
+ settings[key] = __hostGlobalCall(["Number"], value);
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ return options(directory, settings);
155
+ return null;
156
+ }
157
+
158
+ export function contains(items, value) {
159
+ __requireArity(arguments.length, [0, 1], "contains");
160
+ items = __boundary(items);
161
+ value = __boundary(value);
162
+ return __normalize(items.includes(value));
163
+ return null;
164
+ }
165
+ //# sourceMappingURL=options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./database_options\"\n databaseOptions(root, spec, workers)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 1048576\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"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 \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;"}
@@ -0,0 +1,166 @@
1
+ import * as modules from "node:module";
2
+ import * as path from "node:path";
3
+ import * as threads from "node:worker_threads";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ requireBoolean as __requireBoolean,
7
+ normalize as __normalize,
8
+ finite as __finite,
9
+ numericAdd as __numericAdd,
10
+ boundary as __boundary,
11
+ requireArity as __requireArity,
12
+ withArity as __withArity,
13
+ } from "./.lango/runtime.mjs";
14
+
15
+ export class PostgresAdapter {
16
+ parameterStyle;
17
+ #closed;
18
+ #broken;
19
+ #state;
20
+ #depth;
21
+ #rollbackOnly;
22
+ #timeout;
23
+ #signal;
24
+ #port;
25
+ #lango;
26
+ #worker;
27
+ constructor(mod, settings, root) {
28
+ __requireArity(arguments.length, [0, 1, 2], "constructor");
29
+ mod = __boundary(mod);
30
+ settings = __boundary(settings);
31
+ root = __boundary(root);
32
+ this.#closed = false;
33
+ this.#broken = false;
34
+ this.#state = null;
35
+ this.#depth = 0;
36
+ this.#rollbackOnly = false;
37
+ this.parameterStyle = "postgresql";
38
+ this.#timeout = __normalize(__hostGlobal(["Math"]).min(2147483647, __numericAdd(__normalize(settings.queryTimeoutMs), 1000)));
39
+ this.#signal = new (__hostGlobal(["Int32Array"]))(new (__hostGlobal(["SharedArrayBuffer"]))(4));
40
+ let channel = __normalize(__hostGlobal(["Reflect"]).construct(__normalize(mod.MessageChannel), []));
41
+ this.#port = __normalize(channel.port1);
42
+ let resolver = __normalize(modules.createRequire(__normalize(path.join(root, "package.json"))));
43
+ let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
44
+ this.#worker = __normalize(__hostGlobal(["Reflect"]).construct(__normalize(mod.Worker), [__normalize(path.join(__normalize(path.dirname(entry)), "postgres_worker.mjs")), { workerData: { settings: settings, port: __normalize(channel.port2), signal: __normalize(this.#signal) }, transferList: [__normalize(channel.port2)] }]));
45
+ let worker = __normalize(this.#worker);
46
+ __normalize(worker.on("error", __withArity((error) => {
47
+ error = __boundary(error);
48
+ this.#broken = true;
49
+ return null;
50
+ }, [0], "closure")));
51
+ __normalize(this.#worker.unref());
52
+ __normalize(this.#port.unref());
53
+ try {
54
+ this.#exchange({ action: "connect" }, __normalize(__hostGlobal(["Math"]).min(2147483647, __numericAdd(__finite(__normalize(settings.connectTimeoutSeconds) * 1000), 1000))));
55
+ } catch (error) {
56
+ this.close();
57
+ throw new (__hostGlobal(["Error"]))("PostgreSQL initialization failed");
58
+ }
59
+ }
60
+ #exchange(task, timeout) {
61
+ __requireArity(arguments.length, [0, 1], "exchange");
62
+ task = __boundary(task);
63
+ timeout = __boundary(timeout);
64
+ if (__requireBoolean(__requireBoolean(__normalize(this.#closed)) || __requireBoolean(__normalize(this.#broken)))) {
65
+ throw new (__hostGlobal(["Error"]))("PostgreSQL connection is unavailable");
66
+ }
67
+ __normalize(__hostGlobal(["Atomics"]).store(__normalize(this.#signal), 0, 0));
68
+ __normalize(this.#port.postMessage(task));
69
+ let waited = __normalize(__hostGlobal(["Atomics"]).wait(__normalize(this.#signal), 0, 0, timeout));
70
+ if (__requireBoolean(waited === "timed-out")) {
71
+ this.#broken = true;
72
+ __normalize(this.#worker.terminate());
73
+ throw new (__hostGlobal(["Error"]))("PostgreSQL operation timed out");
74
+ }
75
+ let reply = __normalize(threads.receiveMessageOnPort(__normalize(this.#port)));
76
+ if (__requireBoolean(reply === null)) {
77
+ this.#broken = true;
78
+ throw new (__hostGlobal(["Error"]))("PostgreSQL response was not received");
79
+ }
80
+ let result = __normalize(reply.message);
81
+ this.#state = __normalize(result.state);
82
+ if (__requireBoolean(__normalize(result.failed))) {
83
+ this.#broken = __normalize(result.dead);
84
+ let error = new (__hostGlobal(["Error"]))("PostgreSQL query failed");
85
+ error.code = __normalize(result.code);
86
+ error.position = __normalize(result.position);
87
+ error.transactionUnusable = __normalize(this.#state) === "failed";
88
+ throw error;
89
+ }
90
+ return result;
91
+ return null;
92
+ }
93
+ execute(sql, parameters) {
94
+ __requireArity(arguments.length, [0, 1], "execute");
95
+ sql = __boundary(sql);
96
+ parameters = __boundary(parameters);
97
+ return this.#exchange({ action: "query", sql: sql, parameters: parameters }, __normalize(this.#timeout));
98
+ return null;
99
+ }
100
+ begin() {
101
+ if (__requireBoolean(__requireBoolean(__normalize(this.#depth) === 0) && __requireBoolean(__normalize(this.#state) === null))) {
102
+ this.execute("BEGIN", []);
103
+ }
104
+ this.#depth = __numericAdd(__normalize(this.#depth), 1);
105
+ return null;
106
+ return null;
107
+ }
108
+ commit() {
109
+ if (__requireBoolean(__normalize(this.#depth) === 0)) {
110
+ throw new (__hostGlobal(["Error"]))("NoActiveTransaction");
111
+ }
112
+ if (__requireBoolean(__normalize(this.#depth) > 1)) {
113
+ this.#depth = __finite(__normalize(this.#depth) - 1);
114
+ return null;
115
+ }
116
+ if (__requireBoolean(__requireBoolean(__normalize(this.#rollbackOnly)) || __requireBoolean(__normalize(this.#state) === "failed"))) {
117
+ this.rollback();
118
+ throw new (__hostGlobal(["Error"]))("TransactionRolledBack");
119
+ }
120
+ this.execute("COMMIT", []);
121
+ this.#depth = 0;
122
+ return null;
123
+ return null;
124
+ }
125
+ rollback() {
126
+ if (__requireBoolean(__normalize(this.#depth) > 1)) {
127
+ this.#depth = __finite(__normalize(this.#depth) - 1);
128
+ this.#rollbackOnly = true;
129
+ return null;
130
+ }
131
+ if (__requireBoolean(__normalize(this.#state) !== null)) {
132
+ this.execute("ROLLBACK", []);
133
+ }
134
+ this.#depth = 0;
135
+ this.#rollbackOnly = false;
136
+ return null;
137
+ return null;
138
+ }
139
+ transactionState() {
140
+ if (__requireBoolean(__normalize(this.#broken))) {
141
+ throw new (__hostGlobal(["Error"]))("PostgreSQL connection is unavailable");
142
+ }
143
+ if (__requireBoolean(__requireBoolean(__normalize(this.#rollbackOnly)) && __requireBoolean(__normalize(this.#state) !== "failed"))) {
144
+ return "rollback_only";
145
+ }
146
+ return __normalize(this.#state);
147
+ return null;
148
+ }
149
+ close() {
150
+ if (__requireBoolean(__normalize(this.#closed))) {
151
+ return null;
152
+ }
153
+ try {
154
+ if (__requireBoolean(!__requireBoolean(__normalize(this.#broken)))) {
155
+ this.#exchange({ action: "close" }, __normalize(this.#timeout));
156
+ }
157
+ } finally {
158
+ this.#closed = true;
159
+ __normalize(this.#port.close());
160
+ __normalize(this.#worker.terminate());
161
+ }
162
+ return null;
163
+ return null;
164
+ }
165
+ }
166
+ //# sourceMappingURL=postgres_adapter.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres_adapter.mjs","sources":["postgres_adapter.lango"],"sourcesContent":["import js \"node:module\" as modules\nimport js \"node:path\" as path\nimport js \"node:worker_threads\" as threads\nimport js global Reflect\nimport js global SharedArrayBuffer\nimport js global Int32Array\nimport js global Atomics\nimport js global Math\nimport js global Error\n\nexport class PostgresAdapter(mod, settings, root)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nPostgresAdapter(mod, settings, root)\n @closed = false\n @broken = false\n @state = null\n @depth = 0\n @rollbackOnly = false\n @parameterStyle = \"postgresql\"\n @timeout = Math/min(2147483647, settings.queryTimeoutMs + 1000)\n @signal = new Int32Array(new SharedArrayBuffer(4))\n channel = Reflect/construct(mod.MessageChannel, [])\n @port = channel.port1\n resolver = modules/createRequire(path/join(root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @worker = Reflect/construct(mod.Worker, [path/join(path/dirname(entry), \"postgres_worker.mjs\"), {\n workerData: {\n settings: settings\n port: channel.port2\n signal: @signal\n }\n transferList: [channel.port2]\n }])\n worker = @worker\n worker.on(\"error\", (error)\n @broken = true\n )\n @worker.unref()\n @port.unref()\n try\n exchange({\n action: \"connect\"\n }, Math/min(2147483647, settings.connectTimeoutSeconds * 1000 + 1000))\n catch error\n close()\n throw new Error(\"PostgreSQL initialization failed\")\n\nPostgresAdapter:exchange(task, timeout)\n if @closed or @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n Atomics/store(@signal, 0, 0)\n @port.postMessage(task)\n waited = Atomics/wait(@signal, 0, 0, timeout)\n if waited == \"timed-out\"\n @broken = true\n @worker.terminate()\n throw new Error(\"PostgreSQL operation timed out\")\n reply = threads/receiveMessageOnPort(@port)\n if reply == null\n @broken = true\n throw new Error(\"PostgreSQL response was not received\")\n result = reply.message\n @state = result.state\n if result.failed\n @broken = result.dead\n error = new Error(\"PostgreSQL query failed\")\n error.code = result.code\n error.position = result.position\n error.transactionUnusable = @state == \"failed\"\n throw error\n return result\n\nPostgresAdapter:execute(sql, parameters)\n return exchange({\n action: \"query\"\n sql: sql\n parameters: parameters\n }, @timeout)\n\nPostgresAdapter:begin()\n if @depth == 0 and @state == null\n execute(\"BEGIN\", [])\n @depth = @depth + 1\n return null\n\nPostgresAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @rollbackOnly or @state == \"failed\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n execute(\"COMMIT\", [])\n @depth = 0\n return null\n\nPostgresAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @rollbackOnly = true\n return null\n if @state != null\n execute(\"ROLLBACK\", [])\n @depth = 0\n @rollbackOnly = false\n return null\n\nPostgresAdapter:transactionState()\n if @broken\n throw new Error(\"PostgreSQL connection is unavailable\")\n if @rollbackOnly and @state != \"failed\"\n return \"rollback_only\"\n return @state\n\nPostgresAdapter:close()\n if @closed\n return null\n try\n if !@broken\n exchange({\n action: \"close\"\n }, @timeout)\n finally\n @closed = true\n @port.close()\n @worker.terminate()\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,119 @@
1
+ import * as pg from "pg";
2
+ import * as threads from "node:worker_threads";
3
+ import {
4
+ hostGlobal as __hostGlobal,
5
+ requireBoolean as __requireBoolean,
6
+ normalize as __normalize,
7
+ finite as __finite,
8
+ boundary as __boundary,
9
+ requireArity as __requireArity,
10
+ withArity as __withArity,
11
+ } from "./.lango/runtime.mjs";
12
+
13
+ let state = initialState();
14
+
15
+ let installed = install();
16
+ function install() {
17
+ let port = threads.workerData.port;
18
+ __normalize(port.on("message", __withArity((task) => {
19
+ task = __boundary(task);
20
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity((ignored) => {
21
+ ignored = __boundary(ignored);
22
+ return execute(task);
23
+ return null;
24
+ }, [0], "closure")).then(__withArity((result) => {
25
+ result = __boundary(result);
26
+ reply(result);
27
+ return null;
28
+ return null;
29
+ }, [0], "closure")).catch(__withArity((error) => {
30
+ error = __boundary(error);
31
+ if (__requireBoolean(__normalize(state.transaction) !== null)) {
32
+ state.transaction = "failed";
33
+ }
34
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(error.code) === null) || __requireBoolean(error.code.length !== 5)) || __requireBoolean(__normalize(error.code.startsWith("08"))))) {
35
+ state.dead = true;
36
+ }
37
+ let position = null;
38
+ if (__requireBoolean(__normalize(error.position) !== null)) {
39
+ position = __normalize(__hostGlobal(["Number"]).parseInt(__normalize(error.position), 10));
40
+ }
41
+ reply({ failed: true, dead: __normalize(state.dead), code: __normalize(error.code), position: position, state: __normalize(state.transaction) });
42
+ return null;
43
+ return null;
44
+ }, [0], "closure"));
45
+ return null;
46
+ }, [0], "closure")));
47
+ return null;
48
+ return null;
49
+ }
50
+
51
+ function execute(task) {
52
+ __requireArity(arguments.length, [0], "execute");
53
+ task = __boundary(task);
54
+ let settings = threads.workerData.settings;
55
+ if (__normalize(task.action) === "connect") {
56
+ state.client = new pg.Client({ connectionString: __normalize(settings.connection), connectionTimeoutMillis: __normalize(__hostGlobal(["Math"]).min(2147483647, __finite(__normalize(settings.connectTimeoutSeconds) * 1000))), statement_timeout: __normalize(settings.queryTimeoutMs), application_name: "lango-server" });
57
+ let client = __normalize(state.client);
58
+ __normalize(client.on("error", __withArity((error) => {
59
+ error = __boundary(error);
60
+ state.dead = true;
61
+ return null;
62
+ }, [0], "closure")));
63
+ return __normalize(client.connect()).then(__withArity((ignored) => {
64
+ ignored = __boundary(ignored);
65
+ return success([], null);
66
+ return null;
67
+ }, [0], "closure"));
68
+ } else if (__normalize(task.action) === "query") {
69
+ return __normalize(state.client.query({ text: __normalize(task.sql), values: __normalize(task.parameters), queryMode: "extended" })).then(__withArity((result) => {
70
+ result = __boundary(result);
71
+ if (__normalize(result.command) === "BEGIN") {
72
+ state.transaction = "active";
73
+ } else if (__normalize(result.command) === "COMMIT" || __normalize(result.command) === "ROLLBACK") {
74
+ state.transaction = null;
75
+ }
76
+ let changes = null;
77
+ if (__normalize(result.command) === "INSERT" || __normalize(result.command) === "UPDATE" || __normalize(result.command) === "DELETE" || __normalize(result.command) === "MERGE") {
78
+ changes = __normalize(result.rowCount);
79
+ }
80
+ return success(__normalize(result.rows), changes);
81
+ return null;
82
+ }, [0], "closure"));
83
+ } else if (__normalize(task.action) === "close") {
84
+ return __normalize(state.client.end()).then(__withArity((ignored) => {
85
+ ignored = __boundary(ignored);
86
+ return success([], null);
87
+ return null;
88
+ }, [0], "closure"));
89
+ } else {
90
+ throw "Unknown PostgreSQL operation";
91
+ }
92
+ return null;
93
+ }
94
+
95
+ function success(rows, changes) {
96
+ __requireArity(arguments.length, [0, 1], "success");
97
+ rows = __boundary(rows);
98
+ changes = __boundary(changes);
99
+ return { failed: false, dead: false, state: __normalize(state.transaction), rows: rows, changes: changes, lastInsertRowid: null };
100
+ return null;
101
+ }
102
+
103
+ function reply(result) {
104
+ __requireArity(arguments.length, [0], "reply");
105
+ result = __boundary(result);
106
+ let port = threads.workerData.port;
107
+ let signal = threads.workerData.signal;
108
+ __normalize(port.postMessage(result));
109
+ __normalize(__hostGlobal(["Atomics"]).store(signal, 0, 1));
110
+ __normalize(__hostGlobal(["Atomics"]).notify(signal, 0));
111
+ return null;
112
+ return null;
113
+ }
114
+
115
+ function initialState() {
116
+ return { client: null, transaction: null, dead: false };
117
+ return null;
118
+ }
119
+ //# sourceMappingURL=postgres_worker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres_worker.mjs","sources":["postgres_worker.lango"],"sourcesContent":["import js \"pg\" as pg\nimport js \"node:worker_threads\" as threads\nimport js global Atomics\nimport js global Math\nimport js global Number\nimport js global Promise\n\n\nglobal state = initialState()\nglobal installed = install()\n\ninstall()\n port = threads.workerData.port\n port.on(\"message\", (task)\n return chain Promise/resolve(null)\n then(ignored)\n capture task\n return execute(task)\n then(result)\n reply(result)\n return null\n catch(error)\n global state\n if state.transaction != null\n state.transaction = \"failed\"\n if error.code == null or error.code.length != 5 or error.code.startsWith(\"08\")\n state.dead = true\n position = null\n if error.position != null\n position = Number/parseInt(error.position, 10)\n reply({\n failed: true\n dead: state.dead\n code: error.code\n position: position\n state: state.transaction\n })\n return null\n )\n return null\n\nexecute(task)\n global state\n settings = threads.workerData.settings\n switch task.action\n case \"connect\"\n state.client = new pg/Client({\n connectionString: settings.connection\n connectionTimeoutMillis: Math/min(2147483647, settings.connectTimeoutSeconds * 1000)\n statement_timeout: settings.queryTimeoutMs\n application_name: \"lango-server\"\n })\n client = state.client\n client.on(\"error\", (error)\n global state\n state.dead = true\n )\n return chain client.connect()\n then(ignored)\n return success([], null)\n case \"query\"\n return chain state.client.query({\n text: task.sql\n values: task.parameters\n queryMode: \"extended\"\n })\n then(result)\n global state\n switch result.command\n case \"BEGIN\"\n state.transaction = \"active\"\n case \"COMMIT\"\n case \"ROLLBACK\"\n state.transaction = null\n changes = null\n switch result.command\n case \"INSERT\"\n case \"UPDATE\"\n case \"DELETE\"\n case \"MERGE\"\n changes = result.rowCount\n return success(result.rows, changes)\n case \"close\"\n return chain state.client.end()\n then(ignored)\n return success([], null)\n else\n throw \"Unknown PostgreSQL operation\"\n\nsuccess(rows, changes)\n global state\n return {\n failed: false\n dead: false\n state: state.transaction\n rows: rows\n changes: changes\n lastInsertRowid: null\n }\n\nreply(result)\n port = threads.workerData.port\n signal = threads.workerData.signal\n port.postMessage(result)\n Atomics/store(signal, 0, 1)\n Atomics/notify(signal, 0)\n return null\n\ninitialState()\n return {\n client: null\n transaction: null\n dead: false\n }\n"],"names":[],"mappings":";;;;;;;;;;;;AAQA;;AACA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;AAWA;;;;;;;;;;;;AAQA;;;;;"}
@@ -0,0 +1,62 @@
1
+ import { contains } from "./options.mjs";
2
+ import * as http from "node:http";
3
+ import {
4
+ fromJson as __fromJson,
5
+ toJson as __toJson,
6
+ isNumber as __isNumber,
7
+ isString as __isString,
8
+ isBool as __isBool,
9
+ isObject as __isObject,
10
+ isArray as __isArray,
11
+ requireBoolean as __requireBoolean,
12
+ normalize as __normalize,
13
+ finite as __finite,
14
+ boundary as __boundary,
15
+ requireArity as __requireArity,
16
+ } from "./.lango/runtime.mjs";
17
+
18
+ export class Response {
19
+ #status;
20
+ #headers;
21
+ constructor() {
22
+ this.#status = 200;
23
+ this.#headers = { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" };
24
+ }
25
+ status(code) {
26
+ __requireArity(arguments.length, [0], "status");
27
+ code = __boundary(code);
28
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isNumber(code))) || __requireBoolean(__finite(code % 1) !== 0)) || __requireBoolean(code < 200)) || __requireBoolean(code > 599)) || __requireBoolean(code === 204)) || __requireBoolean(code === 205)) || __requireBoolean(code === 304))) {
29
+ throw "Response requires a JSON-compatible HTTP status";
30
+ }
31
+ this.#status = code;
32
+ return this;
33
+ return null;
34
+ }
35
+ header(name, value) {
36
+ __requireArity(arguments.length, [0, 1], "header");
37
+ name = __boundary(name);
38
+ value = __boundary(value);
39
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(name))) || __requireBoolean(!__requireBoolean(__isString(value))))) {
40
+ throw "Header name and value must be strings";
41
+ }
42
+ name = __normalize(name.toLowerCase());
43
+ if (__requireBoolean(contains(["x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name))) {
44
+ throw `Reserved response header: ${name}`;
45
+ }
46
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(name.includes("\\r"))) || __requireBoolean(__normalize(name.includes("\n")))) || __requireBoolean(__normalize(value.includes("\\r")))) || __requireBoolean(__normalize(value.includes("\n"))))) {
47
+ throw "Invalid response header";
48
+ }
49
+ __normalize(http.validateHeaderName(name));
50
+ __normalize(http.validateHeaderValue(name, value));
51
+ this.#headers[name] = value;
52
+ return this;
53
+ return null;
54
+ }
55
+ result(body) {
56
+ __requireArity(arguments.length, [0], "result");
57
+ body = __boundary(body);
58
+ return { status: __normalize(this.#status), headers: __fromJson(__toJson(__normalize(this.#headers))), body: body };
59
+ return null;
60
+ }
61
+ }
62
+ //# sourceMappingURL=response.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-token\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}