@lango-project/lango-server 0.1.0 → 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.
Files changed (80) hide show
  1. package/README.md +368 -10
  2. package/dist/builder.mjs +16 -1
  3. package/dist/builder.mjs.map +1 -1
  4. package/dist/cli/endpoint.mjs +8 -6
  5. package/dist/cli/endpoint.mjs.map +1 -1
  6. package/dist/cli/longpoll_broker.mjs +214 -0
  7. package/dist/cli/longpoll_broker.mjs.map +1 -0
  8. package/dist/cli/longpoll_options.mjs +102 -0
  9. package/dist/cli/longpoll_options.mjs.map +1 -0
  10. package/dist/cli/longpoll_session.mjs +135 -0
  11. package/dist/cli/longpoll_session.mjs.map +1 -0
  12. package/dist/cli/middleware.mjs +25 -0
  13. package/dist/cli/middleware.mjs.map +1 -0
  14. package/dist/cli/options.mjs +14 -2
  15. package/dist/cli/options.mjs.map +1 -1
  16. package/dist/cli/route_pattern.mjs +129 -0
  17. package/dist/cli/route_pattern.mjs.map +1 -0
  18. package/dist/cli/routes.mjs +80 -4
  19. package/dist/cli/routes.mjs.map +1 -1
  20. package/dist/cli/server.mjs +243 -23
  21. package/dist/cli/server.mjs.map +1 -1
  22. package/dist/cli/static_files.mjs +125 -0
  23. package/dist/cli/static_files.mjs.map +1 -0
  24. package/dist/endpoint.mjs +8 -6
  25. package/dist/endpoint.mjs.map +1 -1
  26. package/dist/group.mjs +17 -1
  27. package/dist/group.mjs.map +1 -1
  28. package/dist/http_failure.mjs +45 -0
  29. package/dist/http_failure.mjs.map +1 -0
  30. package/dist/longpoll_broker.mjs +214 -0
  31. package/dist/longpoll_broker.mjs.map +1 -0
  32. package/dist/longpoll_options.mjs +102 -0
  33. package/dist/longpoll_options.mjs.map +1 -0
  34. package/dist/longpoll_session.mjs +135 -0
  35. package/dist/longpoll_session.mjs.map +1 -0
  36. package/dist/middleware.mjs +25 -0
  37. package/dist/middleware.mjs.map +1 -0
  38. package/dist/options.mjs +14 -2
  39. package/dist/options.mjs.map +1 -1
  40. package/dist/response.mjs +8 -0
  41. package/dist/response.mjs.map +1 -1
  42. package/dist/route_info.mjs +22 -0
  43. package/dist/route_info.mjs.map +1 -0
  44. package/dist/route_pattern.mjs +129 -0
  45. package/dist/route_pattern.mjs.map +1 -0
  46. package/dist/routes.mjs +80 -4
  47. package/dist/routes.mjs.map +1 -1
  48. package/dist/runtime.mjs +170 -59
  49. package/dist/runtime.mjs.map +1 -1
  50. package/dist/server.mjs +243 -23
  51. package/dist/server.mjs.map +1 -1
  52. package/dist/server_context.mjs +88 -0
  53. package/dist/server_context.mjs.map +1 -0
  54. package/dist/static_files.mjs +125 -0
  55. package/dist/static_files.mjs.map +1 -0
  56. package/dist/token.mjs +12 -0
  57. package/dist/token.mjs.map +1 -1
  58. package/dist/tokens.mjs +16 -1
  59. package/dist/tokens.mjs.map +1 -1
  60. package/package.json +9 -4
  61. package/src/builder.lango +11 -0
  62. package/src/endpoint.lango +10 -4
  63. package/src/group.lango +14 -0
  64. package/src/http_failure.lango +26 -0
  65. package/src/longpoll.lua +61 -0
  66. package/src/longpoll_broker.lango +161 -0
  67. package/src/longpoll_options.lango +79 -0
  68. package/src/longpoll_session.lango +90 -0
  69. package/src/middleware.lango +10 -0
  70. package/src/options.lango +16 -0
  71. package/src/response.lango +6 -0
  72. package/src/route_info.lango +15 -0
  73. package/src/route_pattern.lango +86 -0
  74. package/src/routes.lango +80 -4
  75. package/src/runtime.lango +113 -13
  76. package/src/server.lango +182 -17
  77. package/src/server_context.lango +66 -0
  78. package/src/static_files.lango +90 -0
  79. package/src/token.lango +11 -0
  80. package/src/tokens.lango +11 -1
