@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
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work of authorship, whether in Source
41
+ or Object form, that is based on (or derived from) the Work and for which
42
+ the editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a cross-claim
83
+ or counterclaim in a lawsuit) alleging that the Work or a Contribution
84
+ incorporated within the Work constitutes direct or contributory patent
85
+ infringement, then any patent licenses granted to You under this License
86
+ for that Work shall terminate as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You meet
91
+ the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding those notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
201
+
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Lango Server
2
+ Copyright 2026 Lango Project contributors
3
+
4
+ Contains HTTP body-reading and worker-lifecycle techniques adapted from Lango API.
package/README.md CHANGED
@@ -1,3 +1,432 @@
1
- # Temporary Holding Version
1
+ # Lango Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A JSON HTTP server written in Lango. Its public package API contains two classes:
4
+ `Server` and `Builder`. Application handlers are exported functions identified by
5
+ module and function names. Each request runs in one worker; worker setup stays
6
+ inside the server.
7
+
8
+ This is a new package. It does not migrate or modify Lango API, UI, or Client.
9
+
10
+ ## Requirements and installation
11
+
12
+ Node.js 24 or later is required. Install the server in the application package:
13
+
14
+ ```sh
15
+ npm install @lango-project/lango-server
16
+ ```
17
+
18
+ Version 0.1.0 is currently prepared locally; this command requires publication.
19
+ For a local package archive, run `npm install /path/to/lango-project-lango-server-0.1.0.tgz`.
20
+
21
+ Keep application modules separate from the server launcher. Compile application
22
+ Lango sources before starting the server and expose the generated modules using
23
+ normal npm package exports. Linked packages work when their compiled exports
24
+ exist; the server does not compile, watch, or restart application code.
25
+
26
+ ## Standalone server
27
+
28
+ An application directory contains `package.json`, `routes.xml`, and `deploy.xml`.
29
+ Relative configuration file paths resolve against this directory. Module names
30
+ resolve using its npm dependencies.
31
+
32
+ ```sh
33
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
34
+ npx lango-server /path/to/application
35
+ ```
36
+
37
+ On Windows PowerShell, set `$env:LANGO_JWT_KEY` before running the same command.
38
+ Use a process manager, container, or service wrapper for deployment. The launcher
39
+ handles SIGINT and SIGTERM by awaiting `close()`; the library installs no signal
40
+ handlers. TLS and public web-server configuration belong to deployment.
41
+
42
+ `start()` resolves with `{ host, port }` after all workers have loaded and
43
+ validated their handlers and the HTTP listener is ready. Port zero selects an
44
+ available port. A second call rejects. Startup failures reject and release the
45
+ pool. `close()` is idempotent, stops accepting work, drains accepted requests,
46
+ and releases the listener and pool. A shutdown deadline forces closure and
47
+ rejects rather than silently reporting a graceful shutdown. Closing an unused
48
+ server is safe; a closed server cannot be restarted.
49
+
50
+ ## Application handlers
51
+
52
+ ```lango
53
+ export greet(input)
54
+
55
+ greet(input)
56
+ context token
57
+ context log
58
+ log.info("Greeting requested")
59
+ return {
60
+ message: "Hello, ${input.name}"
61
+ clientId: token.clientId
62
+ }
63
+ ```
64
+
65
+ The handler receives one JSON object. The server accepts POST requests with
66
+ `Content-Type: application/json`; query strings are not supported. Malformed
67
+ JSON, empty bodies, arrays, and primitive input values are rejected. This is an
68
+ RPC transport rather than a general-purpose HTTP framework.
69
+
70
+ A handler may return a Promise. Its resolved result is serialized with native
71
+ `JSON.stringify()` **inside the worker**, so a returned class can provide a
72
+ public `toJSON()` method. An omitted Lango return produces JSON null. Unserializable
73
+ results fail with HTTP 500. The result can be any JSON value, although ordinary
74
+ application handlers normally return objects. Serialization and handler failures
75
+ never publish token changes. Private exception details are not sent to clients.
76
+
77
+ A worker processes one request at a time, including its Promise and events.
78
+ Synchronous work does not block the main HTTP loop. Promise callbacks still use
79
+ Lango's explicit `capture` rules; capture any contexts needed by later callbacks.
80
+ Workers retain their loaded modules between requests. Module-level state is
81
+ worker-local, not shared or client-specific. An optional configured SQL database is available through `context db`; application schema and migrations remain application-owned.
82
+
83
+ ## Routes
84
+
85
+ ```xml
86
+ <routes>
87
+ <group path="/orders" module="@shop/orders">
88
+ <endpoint path="/save" handler="save"/>
89
+ <endpoint path="/list" handler="list"/>
90
+ </group>
91
+ <endpoint path="/login" module="@shop/auth" handler="login" auth="anonymous"/>
92
+ <include module="@shop/catalog" path="/catalog"/>
93
+ <event name="register" module="@shop/auth" handler="register"/>
94
+ <event name="validate" module="@shop/auth" handler="validate"/>
95
+ <event name="request" module="@shop/audit" handler="record"/>
96
+ </routes>
97
+ ```
98
+
99
+ * Every endpoint has a module and exported function name. A group can supply the
100
+ module and auth permission to its children. Includes inherit group auth as a
101
+ default; explicit permissions inside an included file still take precedence.
102
+ The including group does not supply handler modules across the package boundary. No handler is looked up in the
103
+ launcher module. Absolute or relative file modules are also accepted for
104
+ application-local code; relative modules in XML resolve from the containing
105
+ package, and Builder modules resolve from its application root.
106
+ * Groups concatenate path prefixes. Paths are case-sensitive. Exact paths win;
107
+ otherwise the longest matching trailing `/*` prefix wins. `/orders/*` matches
108
+ `/orders/save`, not `/orders`. Duplicate paths and unsupported wildcard forms
109
+ are startup errors. The handler sees the actual path in `context request`.
110
+ * Includes resolve the package's exported `./routes.xml`. Publish the XML file
111
+ and add it to the package's `exports` and `files`. Nested includes resolve
112
+ dependencies from the including package. Include prefixes concatenate; a
113
+ missing include path mounts at `/`. The same package can be mounted at several
114
+ prefixes. Include cycles, missing exports, and duplicate endpoints fail early.
115
+ * Included files contain routes only. They cannot register global lifecycle
116
+ events or change deployment/JWT settings. Events belong to the application's
117
+ root routes file (or Builder). Each event can be registered once.
118
+ * Unknown XML elements and attributes are rejected. XML and Builder definitions
119
+ use the same endpoint validation and startup loading path.
120
+
121
+ A feature package can expose its definitions as follows:
122
+
123
+ ```json
124
+ {
125
+ "name": "@shop/catalog",
126
+ "type": "module",
127
+ "exports": {
128
+ ".": "./dist/catalog.mjs",
129
+ "./routes.xml": "./routes.xml"
130
+ },
131
+ "files": ["dist/**", "routes.xml"]
132
+ }
133
+ ```
134
+
135
+ Its XML still names the handler module explicitly, for example
136
+ `<endpoint path="/list" module="@shop/catalog" handler="list"/>`.
137
+
138
+ ## Builder
139
+
140
+ ```lango
141
+ import js "@lango-project/lango-server" as server
142
+
143
+ createServer(root, signingKey)
144
+ builder = new server/Builder(root)
145
+ builder.configure({
146
+ host: "127.0.0.1"
147
+ port: 3000
148
+ key: signingKey
149
+ })
150
+ orders = builder.group({
151
+ path: "/orders"
152
+ module: "@shop/orders"
153
+ })
154
+ orders.endpoint({
155
+ path: "/save"
156
+ handler: "save"
157
+ })
158
+ builder.include({
159
+ module: "@shop/catalog"
160
+ path: "/catalog"
161
+ })
162
+ builder.event({
163
+ name: "validate"
164
+ module: "@shop/auth"
165
+ handler: "validate"
166
+ })
167
+ return builder.build()
168
+ ```
169
+
170
+ `Builder(root)` defaults to the current directory. `configure`, `endpoint`,
171
+ `include`, and `event` return the Builder. `group` returns a group supporting
172
+ `endpoint`, nested `group`, and `include`; retain the Builder for `build()`.
173
+ The built Server snapshots definitions; later Builder changes do not affect it.
174
+ `new server/Server(directory)` is the XML equivalent. Routes, Endpoint, worker
175
+ classes, and token implementation classes are internal package details.
176
+
177
+ ## Configuration
178
+
179
+ ```xml
180
+ <deploy>
181
+ <http host="127.0.0.1" port="3000" bodyLimit="1048576" bodyTimeoutMs="30000"/>
182
+ <workers workers="2" maxQueue="64" requestTimeoutMs="30000"
183
+ startupTimeoutMs="30000" shutdownTimeoutMs="30000"/>
184
+ <events requestEvent="false" eventTimeoutMs="5000"/>
185
+ <jwt keyEnv="LANGO_JWT_KEY" issuer="shop" audience="shop-client" ttlSeconds="900"/>
186
+ </deploy>
187
+ ```
188
+
189
+ These are also the default values, apart from the required signing key and the
190
+ example issuer/audience (defaults: `lango-server` / `lango-client`). Builder uses
191
+ these attribute names directly in `configure`. Unknown options are errors.
192
+ `bodyLimit` is bytes; timeouts are milliseconds. Workers range from 1 to 128;
193
+ `maxQueue: 0` disables waiting. JWT lifetime is 1 to 86400 seconds.
194
+
195
+ For rotation, use `keysFile` instead of `keyEnv`, and select `activeKeyId`:
196
+
197
+ ```xml
198
+ <jwt keysFile="keys.json" activeKeyId="current" issuer="shop" audience="shop-client"/>
199
+ ```
200
+
201
+ The file is a JSON map of key IDs to secrets. Builder accepts `keys` and
202
+ `activeKeyId`, or a single `key` under the default `current` ID. Each secret must
203
+ contain at least 32 characters and should be cryptographically random. Only
204
+ HS256 is accepted; algorithm, key ID, issuer, audience, expiry, and server-owned
205
+ timestamps are checked. Keys are never generated or stored by the server.
206
+
207
+ ## Contexts and authorization
208
+
209
+ Handlers and events can declare `context request`, `response`, `token`, and `log`.
210
+ Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
211
+ Response supports `status(code)` and `header(name, value)`; the handler return
212
+ value supplies its JSON body. Transport/token headers remain server-owned.
213
+
214
+ Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
215
+ `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
216
+ `clientId`. Invalid, expired, or incorrectly signed tokens yield 401 even on an
217
+ anonymous endpoint; they never silently create a replacement identity.
218
+ Unauthorized requests do not receive a newly created token.
219
+
220
+ `context token` supports:
221
+
222
+ * `clientId`, `auth`, `expiresAt`: identity, comma-separated permissions, expiry.
223
+ * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
224
+ * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
225
+ protected. `get` returns a copy for structured values.
226
+
227
+ Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
228
+ other values require that exact permission. `admin` does not imply `login`.
229
+ The application authenticates credentials and grants permissions. These methods
230
+ do not authenticate anyone automatically.
231
+
232
+ Token updates are committed only after the handler and JSON serialization
233
+ succeed. Validation updates preserve the original token expiry. `clearAuth()`
234
+ updates the returned token; it does not invalidate previously issued copies.
235
+ Use application-owned storage and Validate to enforce logout/revocation across
236
+ old tokens. There is no built-in session database or UI replay protocol.
237
+
238
+ ## Events
239
+
240
+ Event modules and function names are strings, resolved during worker startup.
241
+ Promise results are supported, and events run under the request's contexts.
242
+
243
+ * **register(input)** runs for a tokenless request after assigning `clientId`,
244
+ before endpoint authorization. It can initialize custom token claims. Failure
245
+ prevents the handler and publishes no token. Return values are ignored; throw
246
+ or reject to fail registration. It is not an account-creation
247
+ guarantee: callers can omit tokens, so application side effects need their own
248
+ policy. No Register event is required.
249
+ * **validate(input)** receives null and runs after standard JWT verification
250
+ when the signed `validatedAt` is at least one second old. It receives a read-only
251
+ token. Only `true` continues; `false` produces 401. Exceptions, invalid return
252
+ types, mutation, or timeouts fail the request without running the handler;
253
+ operational failures are not reported as invalid credentials. Successful
254
+ validation updates the server-owned timestamp in the next successful reply.
255
+ Recent-token use does not advance it. If no event is configured, standard JWT
256
+ verification is sufficient. Revocation checks have a one-second freshness
257
+ allowance and depend on the application's storage consistency.
258
+ * **request(metadata)** is enabled only by `requestEvent: true`. It runs after
259
+ the handler completes and JSON serialization succeeds, before the reply is
260
+ sent. Metadata contains the original `input` JSON string, serialized `output`
261
+ JSON string, and HTTP `status`. It observes read-only metadata/token; response
262
+ mutation is unavailable. Event failure is logged and cannot change the
263
+ prepared result. The main process retains that result before invoking the
264
+ event, so even an event that blocks its worker can be terminated without losing
265
+ the successful response. Enabling this event exposes application input/output
266
+ to its configured handler; redact credentials and other sensitive fields there.
267
+
268
+ Each event has `eventTimeoutMs`. The request deadline covers queueing, Register,
269
+ Validate, and the handler; Request has its own event deadline after the result is
270
+ prepared. A hard timeout terminates the worker and the pool replaces it. Tasks
271
+ are never automatically retried: worker termination cannot roll back completed
272
+ external side effects. Client disconnect cancels queued/running work with the
273
+ same limitation. A full queue returns 503; request timeout returns 504; rejected
274
+ bodies return 400/408/413/415 as appropriate. Client error reporting and UI
275
+ Start/Ping events belong to other packages.
276
+
277
+ ## Development and verification
278
+
279
+ ```sh
280
+ npm ci
281
+ npm test
282
+ ```
283
+
284
+ All maintained implementation, tests, and tools are Lango. `dist` contains
285
+ generated JavaScript and is excluded from Git. `src/test` holds test code and
286
+ fixtures. Tests cover configuration, XML groups/includes, JWT/auth, real HTTP,
287
+ worker failures/deadlines, events, graceful shutdown, and an npm archive installed
288
+ into a separate consumer that runs the standalone server and shuts down on SIGTERM.
289
+ The package publishes only production sources/build output and documentation.
290
+
291
+ Run the repository example after building and installing its local dependency:
292
+
293
+ ```sh
294
+ npm run build
295
+ npm install --prefix examples/application --ignore-scripts
296
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
297
+ npm start
298
+ ```
299
+
300
+ ```sh
301
+ curl http://127.0.0.1:3000/demo/echo \
302
+ -H 'Content-Type: application/json' \
303
+ -d '{"message":"Hello"}'
304
+ ```
305
+
306
+ Prepare a publishable archive with `npm pack`. Publishing is a separate release
307
+ step; no package is published by the build or test commands.
308
+
309
+
310
+ ## SQL database configuration
311
+
312
+ Database configuration is optional. Configure one database per server through
313
+ `deploy.xml` or the equivalent `Builder.configure({ database: ... })` map:
314
+
315
+ ```xml
316
+ <database type="sqlite" file="data/application.sqlite"/>
317
+ ```
318
+
319
+ ```xml
320
+ <database type="postgresql" connectionEnv="APP_DATABASE_URL"/>
321
+ ```
322
+
323
+ SQLite paths resolve against the application directory; missing parent directories
324
+ are created. SQLite uses foreign keys, WAL, and a 5000 ms busy timeout by default.
325
+ WAL initialization happens before workers are started. `busyTimeoutMs` customizes
326
+ lock waiting; it is not a timeout for arbitrary SQLite query execution. `:memory:`
327
+ is allowed only with one worker, since each connection would otherwise get a
328
+ different database. Worker replacement loses in-memory data.
329
+
330
+ For PostgreSQL, `connectionEnv` names an environment variable containing a
331
+ `postgresql://` or `postgres://` connection URL, including any required SSL options.
332
+ Credentials are resolved at configuration time and are not logged. Defaults are
333
+ `queryTimeoutMs: 5000` (PostgreSQL `statement_timeout`) and
334
+ `connectTimeoutSeconds: 5`. These limits can be set as database attributes or map
335
+ fields. Database startup failures prevent the HTTP listener from opening.
336
+
337
+ ```lango
338
+ builder.configure({
339
+ database: {
340
+ type: "postgresql"
341
+ connectionEnv: "APP_DATABASE_URL"
342
+ queryTimeoutMs: 5000
343
+ }
344
+ })
345
+ ```
346
+
347
+ Each request worker owns one persistent connection. The server creates a fresh
348
+ DB scope before Register/Validate and keeps it available to the handler. Request
349
+ gets a separate clean scope after the handler result is serialized. Scopes cannot
350
+ be reused after completion. Physical connections are released on shutdown; worker
351
+ replacement discards the old connection and creates a new one. If DB configuration
352
+ is absent, SQL fails with `DatabaseNotConfigured` instead of borrowing an unrelated
353
+ default adapter.
354
+
355
+ Application code uses Lango SQL rather than a driver API:
356
+
357
+ ```lango
358
+ findCustomer(input)
359
+ context db
360
+ row = SQL
361
+ select id, name from customer where id = :id
362
+ row.id = input.id
363
+ row.execute()
364
+ if row.next()
365
+ return {
366
+ id: row.id
367
+ name: row.name
368
+ }
369
+ return null
370
+ ```
371
+
372
+ **Build all SQL application modules with lango-js 0.1.13 or newer.** SQL and
373
+ `start_trans()`, `commit_trans()`, `rollback_trans()`, `trans_state()` use the active
374
+ db context across separately compiled runtime copies. Promise callbacks that use
375
+ SQL should declare/capture db using the normal context capture rules.
376
+
377
+ Transactions are explicit. The server never implicitly commits a transaction.
378
+ An open transaction at successful scope completion is rolled back and reported as
379
+ an error; failure paths also roll back before connection reuse. Nested transactions
380
+ join the outer transaction and an inner rollback makes it rollback-only. PostgreSQL
381
+ failed-transaction state remains failed until rollback. A failing Request event
382
+ cannot roll back the already completed handler scope or change its prepared reply.
383
+ Previously committed writes are not undone by later serialization, token, network,
384
+ or event failures. Application-specific transactional guarantees remain explicit.
385
+
386
+ `:name` bindings are used for both engines. PostgreSQL positional binding conversion
387
+ preserves quotes, comments, dollar strings, and casts. Values are never interpolated
388
+ into SQL. Decimal parameters are exact text; use TEXT storage for exact decimals
389
+ in SQLite because its numeric affinity can convert values to floating point.
390
+ PostgreSQL numeric and int8 results remain strings by default. SQLite integers outside
391
+ the safe JavaScript integer range also return strings. Use SQL `RETURNING` for
392
+ portable generated-ID retrieval. SQL dialects and schema migrations are not translated.
393
+
394
+ PostgreSQL uses the standard pure JavaScript `pg` driver. A private helper thread
395
+ per request worker handles driver I/O while Lango SQL stays synchronous. This adds
396
+ no public API or worker configuration and requires no libpq headers, native compiler,
397
+ or pg-native installation. Closing or terminating the owner also releases its helper.
398
+
399
+ The database example uses SQL `RETURNING` and the same handler can run with either
400
+ engine. Its initial table creation is demonstration code; production migrations
401
+ should be managed by the application:
402
+
403
+ ```sh
404
+ npm run build
405
+ npm install --prefix examples/database --ignore-scripts
406
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
407
+ node dist/cli/server.mjs examples/database
408
+ ```
409
+
410
+ ```sh
411
+ curl http://127.0.0.1:3000/notes/save \
412
+ -H 'Content-Type: application/json' \
413
+ -d '{"message":"Stored through Lango SQL"}'
414
+ ```
415
+
416
+ `npm test` covers SQLite and a packed consumer with a SQL handler. To run the same
417
+ SQL/transaction suite plus PostgreSQL precision, timeout and connection-cleanup tests:
418
+
419
+ ```sh
420
+ LANGO_TEST_POSTGRES='postgresql://user:password@localhost/database' npm run test:postgres
421
+ ```
422
+
423
+ The tests create the `lango_server_items` table; use a dedicated test database. CI
424
+ runs SQLite first and PostgreSQL against an isolated PostgreSQL service.
425
+
426
+ ### Release order for this change
427
+
428
+ The server's development compiler dependency is now `^0.1.13`. Publish the prepared
429
+ lango-js 0.1.13 archive before running a fresh registry-based installation or CI,
430
+ then build/publish lango-server and rebuild application SQL modules. Local validation
431
+ uses the exact prepared compiler archive, without npm links; nothing is automatically
432
+ published by these commands.