@lango-project/lango-server 0.1.1 → 0.1.2
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 +86 -7
- package/dist/cli/endpoint.mjs +2 -6
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +1 -1
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/route_pattern.mjs +129 -0
- package/dist/cli/route_pattern.mjs.map +1 -0
- package/dist/cli/routes.mjs +25 -13
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/endpoint.mjs +2 -6
- package/dist/endpoint.mjs.map +1 -1
- package/dist/http_failure.mjs +45 -0
- package/dist/http_failure.mjs.map +1 -0
- package/dist/longpoll_options.mjs +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/response.mjs +8 -0
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +22 -0
- package/dist/route_info.mjs.map +1 -0
- package/dist/route_pattern.mjs +129 -0
- package/dist/route_pattern.mjs.map +1 -0
- package/dist/routes.mjs +25 -13
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +57 -20
- package/dist/runtime.mjs.map +1 -1
- package/dist/server_context.mjs +12 -2
- package/dist/server_context.mjs.map +1 -1
- package/dist/token.mjs +12 -0
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +16 -1
- package/dist/tokens.mjs.map +1 -1
- package/package.json +2 -2
- package/src/endpoint.lango +3 -4
- package/src/http_failure.lango +26 -0
- package/src/longpoll_options.lango +1 -1
- package/src/response.lango +6 -0
- package/src/route_info.lango +15 -0
- package/src/route_pattern.lango +86 -0
- package/src/routes.lango +20 -8
- package/src/runtime.lango +55 -17
- package/src/server_context.lango +11 -3
- package/src/token.lango +11 -0
- package/src/tokens.lango +11 -1
package/README.md
CHANGED
|
@@ -137,10 +137,13 @@ JWT authorization applies to POST handlers; static files are public.
|
|
|
137
137
|
launcher module. Absolute or relative file modules are also accepted for
|
|
138
138
|
application-local code; relative modules in XML resolve from the containing
|
|
139
139
|
package, and Builder modules resolve from its application root.
|
|
140
|
-
* Groups concatenate path prefixes. Paths are case-sensitive.
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
140
|
+
* Groups concatenate path prefixes. Paths are case-sensitive. Literal endpoints
|
|
141
|
+
beat parameterized endpoints, which beat trailing `/*` wildcards. Among matching
|
|
142
|
+
patterns in the same category, the first differing literal segment beats a
|
|
143
|
+
parameter; otherwise longer wildcard prefixes win. `/orders/*` matches
|
|
144
|
+
`/orders/save`, not `/orders`. Duplicate paths, equivalent parameter patterns
|
|
145
|
+
and unsupported wildcard forms are startup errors. The handler and middleware
|
|
146
|
+
see the original actual path in `context request`.
|
|
144
147
|
* Includes resolve the package's exported `./routes.xml`. Publish the XML file
|
|
145
148
|
and add it to the package's `exports` and `files`. Nested includes resolve
|
|
146
149
|
dependencies from the including package. Include prefixes concatenate; a
|
|
@@ -170,6 +173,51 @@ A feature package can expose its definitions as follows:
|
|
|
170
173
|
Its XML still names the handler module explicitly, for example
|
|
171
174
|
`<endpoint path="/list" module="@shop/catalog" handler="list"/>`.
|
|
172
175
|
|
|
176
|
+
### Path parameters
|
|
177
|
+
|
|
178
|
+
An endpoint can capture complete path segments with `{name}`:
|
|
179
|
+
|
|
180
|
+
```lango
|
|
181
|
+
builder.endpoint({
|
|
182
|
+
path: "/user/{userId}"
|
|
183
|
+
module: "@shop/users"
|
|
184
|
+
handler: "read"
|
|
185
|
+
auth: "login"
|
|
186
|
+
})
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
```xml
|
|
190
|
+
<endpoint path="/user/{userId}" module="@shop/users" handler="read"/>
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A POST to `/user/007` with body `{ "name": "Ada", "userId": "body-value" }`
|
|
194
|
+
passes `{ name: "Ada", userId: "007" }` to the handler. URL parameters overwrite
|
|
195
|
+
same-named body fields and are available before Register, middleware and handler
|
|
196
|
+
execution. The JSON body must still be an object. Validate retains its existing
|
|
197
|
+
input contract; parameters are not added to request headers or route metadata.
|
|
198
|
+
|
|
199
|
+
Values are strings, never inferred as numbers. Each parameter consumes exactly
|
|
200
|
+
one nonempty raw segment and is percent-decoded exactly once after choosing the
|
|
201
|
+
winning route. `%20` becomes a space, `+` remains a plus, `%2F` becomes a slash
|
|
202
|
+
inside that value, and `%252F` becomes `%2F`. Invalid percent encoding in a captured
|
|
203
|
+
value produces HTTP 400 InvalidPath before application code runs. request.path
|
|
204
|
+
and the middleware path argument retain the original encoded path.
|
|
205
|
+
|
|
206
|
+
Multiple parameters, group prefixes, XML groups and npm include prefixes are
|
|
207
|
+
supported. A trailing wildcard can follow parameters (`/user/{userId}/*`);
|
|
208
|
+
no wildcard value is added to input. Query strings and path parameters remain
|
|
209
|
+
separate concepts; this feature does not change the existing POST query policy.
|
|
210
|
+
|
|
211
|
+
Parameter names are case-sensitive ASCII identifiers beginning with a letter or
|
|
212
|
+
underscore. A name must occupy an entire segment, occur only once in a route,
|
|
213
|
+
and cannot be __proto__, constructor or prototype. Routes such as `/user/{id}`
|
|
214
|
+
and `/user/{name}` have the same structure and cannot both be registered.
|
|
215
|
+
Overlapping structures with different literal positions are resolved from left
|
|
216
|
+
to right, independently of registration order. For example, `/choose/static/{id}`
|
|
217
|
+
beats `/choose/{id}/fixed` when both match `/choose/static/fixed`.
|
|
218
|
+
|
|
219
|
+
Longpoll channel and fallback paths remain exact and do not accept parameters.
|
|
220
|
+
|
|
173
221
|
## Builder
|
|
174
222
|
|
|
175
223
|
```lango
|
|
@@ -257,6 +305,20 @@ registrations. An unresolved module, missing/non-function export, or route using
|
|
|
257
305
|
unregistered middleware fails startup. No function or captured closure is
|
|
258
306
|
transferred from the main thread, and no per-request import is needed.
|
|
259
307
|
|
|
308
|
+
Middleware registrations may also specify `validate: "checkRoutes"` (or the XML
|
|
309
|
+
attribute `validate="checkRoutes"`). This names another export in the same
|
|
310
|
+
module, called once in each worker before listening with an independent route
|
|
311
|
+
metadata snapshot. It may return a Promise. A missing/non-function validator or
|
|
312
|
+
a thrown/rejected error fails startup. Validators run without request contexts;
|
|
313
|
+
they check configuration rather than handling requests.
|
|
314
|
+
|
|
315
|
+
Inside request handlers and middleware, `context server` also provides
|
|
316
|
+
`routes()`. It returns a fresh array of `{ path, kind, auth, middleware }` records,
|
|
317
|
+
where kind is `endpoint` or `longpoll`. Module paths and handler names are not
|
|
318
|
+
exposed. Mutating a snapshot cannot change routing. Startup validators receive
|
|
319
|
+
the same metadata shape, allowing libraries to discover their configured URLs
|
|
320
|
+
without introducing library-specific behavior into the server.
|
|
321
|
+
|
|
260
322
|
The middleware signature is `wrap(handler, path, input)`: `handler` is the resolved
|
|
261
323
|
application function, `path` is the actual request path including mounted prefixes,
|
|
262
324
|
and `input` is the decoded request object. For example, the registered module can
|
|
@@ -320,8 +382,14 @@ timestamps are checked. Keys are never generated or stored by the server.
|
|
|
320
382
|
|
|
321
383
|
Handlers and events can declare `context request`, `response`, `token`, and `log`.
|
|
322
384
|
Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
|
|
323
|
-
Response supports `status(code)
|
|
324
|
-
value supplies its JSON body. Transport/token headers remain
|
|
385
|
+
Response supports `status(code)`, `header(name, value)` and `reject(status, code)`;
|
|
386
|
+
the handler return value supplies its JSON body. Transport/token headers remain
|
|
387
|
+
server-owned. `reject` throws a controlled HTTP failure (400–599) with a short
|
|
388
|
+
error code, for example `response.reject(400, "InvalidInput")`. Codes start with
|
|
389
|
+
an ASCII letter and contain at most 64 letters, digits or underscores. Configured
|
|
390
|
+
response headers are preserved. Rejections roll back open SQL transactions and
|
|
391
|
+
send `{ error: code }` without a token; committed side effects are not undone.
|
|
392
|
+
Unexpected exceptions still produce a generic 500.
|
|
325
393
|
|
|
326
394
|
Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
|
|
327
395
|
`X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
|
|
@@ -335,6 +403,8 @@ Unauthorized requests do not receive a newly created token.
|
|
|
335
403
|
* `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
|
|
336
404
|
* `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
|
|
337
405
|
protected. `get` returns a copy for structured values.
|
|
406
|
+
* `renew()`: requests renewal after successful serialization and SQL cleanup on
|
|
407
|
+
a reply with a status below 400. It does not immediately change `expiresAt`.
|
|
338
408
|
|
|
339
409
|
Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
|
|
340
410
|
other values require that exact permission. `admin` does not imply `login`.
|
|
@@ -347,6 +417,15 @@ updates the returned token; it does not invalidate previously issued copies.
|
|
|
347
417
|
Use application-owned storage and Validate to enforce logout/revocation across
|
|
348
418
|
old tokens. There is no built-in session database or UI replay protocol.
|
|
349
419
|
|
|
420
|
+
Renewal sets the new JWT's `iat` to the current second and `exp` to that value
|
|
421
|
+
plus `ttlSeconds`. Identity, permissions and custom claims are retained. The
|
|
422
|
+
timestamp of the last actual Validate result is preserved, so it may precede
|
|
423
|
+
the renewed token's issuance time. Renewal does not fake a fresh validation.
|
|
424
|
+
Read-only event tokens cannot request renewal. Expiration is checked again
|
|
425
|
+
before renewal and signing; an expired token cannot be revived. Failed or
|
|
426
|
+
rejected requests publish no renewal. Previously issued tokens remain valid
|
|
427
|
+
until their own expiry unless the application's Validate policy revokes them.
|
|
428
|
+
|
|
350
429
|
## Events
|
|
351
430
|
|
|
352
431
|
Event modules and function names are strings, resolved during worker startup.
|
|
@@ -572,7 +651,7 @@ No sticky sessions are required.
|
|
|
572
651
|
The Builder equivalent is `builder.longpoll(options)` or
|
|
573
652
|
`group.longpoll(options)`. No module or handler is needed. Group and include
|
|
574
653
|
prefixes apply to both `path` and `fallback`; auth is inherited and defaults to
|
|
575
|
-
`login`. Paths must be exact absolute URL paths, without wildcards or query
|
|
654
|
+
`login`. Paths must be exact absolute URL paths, without parameters, wildcards or query
|
|
576
655
|
strings. Duplicate paths conflict with endpoints as well as other longpoll routes.
|
|
577
656
|
The fallback is returned to the client; the server never calls it automatically.
|
|
578
657
|
|
package/dist/cli/endpoint.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routePattern } from "./route_pattern.mjs";
|
|
1
2
|
import { middlewareName } from "./middleware.mjs";
|
|
2
3
|
import {
|
|
3
4
|
isNumber as __isNumber,
|
|
@@ -20,12 +21,7 @@ export class Endpoint {
|
|
|
20
21
|
constructor(spec) {
|
|
21
22
|
__requireArity(arguments.length, [0], "constructor");
|
|
22
23
|
spec = __boundary(spec);
|
|
23
|
-
|
|
24
|
-
throw "Endpoint requires an absolute URL path";
|
|
25
|
-
}
|
|
26
|
-
if (__requireBoolean(__requireBoolean(__normalize(spec.path.includes("*"))) && __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(spec.path.endsWith("/*")))) || __requireBoolean(__normalize(spec.path.indexOf("*")) !== __normalize(spec.path.lastIndexOf("*")))))) {
|
|
27
|
-
throw "Only trailing /* wildcards are supported";
|
|
28
|
-
}
|
|
24
|
+
routePattern(__normalize(spec.path));
|
|
29
25
|
for (const key of ["module", "handler"]) {
|
|
30
26
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec[key])))) || __requireBoolean(__normalize(spec[key]) === ""))) {
|
|
31
27
|
throw `Endpoint requires ${key}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n middleware\n\nEndpoint(spec)\n
|
|
1
|
+
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./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 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 @auth = spec.auth\n if @auth == null\n @auth = \"login\"\n if !is_string(@auth) or @auth == \"\" or @auth.includes(\",\")\n throw \"Endpoint auth must name one permission\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -51,7 +51,7 @@ export function longpollOptions(spec) {
|
|
|
51
51
|
function validPath(value) {
|
|
52
52
|
__requireArity(arguments.length, [0], "validPath");
|
|
53
53
|
value = __boundary(value);
|
|
54
|
-
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(value))) || __requireBoolean(!__requireBoolean(__normalize(value.startsWith("/"))))) || __requireBoolean(__normalize(value.includes("*")))) || __requireBoolean(__normalize(value.includes("?")))) || __requireBoolean(__normalize(value.includes("#")))) || __requireBoolean(__normalize(value.includes("\\")))) || __requireBoolean(__normalize(value.includes("//"))))) {
|
|
54
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(value))) || __requireBoolean(!__requireBoolean(__normalize(value.startsWith("/"))))) || __requireBoolean(__normalize(value.includes("*")))) || __requireBoolean(__normalize(value.includes("{")))) || __requireBoolean(__normalize(value.includes("}")))) || __requireBoolean(__normalize(value.includes("?")))) || __requireBoolean(__normalize(value.includes("#")))) || __requireBoolean(__normalize(value.includes("\\")))) || __requireBoolean(__normalize(value.includes("//"))))) {
|
|
55
55
|
throw "Longpoll requires an exact absolute URL path";
|
|
56
56
|
}
|
|
57
57
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import 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: \"login\"\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 if result.auth == null\n result.auth = \"login\"\n validPath(result.path)\n if !is_string(result.auth) or result.auth == \"\" or result.auth.includes(\",\")\n throw \"Longpoll auth must name one permission\"\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(\"//\")\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":";;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import 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: \"login\"\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 if result.auth == null\n result.auth = \"login\"\n validPath(result.path)\n if !is_string(result.auth) or result.auth == \"\" or result.auth.includes(\",\")\n throw \"Longpoll auth must name one permission\"\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":";;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hostGlobal as __hostGlobal,
|
|
3
|
+
isNumber as __isNumber,
|
|
4
|
+
isString as __isString,
|
|
5
|
+
isBool as __isBool,
|
|
6
|
+
isObject as __isObject,
|
|
7
|
+
isArray as __isArray,
|
|
8
|
+
entries as __entries,
|
|
9
|
+
range as __range,
|
|
10
|
+
requireBoolean as __requireBoolean,
|
|
11
|
+
normalize as __normalize,
|
|
12
|
+
finite as __finite,
|
|
13
|
+
boundary as __boundary,
|
|
14
|
+
requireArity as __requireArity,
|
|
15
|
+
} from "./.lango/runtime.mjs";
|
|
16
|
+
|
|
17
|
+
export function routePattern(path) {
|
|
18
|
+
__requireArity(arguments.length, [0], "routePattern");
|
|
19
|
+
path = __boundary(path);
|
|
20
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(path))) || __requireBoolean(!__requireBoolean(__normalize(path.startsWith("/"))))) || __requireBoolean(__normalize(path.includes("?")))) || __requireBoolean(__normalize(path.includes("#")))) || __requireBoolean(__normalize(path.includes("\\")))) || __requireBoolean(__normalize(path.includes("//"))))) {
|
|
21
|
+
throw "Endpoint requires an absolute URL path";
|
|
22
|
+
}
|
|
23
|
+
if (__requireBoolean(__requireBoolean(__normalize(path.includes("*"))) && __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(path.endsWith("/*")))) || __requireBoolean(__normalize(path.indexOf("*")) !== __normalize(path.lastIndexOf("*")))))) {
|
|
24
|
+
throw "Only trailing /* wildcards are supported";
|
|
25
|
+
}
|
|
26
|
+
let segments = __normalize(path.split("/"));
|
|
27
|
+
segments = __normalize(segments.slice(1));
|
|
28
|
+
let wildcard = __normalize(path.endsWith("/*"));
|
|
29
|
+
if (__requireBoolean(wildcard)) {
|
|
30
|
+
__normalize(segments.pop());
|
|
31
|
+
}
|
|
32
|
+
let names = [];
|
|
33
|
+
let shape = [];
|
|
34
|
+
let identifier = new (__hostGlobal(["RegExp"]))("^[A-Za-z_][A-Za-z0-9_]*$");
|
|
35
|
+
let reserved = ["__proto__", "constructor", "prototype"];
|
|
36
|
+
for (const segment of segments) {
|
|
37
|
+
if (__requireBoolean(__requireBoolean(__normalize(segment.includes("{"))) || __requireBoolean(__normalize(segment.includes("}"))))) {
|
|
38
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(segment.startsWith("{")))) || __requireBoolean(!__requireBoolean(__normalize(segment.endsWith("}")))))) {
|
|
39
|
+
throw "Path parameters must occupy an entire segment";
|
|
40
|
+
}
|
|
41
|
+
let name = __normalize(segment.slice(1, __finite(-1)));
|
|
42
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(identifier.test(name)))) || __requireBoolean(__normalize(reserved.includes(name))))) {
|
|
43
|
+
throw `Invalid path parameter name: ${name}`;
|
|
44
|
+
}
|
|
45
|
+
if (__requireBoolean(__normalize(names.includes(name)))) {
|
|
46
|
+
throw `Duplicate path parameter: ${name}`;
|
|
47
|
+
}
|
|
48
|
+
names.push(name);
|
|
49
|
+
shape.push("{}");
|
|
50
|
+
} else {
|
|
51
|
+
shape.push(segment);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (__requireBoolean(wildcard)) {
|
|
55
|
+
shape.push("*");
|
|
56
|
+
}
|
|
57
|
+
let key = __normalize(shape.join("/"));
|
|
58
|
+
key = `/${key}`;
|
|
59
|
+
return { segments: segments, wildcard: wildcard, key: key };
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function matchPath(pattern, path) {
|
|
64
|
+
__requireArity(arguments.length, [0, 1], "matchPath");
|
|
65
|
+
pattern = __boundary(pattern);
|
|
66
|
+
path = __boundary(path);
|
|
67
|
+
let parts = __normalize(path.split("/"));
|
|
68
|
+
if (__requireBoolean(__normalize(parts[0]) !== "")) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
parts = __normalize(parts.slice(1));
|
|
72
|
+
let count = pattern.segments.length;
|
|
73
|
+
if (__requireBoolean(__normalize(pattern.wildcard))) {
|
|
74
|
+
if (__requireBoolean(__normalize(parts.length) <= count)) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
if (__requireBoolean(__normalize(parts.length) !== count)) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
let parameters = { };
|
|
83
|
+
for (const [index, segment] of __entries(__normalize(pattern.segments))) {
|
|
84
|
+
let value = __normalize(parts[index]);
|
|
85
|
+
if (__requireBoolean(__normalize(segment.startsWith("{")))) {
|
|
86
|
+
if (__requireBoolean(value === "")) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
let name = __normalize(segment.slice(1, __finite(-1)));
|
|
90
|
+
parameters[name] = value;
|
|
91
|
+
} else {
|
|
92
|
+
if (__requireBoolean(segment !== value)) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return parameters;
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function moreSpecific(candidate, current) {
|
|
102
|
+
__requireArity(arguments.length, [0, 1], "moreSpecific");
|
|
103
|
+
candidate = __boundary(candidate);
|
|
104
|
+
current = __boundary(current);
|
|
105
|
+
if (__requireBoolean(current === null)) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
if (__requireBoolean(__normalize(candidate.wildcard) !== __normalize(current.wildcard))) {
|
|
109
|
+
return !__requireBoolean(__normalize(candidate.wildcard));
|
|
110
|
+
}
|
|
111
|
+
let first = __normalize(candidate.segments);
|
|
112
|
+
let second = __normalize(current.segments);
|
|
113
|
+
let count = __normalize(first.length);
|
|
114
|
+
if (__requireBoolean(__normalize(second.length) < count)) {
|
|
115
|
+
count = __normalize(second.length);
|
|
116
|
+
}
|
|
117
|
+
for (const index of __range(0, count)) {
|
|
118
|
+
let segment = __normalize(first[index]);
|
|
119
|
+
let alternative = __normalize(second[index]);
|
|
120
|
+
let literal = !__requireBoolean(__normalize(segment.startsWith("{")));
|
|
121
|
+
let other = !__requireBoolean(__normalize(alternative.startsWith("{")));
|
|
122
|
+
if (__requireBoolean(literal !== other)) {
|
|
123
|
+
return literal;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return __normalize(first.length) > __normalize(second.length);
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=route_pattern.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route_pattern.mjs","sources":["route_pattern.lango"],"sourcesContent":["import js global RegExp\n\nexport routePattern(path)\nexport matchPath(pattern, path)\nexport moreSpecific(candidate, current)\n\nroutePattern(path)\n if !is_string(path) or !path.startsWith(\"/\") or path.includes(\"?\") or path.includes(\"#\") or path.includes(\"\\\\\") or path.includes(\"//\")\n throw \"Endpoint requires an absolute URL path\"\n if path.includes(\"*\") and (!path.endsWith(\"/*\") or path.indexOf(\"*\") != path.lastIndexOf(\"*\"))\n throw \"Only trailing /* wildcards are supported\"\n segments = path.split(\"/\")\n segments = segments.slice(1)\n wildcard = path.endsWith(\"/*\")\n if wildcard\n segments.pop()\n names = []\n shape = []\n identifier = new RegExp(\"^[A-Za-z_][A-Za-z0-9_]*$\")\n reserved = [\"__proto__\", \"constructor\", \"prototype\"]\n for segments as segment\n if segment.includes(\"{\") or segment.includes(\"}\")\n if !segment.startsWith(\"{\") or !segment.endsWith(\"}\")\n throw \"Path parameters must occupy an entire segment\"\n name = segment.slice(1, -1)\n if !identifier.test(name) or reserved.includes(name)\n throw \"Invalid path parameter name: ${name}\"\n if names.includes(name)\n throw \"Duplicate path parameter: ${name}\"\n names.add(name)\n shape.add(\"{}\")\n else\n shape.add(segment)\n if wildcard\n shape.add(\"*\")\n key = shape.join(\"/\")\n key = \"/${key}\"\n return {\n segments: segments\n wildcard: wildcard\n key: key\n }\n\nmatchPath(pattern, path)\n parts = path.split(\"/\")\n if parts[0] != \"\"\n return null\n parts = parts.slice(1)\n count = pattern.segments.length\n if pattern.wildcard\n if parts.length <= count\n return null\n else\n if parts.length != count\n return null\n parameters = {}\n for pattern.segments as index: segment\n value = parts[index]\n if segment.startsWith(\"{\")\n if value == \"\"\n return null\n name = segment.slice(1, -1)\n parameters[name] = value\n else\n if segment != value\n return null\n return parameters\n\nmoreSpecific(candidate, current)\n if current == null\n return true\n if candidate.wildcard != current.wildcard\n return !candidate.wildcard\n first = candidate.segments\n second = current.segments\n count = first.length\n if second.length < count\n count = second.length\n for range(count) as index\n segment = first[index]\n alternative = second[index]\n literal = !segment.startsWith(\"{\")\n other = !alternative.startsWith(\"{\")\n if literal != other\n return literal\n return first.length > second.length\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/cli/routes.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routePattern } from "./route_pattern.mjs";
|
|
1
2
|
import { contains } from "./options.mjs";
|
|
2
3
|
import { attributes } from "./options.mjs";
|
|
3
4
|
import { middlewareName } from "./middleware.mjs";
|
|
@@ -43,13 +44,25 @@ export class Routes {
|
|
|
43
44
|
__requireArity(arguments.length, [0], "endpoint");
|
|
44
45
|
spec = __boundary(spec);
|
|
45
46
|
let item = new Endpoint(spec);
|
|
47
|
+
this.#checkPath(__normalize(item.path));
|
|
48
|
+
__add(this.#items, { path: __normalize(item.path), module: resolveModule(__normalize(item.module), __normalize(this.#root)), handler: __normalize(item.handler), auth: __normalize(item.auth), middleware: __normalize(item.middleware) });
|
|
49
|
+
return this;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
#checkPath(path) {
|
|
53
|
+
__requireArity(arguments.length, [0], "checkPath");
|
|
54
|
+
path = __boundary(path);
|
|
55
|
+
let pattern = routePattern(path);
|
|
46
56
|
for (const other of __normalize(this.#items)) {
|
|
47
|
-
if (__requireBoolean(__normalize(other.path) ===
|
|
48
|
-
throw `Duplicate endpoint: ${
|
|
57
|
+
if (__requireBoolean(__normalize(other.path) === path)) {
|
|
58
|
+
throw `Duplicate endpoint: ${path}`;
|
|
59
|
+
}
|
|
60
|
+
let existing = routePattern(__normalize(other.path));
|
|
61
|
+
if (__requireBoolean(__normalize(existing.key) === __normalize(pattern.key))) {
|
|
62
|
+
throw `Conflicting endpoint pattern: ${path}`;
|
|
49
63
|
}
|
|
50
64
|
}
|
|
51
|
-
|
|
52
|
-
return this;
|
|
65
|
+
return null;
|
|
53
66
|
return null;
|
|
54
67
|
}
|
|
55
68
|
addMiddleware(name, spec) {
|
|
@@ -64,14 +77,17 @@ export class Routes {
|
|
|
64
77
|
throw "Middleware requires a module and exported handler";
|
|
65
78
|
}
|
|
66
79
|
for (const [key, value] of __entries(spec)) {
|
|
67
|
-
if (__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler"))) {
|
|
80
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(key !== "module") && __requireBoolean(key !== "handler")) && __requireBoolean(key !== "validate"))) {
|
|
68
81
|
throw `Unknown middleware option: ${key}`;
|
|
69
82
|
}
|
|
70
83
|
}
|
|
71
84
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.handler)))) || __requireBoolean(__normalize(spec.handler) === ""))) {
|
|
72
85
|
throw "Middleware handler is required";
|
|
73
86
|
}
|
|
74
|
-
|
|
87
|
+
if (__requireBoolean(__requireBoolean(__normalize(spec.validate) !== null) && __requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.validate)))) || __requireBoolean(__normalize(spec.validate) === "")))) {
|
|
88
|
+
throw "Middleware validate must name an exported function";
|
|
89
|
+
}
|
|
90
|
+
this.#middlewares[name] = { module: resolveModule(__normalize(spec.module), __normalize(this.#root)), handler: __normalize(spec.handler), validate: __normalize(spec.validate) };
|
|
75
91
|
return this;
|
|
76
92
|
return null;
|
|
77
93
|
}
|
|
@@ -83,11 +99,7 @@ export class Routes {
|
|
|
83
99
|
__requireArity(arguments.length, [0], "longpoll");
|
|
84
100
|
spec = __boundary(spec);
|
|
85
101
|
let item = longpollOptions(spec);
|
|
86
|
-
|
|
87
|
-
if (__requireBoolean(__normalize(other.path) === __normalize(item.path))) {
|
|
88
|
-
throw `Duplicate endpoint: ${__normalize(item.path)}`;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
102
|
+
this.#checkPath(__normalize(item.path));
|
|
91
103
|
__add(this.#items, item);
|
|
92
104
|
return this;
|
|
93
105
|
return null;
|
|
@@ -229,12 +241,12 @@ export class Routes {
|
|
|
229
241
|
leaf(tag);
|
|
230
242
|
this.#includeAt(spec, directory, prefix, stack, auth);
|
|
231
243
|
} else if (__normalize(tag.tag()) === "middleware") {
|
|
232
|
-
attributes(tag, ["name", "module", "handler"]);
|
|
244
|
+
attributes(tag, ["name", "module", "handler", "validate"]);
|
|
233
245
|
leaf(tag);
|
|
234
246
|
if (__requireBoolean(!__requireBoolean(allowEvents))) {
|
|
235
247
|
throw "Middleware declarations are only allowed in the application's root routes.xml";
|
|
236
248
|
}
|
|
237
|
-
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler) });
|
|
249
|
+
this.addMiddleware(__normalize(spec.name), { module: resolveModule(__normalize(spec.module), directory), handler: __normalize(spec.handler), validate: __normalize(spec.validate) });
|
|
238
250
|
} else if (__normalize(tag.tag()) === "event") {
|
|
239
251
|
attributes(tag, ["name", "module", "handler"]);
|
|
240
252
|
leaf(tag);
|
package/dist/cli/routes.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n
|
|
1
|
+
{"version":3,"file":"routes.mjs","sources":["routes.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./options\"\n contains(items, value)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport \"./options\"\n attributes(tag, allowed)\nimport js global Object\nimport \"./middleware\"\n middlewareName(name)\nimport \"./endpoint\"\n class Endpoint\n\nimport \"./longpoll_options\"\n longpollOptions(spec)\n\nexport class Routes(root)\n methods\n endpoint(spec)\n addMiddleware(name, spec)\n middlewares()\n longpoll(spec)\n include(spec, auth = null)\n xml(file)\n definitions()\n events()\n event(spec)\n\nRoutes(root)\n @root = path/resolve(root)\n @items = []\n @events = {}\n @middlewares = Object/create(null)\n\nRoutes:endpoint(spec)\n item = new Endpoint(spec)\n checkPath(item.path)\n @items.add({\n path: item.path\n module: resolveModule(item.module, @root)\n handler: item.handler\n auth: item.auth\n middleware: item.middleware\n })\n return @this\n\nRoutes:checkPath(path)\n pattern = routePattern(path)\n for @items as other\n if other.path == path\n throw \"Duplicate endpoint: ${path}\"\n existing = routePattern(other.path)\n if existing.key == pattern.key\n throw \"Conflicting endpoint pattern: ${path}\"\n return null\n\nRoutes:addMiddleware(name, spec)\n middlewareName(name)\n if Object/hasOwn(@middlewares, name)\n throw \"Duplicate middleware: ${name}\"\n if !is_object(spec) or is_array(spec)\n throw \"Middleware requires a module and exported handler\"\n for spec as key: value\n if key != \"module\" and key != \"handler\" and key != \"validate\"\n throw \"Unknown middleware option: ${key}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Middleware handler is required\"\n if spec.validate != null and (!is_string(spec.validate) or spec.validate == \"\")\n throw \"Middleware validate must name an exported function\"\n @middlewares[name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n validate: spec.validate\n }\n return @this\n\nRoutes:middlewares()\n return from_json(to_json(@middlewares))\n\nRoutes:longpoll(spec)\n item = longpollOptions(spec)\n checkPath(item.path)\n @items.add(item)\n return @this\n\nRoutes:event(spec)\n if !contains([\"register\", \"validate\", \"request\"], spec.name)\n throw \"Unknown event: ${spec.name}\"\n if spec.name in @events\n throw \"Duplicate event: ${spec.name}\"\n if !is_string(spec.handler) or spec.handler == \"\"\n throw \"Event handler is required\"\n @events[spec.name] = {\n module: resolveModule(spec.module, @root)\n handler: spec.handler\n }\n return @this\n\nRoutes:include(spec, auth = null)\n includeAt(spec, @root, \"\", [], auth)\n return @this\n\nRoutes:xml(file)\n readXml(path/resolve(file), \"\", @root, [], true)\n return @this\n\nRoutes:definitions()\n return from_json(to_json(@items))\n\nRoutes:events()\n return from_json(to_json(@events))\n\nresolveModule(name, directory)\n if !is_string(name) or name == \"\" or name.startsWith(\"node:\")\n throw \"Application module is required\"\n resolver = modules/createRequire(path/join(directory, \"package.json\"))\n resolved = resolver.resolve(name)\n if !path/isAbsolute(resolved)\n throw \"Application module must resolve to a file: ${name}\"\n return resolved\n\njoinPath(prefix, suffix)\n if !is_string(suffix) or !suffix.startsWith(\"/\")\n throw \"Route path must begin with /\"\n if prefix == \"\" or prefix == \"/\"\n return suffix\n if suffix == \"/\"\n return \"${prefix}/\"\n return \"${prefix}${suffix}\"\n\nRoutes:includeAt(spec, directory, prefix, stack, inheritedAuth = null)\n if !is_string(spec.module) or spec.module == \"\" or spec.module.startsWith(\".\") or spec.module.startsWith(\"/\") or spec.module.startsWith(\"node:\")\n throw \"Include requires an npm package name\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n if !is_string(mount)\n throw \"Include path must be a string\"\n if mount.includes(\"*\") or mount.includes(\"//\") or mount.includes(\"?\") or mount.includes(\"#\") or mount.includes(\"\\\\\")\n throw \"Invalid include prefix\"\n if mount.endsWith(\"/\") and mount != \"/\"\n mount = mount.slice(0, -1)\n combined = joinPath(prefix, mount)\n if combined == \"/\"\n combined = \"\"\n file = resolveModule(\"${spec.module}/routes.xml\", directory)\n readXml(file, combined, path/dirname(file), stack, false, inheritedAuth)\n return null\n\nRoutes:readXml(file, prefix, directory, stack, allowEvents, inheritedAuth = null)\n real = fs/realpathSync(file)\n if stack.includes(real)\n throw \"Route include cycle: ${real}\"\n root = xml2obj(fs/readFileSync(real, \"utf8\"))\n if root.tag() != \"routes\"\n throw \"Expected routes root: ${real}\"\n attributes(root, [])\n nextStack = stack.slice()\n nextStack.add(real)\n collect(root, prefix, null, inheritedAuth, directory, nextStack, allowEvents)\n return null\n\nRoutes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack, allowEvents)\n if parent.innerText().trim() != \"\"\n throw \"Route XML cannot contain text\"\n for parent.children() as tag\n spec = tag.attributes()\n mod = spec.module\n auth = spec.auth\n if mod == null\n mod = inheritedModule\n if auth == null\n auth = inheritedAuth\n switch tag.tag()\n case \"endpoint\"\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n })\n case \"longpoll\"\n attributes(tag, [\"path\", \"auth\", \"waitTimeoutMs\", \"retentionMs\", \"maxMessages\", \"fallback\"])\n leaf(tag)\n spec.path = joinPath(prefix, spec.path)\n spec.auth = auth\n if spec.fallback != null\n spec.fallback = joinPath(prefix, spec.fallback)\n longpoll(spec)\n case \"group\"\n attributes(tag, [\"path\", \"module\", \"auth\"])\n collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false)\n case \"include\"\n attributes(tag, [\"module\", \"path\"])\n leaf(tag)\n includeAt(spec, directory, prefix, stack, auth)\n case \"middleware\"\n attributes(tag, [\"name\", \"module\", \"handler\", \"validate\"])\n leaf(tag)\n if !allowEvents\n throw \"Middleware declarations are only allowed in the application's root routes.xml\"\n addMiddleware(spec.name, {\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n validate: spec.validate\n })\n case \"event\"\n attributes(tag, [\"name\", \"module\", \"handler\"])\n leaf(tag)\n if !allowEvents\n throw \"Events are only allowed in the application's root routes.xml\"\n event({\n name: spec.name\n module: resolveModule(spec.module, directory)\n handler: spec.handler\n })\n else\n attributes(tag, [\"path\", \"module\", \"handler\", \"auth\"])\n leaf(tag)\n endpoint({\n path: joinPath(prefix, spec.path)\n module: resolveModule(mod, directory)\n handler: spec.handler\n auth: auth\n middleware: tag.tag()\n })\n return null\n\nleaf(tag)\n if tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Expected an empty ${tag.tag()} element\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;"}
|
package/dist/endpoint.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { routePattern } from "./route_pattern.mjs";
|
|
1
2
|
import { middlewareName } from "./middleware.mjs";
|
|
2
3
|
import {
|
|
3
4
|
isNumber as __isNumber,
|
|
@@ -20,12 +21,7 @@ export class Endpoint {
|
|
|
20
21
|
constructor(spec) {
|
|
21
22
|
__requireArity(arguments.length, [0], "constructor");
|
|
22
23
|
spec = __boundary(spec);
|
|
23
|
-
|
|
24
|
-
throw "Endpoint requires an absolute URL path";
|
|
25
|
-
}
|
|
26
|
-
if (__requireBoolean(__requireBoolean(__normalize(spec.path.includes("*"))) && __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(spec.path.endsWith("/*")))) || __requireBoolean(__normalize(spec.path.indexOf("*")) !== __normalize(spec.path.lastIndexOf("*")))))) {
|
|
27
|
-
throw "Only trailing /* wildcards are supported";
|
|
28
|
-
}
|
|
24
|
+
routePattern(__normalize(spec.path));
|
|
29
25
|
for (const key of ["module", "handler"]) {
|
|
30
26
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec[key])))) || __requireBoolean(__normalize(spec[key]) === ""))) {
|
|
31
27
|
throw `Endpoint requires ${key}`;
|
package/dist/endpoint.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n middleware\n\nEndpoint(spec)\n
|
|
1
|
+
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./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 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 @auth = spec.auth\n if @auth == null\n @auth = \"login\"\n if !is_string(@auth) or @auth == \"\" or @auth.includes(\",\")\n throw \"Endpoint auth must name one permission\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hostGlobal as __hostGlobal,
|
|
3
|
+
fromJson as __fromJson,
|
|
4
|
+
toJson as __toJson,
|
|
5
|
+
isNumber as __isNumber,
|
|
6
|
+
isString as __isString,
|
|
7
|
+
isBool as __isBool,
|
|
8
|
+
isObject as __isObject,
|
|
9
|
+
isArray as __isArray,
|
|
10
|
+
requireBoolean as __requireBoolean,
|
|
11
|
+
normalize as __normalize,
|
|
12
|
+
finite as __finite,
|
|
13
|
+
boundary as __boundary,
|
|
14
|
+
requireArity as __requireArity,
|
|
15
|
+
} from "./.lango/runtime.mjs";
|
|
16
|
+
|
|
17
|
+
export class HttpFailure {
|
|
18
|
+
#status;
|
|
19
|
+
#code;
|
|
20
|
+
#headers;
|
|
21
|
+
constructor(status, code, headers) {
|
|
22
|
+
__requireArity(arguments.length, [0, 1, 2], "constructor");
|
|
23
|
+
status = __boundary(status);
|
|
24
|
+
code = __boundary(code);
|
|
25
|
+
headers = __boundary(headers);
|
|
26
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isNumber(status))) || __requireBoolean(__finite(status % 1) !== 0)) || __requireBoolean(status < 400)) || __requireBoolean(status > 599))) {
|
|
27
|
+
throw "Rejected response requires an error status";
|
|
28
|
+
}
|
|
29
|
+
let pattern = new (__hostGlobal(["RegExp"]))("^[A-Za-z][A-Za-z0-9_]{0,63}$");
|
|
30
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(code))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(code)))))) {
|
|
31
|
+
throw "Rejected response requires an error code";
|
|
32
|
+
}
|
|
33
|
+
this.#status = status;
|
|
34
|
+
this.#code = code;
|
|
35
|
+
this.#headers = __fromJson(__toJson(headers));
|
|
36
|
+
if (__requireBoolean(status === 401)) {
|
|
37
|
+
this.#headers["www-authenticate"] = "Bearer";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
result() {
|
|
41
|
+
return { status: __normalize(this.#status), headers: __fromJson(__toJson(__normalize(this.#headers))), body: __toJson({ error: __normalize(this.#code) }) };
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=http_failure.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http_failure.mjs","sources":["http_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class HttpFailure(status, code, headers)\n methods\n result()\n\nHttpFailure(status, code, headers)\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 @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 return {\n status: @status\n headers: from_json(to_json(@headers))\n body: to_json({\n error: @code\n })\n }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -51,7 +51,7 @@ export function longpollOptions(spec) {
|
|
|
51
51
|
function validPath(value) {
|
|
52
52
|
__requireArity(arguments.length, [0], "validPath");
|
|
53
53
|
value = __boundary(value);
|
|
54
|
-
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(value))) || __requireBoolean(!__requireBoolean(__normalize(value.startsWith("/"))))) || __requireBoolean(__normalize(value.includes("*")))) || __requireBoolean(__normalize(value.includes("?")))) || __requireBoolean(__normalize(value.includes("#")))) || __requireBoolean(__normalize(value.includes("\\")))) || __requireBoolean(__normalize(value.includes("//"))))) {
|
|
54
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(value))) || __requireBoolean(!__requireBoolean(__normalize(value.startsWith("/"))))) || __requireBoolean(__normalize(value.includes("*")))) || __requireBoolean(__normalize(value.includes("{")))) || __requireBoolean(__normalize(value.includes("}")))) || __requireBoolean(__normalize(value.includes("?")))) || __requireBoolean(__normalize(value.includes("#")))) || __requireBoolean(__normalize(value.includes("\\")))) || __requireBoolean(__normalize(value.includes("//"))))) {
|
|
55
55
|
throw "Longpoll requires an exact absolute URL path";
|
|
56
56
|
}
|
|
57
57
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import 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: \"login\"\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 if result.auth == null\n result.auth = \"login\"\n validPath(result.path)\n if !is_string(result.auth) or result.auth == \"\" or result.auth.includes(\",\")\n throw \"Longpoll auth must name one permission\"\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(\"//\")\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":";;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"longpoll_options.mjs","sources":["longpoll_options.lango"],"sourcesContent":["import 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: \"login\"\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 if result.auth == null\n result.auth = \"login\"\n validPath(result.path)\n if !is_string(result.auth) or result.auth == \"\" or result.auth.includes(\",\")\n throw \"Longpoll auth must name one permission\"\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":";;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/response.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { contains } from "./options.mjs";
|
|
2
|
+
import { HttpFailure } from "./http_failure.mjs";
|
|
2
3
|
import * as http from "node:http";
|
|
3
4
|
import {
|
|
4
5
|
fromJson as __fromJson,
|
|
@@ -58,5 +59,12 @@ export class Response {
|
|
|
58
59
|
return { status: __normalize(this.#status), headers: __fromJson(__toJson(__normalize(this.#headers))), body: body };
|
|
59
60
|
return null;
|
|
60
61
|
}
|
|
62
|
+
reject(status, code) {
|
|
63
|
+
__requireArity(arguments.length, [0, 1], "reject");
|
|
64
|
+
status = __boundary(status);
|
|
65
|
+
code = __boundary(code);
|
|
66
|
+
throw new HttpFailure(status, code, __normalize(this.#headers));
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
61
69
|
}
|
|
62
70
|
//# sourceMappingURL=response.mjs.map
|
package/dist/response.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\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":"
|
|
1
|
+
{"version":3,"file":"response.mjs","sources":["response.lango"],"sourcesContent":["import js \"node:http\" as http\n\nimport \"./options\"\n contains(items, value)\nimport \"./http_failure\"\n class HttpFailure\nexport class Response()\n methods\n status(code)\n header(name, value)\n result(body)\n reject(status, code)\n\nResponse()\n @status = 200\n @headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n\nResponse:status(code)\n if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304\n throw \"Response requires a JSON-compatible HTTP status\"\n @status = code\n return @this\n\nResponse:header(name, value)\n if !is_string(name) or !is_string(value)\n throw \"Header name and value must be strings\"\n name = name.toLowerCase()\n if contains([\"x-lango-token\", \"content-length\", \"transfer-encoding\", \"connection\", \"content-type\"], name)\n throw \"Reserved response header: ${name}\"\n if name.includes(\"\\r\") or name.includes(\"\\n\") or value.includes(\"\\r\") or value.includes(\"\\n\")\n throw \"Invalid response header\"\n http/validateHeaderName(name)\n http/validateHeaderValue(name, value)\n @headers[name] = value\n return @this\n\nResponse:result(body)\n return {\n status: @status\n headers: from_json(to_json(@headers))\n body: body\n }\n\nResponse:reject(status, code)\n throw new HttpFailure(status, code, @headers)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|