@@ -0,0 +1,79 @@
1
+ import js global Number
2
+ import js global Object
3
+ import js global process
4
+ import js global URL
5
+
6
+ export longpollOptions(spec)
7
+ export redisOptions(spec)
8
+
9
+ longpollOptions(spec)
10
+ result = {
11
+ kind: "longpoll"
12
+ path: spec.path
13
+ auth: "login"
14
+ waitTimeoutMs: 20000
15
+ retentionMs: 300000
16
+ maxMessages: 1000
17
+ fallback: null
18
+ }
19
+ for spec as key: value
20
+ if !Object/hasOwn(result, key) or key == "kind"
21
+ throw "Unknown longpoll option: ${key}"
22
+ result[key] = value
23
+ if result.auth == null
24
+ result.auth = "login"
25
+ validPath(result.path)
26
+ if !is_string(result.auth) or result.auth == "" or result.auth.includes(",")
27
+ throw "Longpoll auth must name one permission"
28
+ if result.fallback != null
29
+ validPath(result.fallback)
30
+ limits = {
31
+ waitTimeoutMs: 60000
32
+ retentionMs: 86400000
33
+ maxMessages: 10000
34
+ }
35
+ for limits as key: limit
36
+ if !is_number(result[key]) and !is_string(result[key])
37
+ throw "Invalid longpoll option: ${key}"
38
+ value = Number(result[key])
39
+ if !Number/isSafeInteger(value) or value < 1 or value > limit
40
+ throw "Invalid longpoll option: ${key}"
41
+ result[key] = value
42
+ return result
43
+
44
+ validPath(value)
45
+ 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("//")
46
+ throw "Longpoll requires an exact absolute URL path"
47
+ return null
48
+
49
+ redisOptions(spec)
50
+ if spec == null
51
+ return null
52
+ if !is_object(spec) or is_array(spec)
53
+ throw "Redis configuration must be a map"
54
+ allowed = ["connectionEnv", "namespace", "maxPendingPolls"]
55
+ for spec as key: value
56
+ if !allowed.includes(key)
57
+ throw "Unknown Redis option: ${key}"
58
+ if !is_string(spec.connectionEnv) or spec.connectionEnv == "" or !is_string(spec.namespace) or spec.namespace == "" or spec.namespace.length > 128
59
+ throw "Redis requires connectionEnv and namespace"
60
+ name = spec.connectionEnv
61
+ value = process.env[name]
62
+ if !is_string(value) or value == ""
63
+ throw "Redis connection environment variable is missing"
64
+ url = new URL(value)
65
+ protocols = ["redis:", "rediss:"]
66
+ if !protocols.includes(url.protocol)
67
+ throw "Redis requires a redis:// or rediss:// URL"
68
+ maximum = 1024
69
+ if spec.maxPendingPolls != null
70
+ if !is_number(spec.maxPendingPolls) and !is_string(spec.maxPendingPolls)
71
+ throw "Invalid Redis maxPendingPolls"
72
+ maximum = Number(spec.maxPendingPolls)
73
+ if !Number/isSafeInteger(maximum) or maximum < 1 or maximum > 10000
74
+ throw "Invalid Redis maxPendingPolls"
75
+ return {
76
+ connectionEnv: spec.connectionEnv
77
+ namespace: spec.namespace
78
+ maxPendingPolls: maximum
79
+ }
@@ -0,0 +1,90 @@
1
+ import js global Promise
2
+ import js global Buffer
3
+ import js global Date
4
+ import js global Math
5
+ import js global setTimeout
6
+ import js global clearTimeout
7
+
8
+ export class LongpollSession(broker, route, authorize, body)
9
+ methods
10
+ run()
11
+ cancel()
12
+
13
+ LongpollSession(broker, route, authorize, body)
14
+ @broker = broker
15
+ @route = route
16
+ @authorize = authorize
17
+ @body = body
18
+ @cancelled = false
19
+ @timer = null
20
+ @sleep = null
21
+ @token = null
22
+ @deadline = 0
23
+ @input = null
24
+ @cursor = null
25
+
26
+ LongpollSession:cancel()
27
+ @cancelled = true
28
+ clearTimeout(@timer)
29
+ if @sleep != null
30
+ @sleep.resolve(null)
31
+ return null
32
+
33
+ LongpollSession:run()
34
+ try
35
+ @input = from_json(@body)
36
+ input = @input
37
+ if !is_object(input) or is_array(input) or !is_string(input.key) or input.key == "" or Buffer/byteLength(input.key) > 1024
38
+ return Promise/resolve(failure(400, "InvalidLongpollInput"))
39
+ if input.cursor != null and (!is_string(input.cursor) or input.cursor.length > 512)
40
+ return Promise/resolve(failure(400, "InvalidLongpollInput"))
41
+ @cursor = input.cursor
42
+ catch error
43
+ return Promise/resolve(failure(400, "InvalidJson"))
44
+ auth = @authorize
45
+ return chain auth(null, null)
46
+ then(result)
47
+ if result.status != 200
48
+ return result
49
+ @token = result.authorization
50
+ @deadline = Date/now() + @route.waitTimeoutMs
51
+ return poll()
52
+ catch(error)
53
+ return failure(503, "LongpollUnavailable")
54
+ finally
55
+ cancel()
56
+
57
+ LongpollSession:poll()
58
+ if @cancelled
59
+ return Promise/resolve(failure(503, "Unavailable"))
60
+ return chain @broker.read(@route.path, @input.key, @cursor)
61
+ then(batch)
62
+ if @cancelled
63
+ return failure(503, "Unavailable")
64
+ if batch.resyncRequired or batch.messages.length > 0 or Date/now() >= @deadline
65
+ if batch.resyncRequired
66
+ batch.fallback = @route.fallback
67
+ auth = @authorize
68
+ return auth(@token, batch)
69
+ @cursor = batch.cursor
70
+ @sleep = Promise/withResolvers()
71
+ sleep = @sleep
72
+ wake = ()
73
+ capture sleep
74
+ sleep.resolve(null)
75
+ @timer = setTimeout(wake, Math/min(250, Math/max(1, @deadline - Date/now())))
76
+ return chain sleep.promise
77
+ then(ignored)
78
+ return poll()
79
+
80
+ failure(status, code)
81
+ return {
82
+ status: status
83
+ headers: {
84
+ "content-type": "application/json; charset=utf-8"
85
+ "cache-control": "no-store"
86
+ }
87
+ body: to_json({
88
+ error: code
89
+ })
90
+ }
@@ -0,0 +1,10 @@
1
+ import js global RegExp
2
+
3
+ export middlewareName(name)
4
+
5
+ middlewareName(name)
6
+ reserved = ["routes", "endpoint", "longpoll", "group", "include", "event", "middleware"]
7
+ pattern = new RegExp("^[A-Za-z_][A-Za-z0-9_-]*$")
8
+ if !is_string(name) or !pattern.test(name) or reserved.includes(name)
9
+ throw "Invalid or reserved middleware name: ${name}"
10
+ return name
package/src/options.lango CHANGED
@@ -1,5 +1,9 @@
1
+ import "./longpoll_options"
2
+ redisOptions(spec)
1
3
  import "./database_options"
2
4
  databaseOptions(root, spec, workers)
5
+ import "./static_files"
6
+ staticOptions(root, spec)
3
7
  import js "node:fs" as fs
4
8
  import js "node:path" as path
5
9
  import js global Object
@@ -38,6 +42,8 @@ options(root, supplied = null)
38
42
  activeKeyId: "current"
39
43
  requestEvent: false
40
44
  database: null
45
+ redis: null
46
+ static: null
41
47
  }
42
48
  if supplied != null
43
49
  for supplied as key: value
@@ -74,6 +80,8 @@ options(root, supplied = null)
74
80
  result.keys = keys
75
81
  result.key = null
76
82
  result.database = databaseOptions(result.root, result.database, result.workers)
83
+ result.redis = redisOptions(result.redis)
84
+ result.static = staticOptions(result.root, result.static)
77
85
  return result
78
86
 
79
87
  deployment(directory)
@@ -90,12 +98,20 @@ deployment(directory)
90
98
  throw "Duplicate or nonempty deployment section: ${name}"
91
99
  seen.add(name)
92
100
  switch name
101
+ case "static"
102
+ attributes(tag, ["path", "directory", "index"])
103
+ settings.static = tag.attributes()
104
+ continue
93
105
  case "http"
94
106
  attributes(tag, ["host", "port", "bodyLimit", "bodyTimeoutMs"])
95
107
  case "workers"
96
108
  attributes(tag, ["workers", "maxQueue", "requestTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs"])
97
109
  case "events"
98
110
  attributes(tag, ["requestEvent", "eventTimeoutMs"])
111
+ case "redis"
112
+ attributes(tag, ["connectionEnv", "namespace", "maxPendingPolls"])
113
+ settings.redis = tag.attributes()
114
+ continue
99
115
  case "database"
100
116
  attributes(tag, ["type", "file", "connectionEnv", "busyTimeoutMs", "queryTimeoutMs", "connectTimeoutSeconds"])
101
117
  settings.database = tag.attributes()
@@ -2,11 +2,14 @@ import js "node:http" as http
2
2
 
3
3
  import "./options"
4
4
  contains(items, value)
5
+ import "./http_failure"
6
+ class HttpFailure
5
7
  export class Response()
6
8
  methods
7
9
  status(code)
8
10
  header(name, value)
9
11
  result(body)
12
+ reject(status, code)
10
13
 
11
14
  Response()
12
15
  @status = 200
@@ -40,3 +43,6 @@ Response:result(body)
40
43
  headers: from_json(to_json(@headers))
41
44
  body: body
42
45
  }
46
+
47
+ Response:reject(status, code)
48
+ throw new HttpFailure(status, code, @headers)
@@ -0,0 +1,15 @@
1
+ export routeInfo(definitions)
2
+
3
+ routeInfo(definitions)
4
+ result = []
5
+ for definitions as route
6
+ kind = route.kind
7
+ if kind == null
8
+ kind = "endpoint"
9
+ result.add({
10
+ path: route.path
11
+ kind: kind
12
+ auth: route.auth
13
+ middleware: route.middleware
14
+ })
15
+ return result
@@ -0,0 +1,86 @@
1
+ import js global RegExp
2
+
3
+ export routePattern(path)
4
+ export matchPath(pattern, path)
5
+ export moreSpecific(candidate, current)
6
+
7
+ routePattern(path)
8
+ if !is_string(path) or !path.startsWith("/") or path.includes("?") or path.includes("#") or path.includes("\\") or path.includes("//")
9
+ throw "Endpoint requires an absolute URL path"
10
+ if path.includes("*") and (!path.endsWith("/*") or path.indexOf("*") != path.lastIndexOf("*"))
11
+ throw "Only trailing /* wildcards are supported"
12
+ segments = path.split("/")
13
+ segments = segments.slice(1)
14
+ wildcard = path.endsWith("/*")
15
+ if wildcard
16
+ segments.pop()
17
+ names = []
18
+ shape = []
19
+ identifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$")
20
+ reserved = ["__proto__", "constructor", "prototype"]
21
+ for segments as segment
22
+ if segment.includes("{") or segment.includes("}")
23
+ if !segment.startsWith("{") or !segment.endsWith("}")
24
+ throw "Path parameters must occupy an entire segment"
25
+ name = segment.slice(1, -1)
26
+ if !identifier.test(name) or reserved.includes(name)
27
+ throw "Invalid path parameter name: ${name}"
28
+ if names.includes(name)
29
+ throw "Duplicate path parameter: ${name}"
30
+ names.add(name)
31
+ shape.add("{}")
32
+ else
33
+ shape.add(segment)
34
+ if wildcard
35
+ shape.add("*")
36
+ key = shape.join("/")
37
+ key = "/${key}"
38
+ return {
39
+ segments: segments
40
+ wildcard: wildcard
41
+ key: key
42
+ }
43
+
44
+ matchPath(pattern, path)
45
+ parts = path.split("/")
46
+ if parts[0] != ""
47
+ return null
48
+ parts = parts.slice(1)
49
+ count = pattern.segments.length
50
+ if pattern.wildcard
51
+ if parts.length <= count
52
+ return null
53
+ else
54
+ if parts.length != count
55
+ return null
56
+ parameters = {}
57
+ for pattern.segments as index: segment
58
+ value = parts[index]
59
+ if segment.startsWith("{")
60
+ if value == ""
61
+ return null
62
+ name = segment.slice(1, -1)
63
+ parameters[name] = value
64
+ else
65
+ if segment != value
66
+ return null
67
+ return parameters
68
+
69
+ moreSpecific(candidate, current)
70
+ if current == null
71
+ return true
72
+ if candidate.wildcard != current.wildcard
73
+ return !candidate.wildcard
74
+ first = candidate.segments
75
+ second = current.segments
76
+ count = first.length
77
+ if second.length < count
78
+ count = second.length
79
+ for range(count) as index
80
+ segment = first[index]
81
+ alternative = second[index]
82
+ literal = !segment.startsWith("{")
83
+ other = !alternative.startsWith("{")
84
+ if literal != other
85
+ return literal
86
+ return first.length > second.length
package/src/routes.lango CHANGED
@@ -1,3 +1,5 @@
1
+ import "./route_pattern"
2
+ routePattern(path)
1
3
  import "./options"
2
4
  contains(items, value)
3
5
  import js "node:fs" as fs
@@ -5,12 +7,21 @@ import js "node:path" as path
5
7
  import js "node:module" as modules
6
8
  import "./options"
7
9
  attributes(tag, allowed)
10
+ import js global Object
11
+ import "./middleware"
12
+ middlewareName(name)
8
13
  import "./endpoint"
9
14
  class Endpoint
10
15
 
16
+ import "./longpoll_options"
17
+ longpollOptions(spec)
18
+
11
19
  export class Routes(root)
12
20
  methods
13
21
  endpoint(spec)
22
+ addMiddleware(name, spec)
23
+ middlewares()
24
+ longpoll(spec)
14
25
  include(spec, auth = null)
15
26
  xml(file)
16
27
  definitions()
@@ -21,20 +32,59 @@ Routes(root)
21
32
  @root = path/resolve(root)
22
33
  @items = []
23
34
  @events = {}
35
+ @middlewares = Object/create(null)
24
36
 
25
37
  Routes:endpoint(spec)
26
38
  item = new Endpoint(spec)
27
- for @items as other
28
- if other.path == item.path
29
- throw "Duplicate endpoint: ${item.path}"
39
+ checkPath(item.path)
30
40
  @items.add({
31
41
  path: item.path
32
42
  module: resolveModule(item.module, @root)
33
43
  handler: item.handler
34
44
  auth: item.auth
45
+ middleware: item.middleware
35
46
  })
36
47
  return @this
37
48
 
49
+ Routes:checkPath(path)
50
+ pattern = routePattern(path)
51
+ for @items as other
52
+ if other.path == path
53
+ throw "Duplicate endpoint: ${path}"
54
+ existing = routePattern(other.path)
55
+ if existing.key == pattern.key
56
+ throw "Conflicting endpoint pattern: ${path}"
57
+ return null
58
+
59
+ Routes:addMiddleware(name, spec)
60
+ middlewareName(name)
61
+ if Object/hasOwn(@middlewares, name)
62
+ throw "Duplicate middleware: ${name}"
63
+ if !is_object(spec) or is_array(spec)
64
+ throw "Middleware requires a module and exported handler"
65
+ for spec as key: value
66
+ if key != "module" and key != "handler" and key != "validate"
67
+ throw "Unknown middleware option: ${key}"
68
+ if !is_string(spec.handler) or spec.handler == ""
69
+ throw "Middleware handler is required"
70
+ if spec.validate != null and (!is_string(spec.validate) or spec.validate == "")
71
+ throw "Middleware validate must name an exported function"
72
+ @middlewares[name] = {
73
+ module: resolveModule(spec.module, @root)
74
+ handler: spec.handler
75
+ validate: spec.validate
76
+ }
77
+ return @this
78
+
79
+ Routes:middlewares()
80
+ return from_json(to_json(@middlewares))
81
+
82
+ Routes:longpoll(spec)
83
+ item = longpollOptions(spec)
84
+ checkPath(item.path)
85
+ @items.add(item)
86
+ return @this
87
+
38
88
  Routes:event(spec)
39
89
  if !contains(["register", "validate", "request"], spec.name)
40
90
  throw "Unknown event: ${spec.name}"
@@ -133,6 +183,14 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
133
183
  handler: spec.handler
134
184
  auth: auth
135
185
  })
186
+ case "longpoll"
187
+ attributes(tag, ["path", "auth", "waitTimeoutMs", "retentionMs", "maxMessages", "fallback"])
188
+ leaf(tag)
189
+ spec.path = joinPath(prefix, spec.path)
190
+ spec.auth = auth
191
+ if spec.fallback != null
192
+ spec.fallback = joinPath(prefix, spec.fallback)
193
+ longpoll(spec)
136
194
  case "group"
137
195
  attributes(tag, ["path", "module", "auth"])
138
196
  collect(tag, joinPath(prefix, spec.path), mod, auth, directory, stack, false)
@@ -140,6 +198,16 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
140
198
  attributes(tag, ["module", "path"])
141
199
  leaf(tag)
142
200
  includeAt(spec, directory, prefix, stack, auth)
201
+ case "middleware"
202
+ attributes(tag, ["name", "module", "handler", "validate"])
203
+ leaf(tag)
204
+ if !allowEvents
205
+ throw "Middleware declarations are only allowed in the application's root routes.xml"
206
+ addMiddleware(spec.name, {
207
+ module: resolveModule(spec.module, directory)
208
+ handler: spec.handler
209
+ validate: spec.validate
210
+ })
143
211
  case "event"
144
212
  attributes(tag, ["name", "module", "handler"])
145
213
  leaf(tag)
@@ -151,7 +219,15 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
151
219
  handler: spec.handler
152
220
  })
153
221
  else
154
- throw "Unknown routes element: ${tag.tag()}"
222
+ attributes(tag, ["path", "module", "handler", "auth"])
223
+ leaf(tag)
224
+ endpoint({
225
+ path: joinPath(prefix, spec.path)
226
+ module: resolveModule(mod, directory)
227
+ handler: spec.handler
228
+ auth: auth
229
+ middleware: tag.tag()
230
+ })
155
231
  return null
156
232
 
157
233
  leaf(tag)