@telorun/http-server 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.
- package/LICENSE +17 -0
- package/dist/http-api-controller.d.ts +47 -0
- package/dist/http-api-controller.js +201 -0
- package/dist/http-server-controller.d.ts +18 -0
- package/dist/http-server-controller.js +104 -0
- package/dist/openapi.js +152 -0
- package/package.json +34 -0
- package/src/http-api-controller.ts +243 -0
- package/src/http-server-controller.ts +183 -0
- package/tsconfig.json +17 -0
- package/tsconfig.lib.json +9 -0
- package/tsconfig.spec.json +10 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# SUSTAINABLE USE LICENSE (Fair-code)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DiglyAI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to use, copy, modify, and distribute the Software for any purpose—including commercial purposes—subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
1. ANTI-COMPETITION RESTRICTION: The Software may not be provided to third parties as a managed service, commercial SaaS (Software-as-a-Service), PaaS (Platform-as-a-Service), BaaS (Backend-as-a-Service), or similar offering where the primary value provided to the user is the functionality of the Software itself, without a separate commercial license from the copyright holder.
|
|
8
|
+
|
|
9
|
+
2. PERMITTED COMMERCIAL USE: You are free to use the Software to build, host, and monetize your own commercial applications, products, and services, provided such use does not violate Clause 1.
|
|
10
|
+
|
|
11
|
+
3. ATTRIBUTION: This copyright notice and license must be included in all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
4. CONTRIBUTIONS: Contributions to the Software are welcome and encouraged. By contributing, you agree that your contributions may be incorporated into the Software and distributed under this license.
|
|
14
|
+
|
|
15
|
+
5. DISCLAIMER: The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.
|
|
16
|
+
|
|
17
|
+
For commercial licensing, managed hosting exemptions, or enterprise inquiries, please contact DiglyAI.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ControllerContext, ResourceContext, ResourceInstance } from "@telorun/sdk";
|
|
2
|
+
import { Static } from "@sinclair/typebox";
|
|
3
|
+
import { FastifyInstance } from "fastify";
|
|
4
|
+
declare const HttpApiManifest: import("@sinclair/typebox").TObject<{
|
|
5
|
+
routes: import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
|
|
6
|
+
request: import("@sinclair/typebox").TObject<{
|
|
7
|
+
path: import("@sinclair/typebox").TString;
|
|
8
|
+
method: import("@sinclair/typebox").TString;
|
|
9
|
+
schema: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TObject<{
|
|
10
|
+
params: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
11
|
+
query: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
12
|
+
body: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
13
|
+
headers: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
14
|
+
}>>;
|
|
15
|
+
}>;
|
|
16
|
+
handler: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TObject<{
|
|
17
|
+
kind: import("@sinclair/typebox").TString;
|
|
18
|
+
name: import("@sinclair/typebox").TString;
|
|
19
|
+
inputs: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
20
|
+
}>>;
|
|
21
|
+
response: import("@sinclair/typebox").TObject<{
|
|
22
|
+
status: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TNumber, import("@sinclair/typebox").TString]>;
|
|
23
|
+
statuses: import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TObject<{
|
|
24
|
+
schema: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TObject<{
|
|
25
|
+
query: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
26
|
+
body: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
27
|
+
headers: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
28
|
+
}>>;
|
|
29
|
+
headers: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TString>>;
|
|
30
|
+
body: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TAny>;
|
|
31
|
+
}>>;
|
|
32
|
+
}>;
|
|
33
|
+
}>>;
|
|
34
|
+
}>;
|
|
35
|
+
type HttpApiManifest = Static<typeof HttpApiManifest>;
|
|
36
|
+
export declare function register(ctx: ControllerContext): Promise<void>;
|
|
37
|
+
export declare class HttpServerApi implements ResourceInstance {
|
|
38
|
+
private readonly ctx;
|
|
39
|
+
readonly manifest: HttpApiManifest;
|
|
40
|
+
constructor(ctx: ResourceContext, manifest: HttpApiManifest);
|
|
41
|
+
init(): Promise<void>;
|
|
42
|
+
register(app: FastifyInstance, prefix?: string): void;
|
|
43
|
+
private registerRoutes;
|
|
44
|
+
private registerRoute;
|
|
45
|
+
}
|
|
46
|
+
export declare function create(resource: HttpApiManifest, ctx: ResourceContext): Promise<HttpServerApi>;
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
const HttpApiRouteManifest = Type.Object({
|
|
3
|
+
request: Type.Object({
|
|
4
|
+
path: Type.String(),
|
|
5
|
+
method: Type.String(),
|
|
6
|
+
schema: Type.Optional(Type.Object({
|
|
7
|
+
params: Type.Optional(Type.Any()),
|
|
8
|
+
query: Type.Optional(Type.Any()),
|
|
9
|
+
body: Type.Optional(Type.Any()),
|
|
10
|
+
headers: Type.Optional(Type.Any()),
|
|
11
|
+
})),
|
|
12
|
+
}),
|
|
13
|
+
handler: Type.Optional(Type.Object({
|
|
14
|
+
kind: Type.String(),
|
|
15
|
+
name: Type.String(),
|
|
16
|
+
inputs: Type.Optional(Type.Any()),
|
|
17
|
+
})),
|
|
18
|
+
response: Type.Object({
|
|
19
|
+
status: Type.Union([Type.Number({ minimum: 100, maximum: 599 }), Type.String()]),
|
|
20
|
+
statuses: Type.Record(Type.String(), Type.Object({
|
|
21
|
+
schema: Type.Optional(Type.Object({
|
|
22
|
+
query: Type.Optional(Type.Any()),
|
|
23
|
+
body: Type.Optional(Type.Any()),
|
|
24
|
+
headers: Type.Optional(Type.Any()),
|
|
25
|
+
})),
|
|
26
|
+
headers: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
27
|
+
body: Type.Optional(Type.Any()),
|
|
28
|
+
})),
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
31
|
+
const HttpApiManifest = Type.Object({
|
|
32
|
+
routes: Type.Array(HttpApiRouteManifest),
|
|
33
|
+
});
|
|
34
|
+
export async function register(ctx) { }
|
|
35
|
+
export class HttpServerApi {
|
|
36
|
+
ctx;
|
|
37
|
+
manifest;
|
|
38
|
+
constructor(ctx, manifest) {
|
|
39
|
+
this.ctx = ctx;
|
|
40
|
+
this.manifest = manifest;
|
|
41
|
+
}
|
|
42
|
+
async init() { }
|
|
43
|
+
register(app, prefix = "") {
|
|
44
|
+
if (prefix) {
|
|
45
|
+
app.register(async (scoped) => {
|
|
46
|
+
this.registerRoutes(scoped);
|
|
47
|
+
}, { prefix });
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
this.registerRoutes(app);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
registerRoutes(app) {
|
|
54
|
+
const routes = this.manifest.routes || [];
|
|
55
|
+
for (const route of routes) {
|
|
56
|
+
this.registerRoute(app, route);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
registerRoute(app, route) {
|
|
60
|
+
const handler = route.handler ? resolveHandlerName(route.handler) : null;
|
|
61
|
+
const schema = {};
|
|
62
|
+
if (route.request.schema?.query) {
|
|
63
|
+
schema.querystring = route.request.schema?.query;
|
|
64
|
+
}
|
|
65
|
+
if (route.request.schema?.params) {
|
|
66
|
+
schema.params = route.request.schema?.params;
|
|
67
|
+
}
|
|
68
|
+
if (route.request.schema?.body) {
|
|
69
|
+
schema.body = route.request.schema?.body;
|
|
70
|
+
}
|
|
71
|
+
if (route.request.schema?.headers) {
|
|
72
|
+
schema.headers = route.request.schema?.headers;
|
|
73
|
+
}
|
|
74
|
+
schema.response = Object.keys(route.response.statuses).reduce((acc, status) => {
|
|
75
|
+
const statusConfig = route.response.statuses[status];
|
|
76
|
+
if (statusConfig.schema) {
|
|
77
|
+
acc[status] = {};
|
|
78
|
+
if (statusConfig.schema.query) {
|
|
79
|
+
acc[status].querystring = statusConfig.schema.query;
|
|
80
|
+
}
|
|
81
|
+
if (statusConfig.schema.body) {
|
|
82
|
+
acc[status].body = statusConfig.schema.body;
|
|
83
|
+
}
|
|
84
|
+
if (statusConfig.schema.headers) {
|
|
85
|
+
acc[status].headers = statusConfig.schema.headers;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return acc;
|
|
89
|
+
}, {});
|
|
90
|
+
app.route({
|
|
91
|
+
method: route.request.method,
|
|
92
|
+
url: route.request.path,
|
|
93
|
+
schema,
|
|
94
|
+
handler: async (request, reply) => {
|
|
95
|
+
// const resolveSchema = createSchemaResolver(ctx);
|
|
96
|
+
const requestPayload = {
|
|
97
|
+
params: request.params,
|
|
98
|
+
query: request.query,
|
|
99
|
+
body: request.body,
|
|
100
|
+
headers: request.headers,
|
|
101
|
+
method: request.method,
|
|
102
|
+
url: request.url,
|
|
103
|
+
};
|
|
104
|
+
// validateRequestSchemas(route.request, requestPayload, resolveSchema);
|
|
105
|
+
const result = handler
|
|
106
|
+
? await this.ctx.invoke(handler.kind, handler.name, resolveHandlerInputs(route.handler, requestPayload))
|
|
107
|
+
: undefined;
|
|
108
|
+
// Handle response with body/headers mapping
|
|
109
|
+
const response = route.response;
|
|
110
|
+
// Set status
|
|
111
|
+
const status = typeof response.status === "string"
|
|
112
|
+
? this.ctx.expandValue(response.status, { result })
|
|
113
|
+
: response.status;
|
|
114
|
+
if (response.status) {
|
|
115
|
+
reply.code(status);
|
|
116
|
+
}
|
|
117
|
+
const statusConfig = response.statuses[response.status];
|
|
118
|
+
if (!statusConfig) {
|
|
119
|
+
return reply.code(500).send({ error: "Invalid response status configuration" });
|
|
120
|
+
}
|
|
121
|
+
// Map headers if specified
|
|
122
|
+
if (statusConfig.headers) {
|
|
123
|
+
reply.headers(this.ctx.expandValue(statusConfig.headers, { result }));
|
|
124
|
+
}
|
|
125
|
+
// Map body if specified
|
|
126
|
+
if (statusConfig.body !== undefined) {
|
|
127
|
+
const mappedBody = this.ctx.expandValue(statusConfig.body, {
|
|
128
|
+
result,
|
|
129
|
+
});
|
|
130
|
+
if (statusConfig.schema && statusConfig.schema.body) {
|
|
131
|
+
this.ctx.validateSchema(mappedBody, statusConfig.schema.body);
|
|
132
|
+
}
|
|
133
|
+
return reply.send(mappedBody);
|
|
134
|
+
}
|
|
135
|
+
// No body mapping, send result as-is
|
|
136
|
+
return reply.send(result);
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export async function create(resource, ctx) {
|
|
142
|
+
ctx.validateSchema(resource, HttpApiManifest);
|
|
143
|
+
return new HttpServerApi(ctx, resource);
|
|
144
|
+
}
|
|
145
|
+
function resolveHandlerName(handler) {
|
|
146
|
+
if (typeof handler === "string") {
|
|
147
|
+
const [kind, name] = handler.split("/");
|
|
148
|
+
return { kind, name };
|
|
149
|
+
}
|
|
150
|
+
if (handler &&
|
|
151
|
+
typeof handler === "object" &&
|
|
152
|
+
typeof handler.name === "string" &&
|
|
153
|
+
typeof handler.kind === "string") {
|
|
154
|
+
return { name: handler.name, kind: handler.kind };
|
|
155
|
+
}
|
|
156
|
+
throw new Error("Unable to resolve handler");
|
|
157
|
+
}
|
|
158
|
+
function resolveHandlerInputs(handler, requestPayload) {
|
|
159
|
+
if (typeof handler === "string") {
|
|
160
|
+
return requestPayload;
|
|
161
|
+
}
|
|
162
|
+
if (!handler || typeof handler !== "object") {
|
|
163
|
+
return requestPayload;
|
|
164
|
+
}
|
|
165
|
+
if (!handler.inputs) {
|
|
166
|
+
return requestPayload;
|
|
167
|
+
}
|
|
168
|
+
const context = { request: requestPayload, ...requestPayload };
|
|
169
|
+
return resolveTemplateInputs(handler.inputs, context);
|
|
170
|
+
}
|
|
171
|
+
function resolveTemplateInputs(value, context) {
|
|
172
|
+
if (typeof value === "string") {
|
|
173
|
+
const match = value.match(/^\s*\$\{\{\s*([^}]+)\s*\}\}\s*$/);
|
|
174
|
+
if (match) {
|
|
175
|
+
return resolveTemplatePath(match[1], context);
|
|
176
|
+
}
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
if (Array.isArray(value)) {
|
|
180
|
+
return value.map((item) => resolveTemplateInputs(item, context));
|
|
181
|
+
}
|
|
182
|
+
if (value && typeof value === "object") {
|
|
183
|
+
const resolved = {};
|
|
184
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
185
|
+
resolved[key] = resolveTemplateInputs(entry, context);
|
|
186
|
+
}
|
|
187
|
+
return resolved;
|
|
188
|
+
}
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
function resolveTemplatePath(pathExpression, context) {
|
|
192
|
+
const parts = pathExpression.trim().split(".").filter(Boolean);
|
|
193
|
+
let current = context;
|
|
194
|
+
for (const part of parts) {
|
|
195
|
+
if (!current || (typeof current !== "object" && typeof current !== "function")) {
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
current = current[part];
|
|
199
|
+
}
|
|
200
|
+
return current;
|
|
201
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ResourceContext, ResourceInstance, RuntimeResource } from "@telorun/sdk";
|
|
2
|
+
type HttpServerResource = RuntimeResource & {
|
|
3
|
+
host?: string;
|
|
4
|
+
port?: number;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
openapi?: {
|
|
7
|
+
info: {
|
|
8
|
+
title: string;
|
|
9
|
+
version: string;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
mounts?: Array<{
|
|
13
|
+
path?: string;
|
|
14
|
+
type?: string;
|
|
15
|
+
}>;
|
|
16
|
+
};
|
|
17
|
+
export declare function create(resource: HttpServerResource, ctx: ResourceContext): ResourceInstance | null;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import swagger from "@fastify/swagger";
|
|
2
|
+
import apiReference from "@scalar/fastify-api-reference";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
class HttpServer {
|
|
5
|
+
releaseHold = null;
|
|
6
|
+
app;
|
|
7
|
+
host;
|
|
8
|
+
port;
|
|
9
|
+
baseUrl;
|
|
10
|
+
resource;
|
|
11
|
+
ctx;
|
|
12
|
+
constructor(resource, ctx) {
|
|
13
|
+
this.resource = resource;
|
|
14
|
+
this.ctx = ctx;
|
|
15
|
+
this.host = resource.host || "0.0.0.0";
|
|
16
|
+
this.port = Number(resource.port || 0);
|
|
17
|
+
this.baseUrl = resource.baseUrl ?? `http://${this.host}:${this.port}`;
|
|
18
|
+
if (!this.port) {
|
|
19
|
+
throw new Error("Http.Server port is required");
|
|
20
|
+
}
|
|
21
|
+
this.app = Fastify({ logger: true });
|
|
22
|
+
}
|
|
23
|
+
async init() {
|
|
24
|
+
this.setupPlugins();
|
|
25
|
+
this.setupRoutes();
|
|
26
|
+
}
|
|
27
|
+
async setupPlugins() {
|
|
28
|
+
if (this.resource.openapi) {
|
|
29
|
+
const servers = [];
|
|
30
|
+
// const routesByName = new Map<string, HttpRouteResource>();
|
|
31
|
+
const mounts = this.resource.mounts || [];
|
|
32
|
+
const prefixes = new Set();
|
|
33
|
+
for (const mount of mounts) {
|
|
34
|
+
prefixes.add(mount.path || "");
|
|
35
|
+
}
|
|
36
|
+
for (const prefix of prefixes) {
|
|
37
|
+
servers.push({ url: this.baseUrl + prefix });
|
|
38
|
+
}
|
|
39
|
+
await this.app.register(swagger, {
|
|
40
|
+
openapi: {
|
|
41
|
+
openapi: "3.0.0",
|
|
42
|
+
info: this.resource.openapi.info,
|
|
43
|
+
servers,
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
await this.app.register(apiReference, {
|
|
47
|
+
routePrefix: "/reference",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
setupRoutes() {
|
|
52
|
+
// const routesByName = new Map<string, HttpRouteResource>();
|
|
53
|
+
const mounts = this.resource.mounts || [];
|
|
54
|
+
// const resolveSchema = createSchemaResolver(this.ctx);
|
|
55
|
+
for (const mount of mounts) {
|
|
56
|
+
const type = mount.type || "";
|
|
57
|
+
const { kind, name } = parseType(type);
|
|
58
|
+
const prefix = mount.path || "";
|
|
59
|
+
const api = this.ctx.getResourcesByName(kind, name);
|
|
60
|
+
if (!api) {
|
|
61
|
+
throw new Error(`Failed to mount Http.Api at "${prefix}": ${type} not found`);
|
|
62
|
+
}
|
|
63
|
+
api.register(this.app, prefix);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async run() {
|
|
67
|
+
this.releaseHold = this.ctx.acquireHold();
|
|
68
|
+
try {
|
|
69
|
+
await this.app.listen({ host: this.host, port: this.port });
|
|
70
|
+
await this.ctx.emitEvent(`${this.resource.metadata.name}.Listening`, {
|
|
71
|
+
port: this.port,
|
|
72
|
+
host: this.host,
|
|
73
|
+
baseUrl: this.baseUrl,
|
|
74
|
+
mounts: this.resource.mounts,
|
|
75
|
+
openapi: this.resource.openapi,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
await this.app.close();
|
|
80
|
+
if (this.releaseHold) {
|
|
81
|
+
this.releaseHold();
|
|
82
|
+
this.releaseHold = null;
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async teardown() {
|
|
88
|
+
if (this.releaseHold) {
|
|
89
|
+
this.releaseHold();
|
|
90
|
+
this.releaseHold = null;
|
|
91
|
+
}
|
|
92
|
+
await this.app.close();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
export function create(resource, ctx) {
|
|
96
|
+
return new HttpServer(resource, ctx);
|
|
97
|
+
}
|
|
98
|
+
function parseType(type) {
|
|
99
|
+
const separator = type.lastIndexOf(".");
|
|
100
|
+
if (separator <= 0 || separator === type.length - 1) {
|
|
101
|
+
return { kind: "", name: "" };
|
|
102
|
+
}
|
|
103
|
+
return { kind: type.slice(0, separator), name: type.slice(separator + 1) };
|
|
104
|
+
}
|
package/dist/openapi.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import swagger from '@fastify/swagger';
|
|
2
|
+
import apiReference from '@scalar/fastify-api-reference';
|
|
3
|
+
function getResourceConfig(resource) {
|
|
4
|
+
return resource;
|
|
5
|
+
}
|
|
6
|
+
export function register(ctx) { }
|
|
7
|
+
export function create(resource, ctx) {
|
|
8
|
+
const openApiResource = resource;
|
|
9
|
+
const config = getResourceConfig(openApiResource);
|
|
10
|
+
const apiRefs = config.apis || [];
|
|
11
|
+
if (apiRefs.length === 0) {
|
|
12
|
+
throw new Error(`OpenApi.Spec "${resource.metadata.name}" is missing apis`);
|
|
13
|
+
}
|
|
14
|
+
const handler = (payload) => {
|
|
15
|
+
const serverResource = payload?.resource;
|
|
16
|
+
const app = payload?.app;
|
|
17
|
+
if (!serverResource || !app) {
|
|
18
|
+
throw new Error(`OpenApi.Spec handler missing Http.Server resource or Fastify app`);
|
|
19
|
+
}
|
|
20
|
+
const matchedApis = resolveApis(apiRefs, ctx);
|
|
21
|
+
const mounts = getResourceConfig(serverResource).mounts || [];
|
|
22
|
+
const servers = buildServers(serverResource, mounts, matchedApis);
|
|
23
|
+
if (servers.length === 0) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const paths = buildPaths(matchedApis, mounts);
|
|
27
|
+
const info = config.info && typeof config.info === 'object'
|
|
28
|
+
? config.info
|
|
29
|
+
: {
|
|
30
|
+
title: resource.metadata.name,
|
|
31
|
+
version: resource.version || '1.0.0',
|
|
32
|
+
};
|
|
33
|
+
const routePrefix = config.path || `/openapi/${resource.metadata.name}`;
|
|
34
|
+
app.register(swagger, {
|
|
35
|
+
openapi: {
|
|
36
|
+
openapi: '3.0.0',
|
|
37
|
+
info,
|
|
38
|
+
servers,
|
|
39
|
+
paths,
|
|
40
|
+
},
|
|
41
|
+
routePrefix,
|
|
42
|
+
});
|
|
43
|
+
app.register(apiReference, {
|
|
44
|
+
routePrefix,
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
const httpServers = ctx.getResources('Http.Server');
|
|
48
|
+
return {
|
|
49
|
+
init: async () => {
|
|
50
|
+
// Register listeners after all resources are initialized
|
|
51
|
+
for (const server of httpServers) {
|
|
52
|
+
ctx.on('Http.Server.Ready', server.metadata.name, handler);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
teardown: () => {
|
|
56
|
+
for (const server of httpServers) {
|
|
57
|
+
ctx.offResourceEvent('Http.Server', server.metadata.name, 'Ready', handler);
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function resolveApis(apiRefs, ctx) {
|
|
63
|
+
const apis = [];
|
|
64
|
+
for (const ref of apiRefs) {
|
|
65
|
+
const { kind, name } = parseRef(ref);
|
|
66
|
+
if (!kind || !name) {
|
|
67
|
+
throw new Error(`Reference not found: ${ref}`);
|
|
68
|
+
}
|
|
69
|
+
if (kind !== 'Http.Api' && kind !== 'Http.Route') {
|
|
70
|
+
throw new Error(`Reference not supported: ${ref}`);
|
|
71
|
+
}
|
|
72
|
+
const resource = ctx.kernel.registry.get(kind)?.get(name);
|
|
73
|
+
if (!resource) {
|
|
74
|
+
throw new Error(`Reference not found: ${ref}`);
|
|
75
|
+
}
|
|
76
|
+
apis.push(resource);
|
|
77
|
+
}
|
|
78
|
+
return apis;
|
|
79
|
+
}
|
|
80
|
+
function buildServers(server, mounts, apis) {
|
|
81
|
+
const config = getResourceConfig(server);
|
|
82
|
+
const host = config.host || '0.0.0.0';
|
|
83
|
+
const port = Number(config.port || 0);
|
|
84
|
+
if (!port) {
|
|
85
|
+
return [];
|
|
86
|
+
}
|
|
87
|
+
// Server URL should be the base URL without mount paths
|
|
88
|
+
// Paths will include the mount prefix
|
|
89
|
+
return [{ url: `http://${host}:${port}` }];
|
|
90
|
+
}
|
|
91
|
+
function buildPaths(apis, mounts) {
|
|
92
|
+
const paths = {};
|
|
93
|
+
const mountPrefixByType = new Map();
|
|
94
|
+
for (const mount of mounts) {
|
|
95
|
+
if (mount.type) {
|
|
96
|
+
mountPrefixByType.set(mount.type, mount.path || '');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
for (const api of apis) {
|
|
100
|
+
const prefix = mountPrefixByType.get(`${api.kind}.${api.metadata.name}`) || '';
|
|
101
|
+
if (api.kind === 'Http.Route') {
|
|
102
|
+
const config = getResourceConfig(api);
|
|
103
|
+
const path = joinPath(prefix, api.metadata?.path || config.path || '');
|
|
104
|
+
const method = (api.metadata?.method ||
|
|
105
|
+
config.method ||
|
|
106
|
+
'GET').toLowerCase();
|
|
107
|
+
if (!path) {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (!paths[path]) {
|
|
111
|
+
paths[path] = {};
|
|
112
|
+
}
|
|
113
|
+
paths[path][method] = { responses: { '200': { description: 'OK' } } };
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const routes = getResourceConfig(api).routes || [];
|
|
117
|
+
for (const route of routes) {
|
|
118
|
+
if (typeof route === 'string') {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const request = route.request || {};
|
|
122
|
+
const path = joinPath(prefix, request.path || '');
|
|
123
|
+
const method = (request.method || 'GET').toLowerCase();
|
|
124
|
+
if (!path) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (!paths[path]) {
|
|
128
|
+
paths[path] = {};
|
|
129
|
+
}
|
|
130
|
+
paths[path][method] = { responses: { '200': { description: 'OK' } } };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return paths;
|
|
134
|
+
}
|
|
135
|
+
function parseRef(ref) {
|
|
136
|
+
const separator = ref.lastIndexOf('.');
|
|
137
|
+
if (separator <= 0 || separator === ref.length - 1) {
|
|
138
|
+
return { kind: '', name: '' };
|
|
139
|
+
}
|
|
140
|
+
return { kind: ref.slice(0, separator), name: ref.slice(separator + 1) };
|
|
141
|
+
}
|
|
142
|
+
function joinPath(prefix, path) {
|
|
143
|
+
if (!prefix) {
|
|
144
|
+
return path;
|
|
145
|
+
}
|
|
146
|
+
if (!path) {
|
|
147
|
+
return prefix;
|
|
148
|
+
}
|
|
149
|
+
const trimmedPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
150
|
+
const trimmedPath = path.startsWith('/') ? path : `/${path}`;
|
|
151
|
+
return `${trimmedPrefix}${trimmedPath}`;
|
|
152
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@telorun/http-server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./http-server": {
|
|
9
|
+
"types": "./dist/http-server-controller.d.ts",
|
|
10
|
+
"bun": "./src/http-server-controller.ts",
|
|
11
|
+
"import": "./dist/http-server-controller.js"
|
|
12
|
+
},
|
|
13
|
+
"./http-server-api": {
|
|
14
|
+
"types": "./dist/http-api-controller.d.ts",
|
|
15
|
+
"bun": "./src/http-api-controller.ts",
|
|
16
|
+
"import": "./dist/http-api-controller.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@sinclair/typebox": "^0.34.48",
|
|
21
|
+
"ajv": "^8.17.1",
|
|
22
|
+
"fastify": "^5.7.2",
|
|
23
|
+
"@fastify/swagger": "^9.6.1",
|
|
24
|
+
"@scalar/fastify-api-reference": "^1.44.6",
|
|
25
|
+
"@telorun/sdk": "0.1.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^20.0.0",
|
|
29
|
+
"typescript": "^5.0.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.lib.json"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { ControllerContext, ResourceContext, ResourceInstance } from "@telorun/sdk";
|
|
2
|
+
import { Static, Type } from "@sinclair/typebox";
|
|
3
|
+
import { FastifyInstance } from "fastify";
|
|
4
|
+
|
|
5
|
+
const HttpApiRouteManifest = Type.Object({
|
|
6
|
+
request: Type.Object({
|
|
7
|
+
path: Type.String(),
|
|
8
|
+
method: Type.String(),
|
|
9
|
+
schema: Type.Optional(
|
|
10
|
+
Type.Object({
|
|
11
|
+
params: Type.Optional(Type.Any()),
|
|
12
|
+
query: Type.Optional(Type.Any()),
|
|
13
|
+
body: Type.Optional(Type.Any()),
|
|
14
|
+
headers: Type.Optional(Type.Any()),
|
|
15
|
+
}),
|
|
16
|
+
),
|
|
17
|
+
}),
|
|
18
|
+
handler: Type.Optional(Type.Object({
|
|
19
|
+
kind: Type.String(),
|
|
20
|
+
name: Type.String(),
|
|
21
|
+
inputs: Type.Optional(Type.Any()),
|
|
22
|
+
})),
|
|
23
|
+
response: Type.Object({
|
|
24
|
+
status: Type.Union([Type.Number({ minimum: 100, maximum: 599 }), Type.String()]),
|
|
25
|
+
statuses: Type.Record(
|
|
26
|
+
Type.String(),
|
|
27
|
+
Type.Object({
|
|
28
|
+
schema: Type.Optional(
|
|
29
|
+
Type.Object({
|
|
30
|
+
query: Type.Optional(Type.Any()),
|
|
31
|
+
body: Type.Optional(Type.Any()),
|
|
32
|
+
headers: Type.Optional(Type.Any()),
|
|
33
|
+
}),
|
|
34
|
+
),
|
|
35
|
+
headers: Type.Optional(Type.Record(Type.String(), Type.String())),
|
|
36
|
+
body: Type.Optional(Type.Any()),
|
|
37
|
+
}),
|
|
38
|
+
),
|
|
39
|
+
}),
|
|
40
|
+
});
|
|
41
|
+
type HttpApiRouteManifest = Static<typeof HttpApiRouteManifest>;
|
|
42
|
+
|
|
43
|
+
const HttpApiManifest = Type.Object({
|
|
44
|
+
routes: Type.Array(HttpApiRouteManifest),
|
|
45
|
+
});
|
|
46
|
+
type HttpApiManifest = Static<typeof HttpApiManifest>;
|
|
47
|
+
|
|
48
|
+
export async function register(ctx: ControllerContext): Promise<void> {}
|
|
49
|
+
|
|
50
|
+
export class HttpServerApi implements ResourceInstance {
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly ctx: ResourceContext,
|
|
53
|
+
readonly manifest: HttpApiManifest,
|
|
54
|
+
) {}
|
|
55
|
+
|
|
56
|
+
async init() {}
|
|
57
|
+
|
|
58
|
+
register(app: FastifyInstance, prefix = "") {
|
|
59
|
+
if (prefix) {
|
|
60
|
+
app.register(
|
|
61
|
+
async (scoped) => {
|
|
62
|
+
this.registerRoutes(scoped);
|
|
63
|
+
},
|
|
64
|
+
{ prefix },
|
|
65
|
+
);
|
|
66
|
+
} else {
|
|
67
|
+
this.registerRoutes(app);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private registerRoutes(app: FastifyInstance) {
|
|
72
|
+
const routes = this.manifest.routes || [];
|
|
73
|
+
for (const route of routes) {
|
|
74
|
+
this.registerRoute(app, route);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private registerRoute(app: FastifyInstance, route: HttpApiRouteManifest) {
|
|
79
|
+
const handler = route.handler ? resolveHandlerName(route.handler) : null;
|
|
80
|
+
const schema: any = {};
|
|
81
|
+
if (route.request.schema?.query) {
|
|
82
|
+
schema.querystring = route.request.schema?.query;
|
|
83
|
+
}
|
|
84
|
+
if (route.request.schema?.params) {
|
|
85
|
+
schema.params = route.request.schema?.params;
|
|
86
|
+
}
|
|
87
|
+
if (route.request.schema?.body) {
|
|
88
|
+
schema.body = route.request.schema?.body;
|
|
89
|
+
}
|
|
90
|
+
if (route.request.schema?.headers) {
|
|
91
|
+
schema.headers = route.request.schema?.headers;
|
|
92
|
+
}
|
|
93
|
+
schema.response = Object.keys(route.response.statuses).reduce(
|
|
94
|
+
(acc, status) => {
|
|
95
|
+
const statusConfig = route.response.statuses[status];
|
|
96
|
+
if (statusConfig.schema) {
|
|
97
|
+
acc[status] = {};
|
|
98
|
+
if (statusConfig.schema.query) {
|
|
99
|
+
acc[status].querystring = statusConfig.schema.query;
|
|
100
|
+
}
|
|
101
|
+
if (statusConfig.schema.body) {
|
|
102
|
+
acc[status].body = statusConfig.schema.body;
|
|
103
|
+
}
|
|
104
|
+
if (statusConfig.schema.headers) {
|
|
105
|
+
acc[status].headers = statusConfig.schema.headers;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return acc;
|
|
109
|
+
},
|
|
110
|
+
{} as Record<string, any>,
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
app.route({
|
|
114
|
+
method: route.request.method,
|
|
115
|
+
url: route.request.path,
|
|
116
|
+
schema,
|
|
117
|
+
handler: async (request, reply) => {
|
|
118
|
+
// const resolveSchema = createSchemaResolver(ctx);
|
|
119
|
+
const requestPayload = {
|
|
120
|
+
params: request.params,
|
|
121
|
+
query: request.query,
|
|
122
|
+
body: request.body,
|
|
123
|
+
headers: request.headers,
|
|
124
|
+
method: request.method,
|
|
125
|
+
url: request.url,
|
|
126
|
+
};
|
|
127
|
+
// validateRequestSchemas(route.request, requestPayload, resolveSchema);
|
|
128
|
+
const result = handler
|
|
129
|
+
? await this.ctx.invoke(
|
|
130
|
+
handler.kind,
|
|
131
|
+
handler.name,
|
|
132
|
+
resolveHandlerInputs(route.handler, requestPayload),
|
|
133
|
+
)
|
|
134
|
+
: undefined;
|
|
135
|
+
// Handle response with body/headers mapping
|
|
136
|
+
|
|
137
|
+
const response = route.response;
|
|
138
|
+
|
|
139
|
+
// Set status
|
|
140
|
+
const status =
|
|
141
|
+
typeof response.status === "string"
|
|
142
|
+
? this.ctx.expandValue(response.status, { result })
|
|
143
|
+
: response.status;
|
|
144
|
+
if (response.status) {
|
|
145
|
+
reply.code(status);
|
|
146
|
+
}
|
|
147
|
+
const statusConfig = response.statuses[response.status];
|
|
148
|
+
if (!statusConfig) {
|
|
149
|
+
return reply.code(500).send({ error: "Invalid response status configuration" });
|
|
150
|
+
}
|
|
151
|
+
// Map headers if specified
|
|
152
|
+
if (statusConfig.headers) {
|
|
153
|
+
reply.headers(this.ctx.expandValue(statusConfig.headers, { result }));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Map body if specified
|
|
157
|
+
if (statusConfig.body !== undefined) {
|
|
158
|
+
const mappedBody = this.ctx.expandValue(statusConfig.body, {
|
|
159
|
+
result,
|
|
160
|
+
});
|
|
161
|
+
if (statusConfig.schema && statusConfig.schema.body) {
|
|
162
|
+
this.ctx.validateSchema(mappedBody, statusConfig.schema.body);
|
|
163
|
+
}
|
|
164
|
+
return reply.send(mappedBody);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// No body mapping, send result as-is
|
|
168
|
+
return reply.send(result);
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function create(
|
|
175
|
+
resource: HttpApiManifest,
|
|
176
|
+
ctx: ResourceContext,
|
|
177
|
+
): Promise<HttpServerApi> {
|
|
178
|
+
ctx.validateSchema(resource, HttpApiManifest);
|
|
179
|
+
return new HttpServerApi(ctx, resource);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function resolveHandlerName(handler: any): { kind: string; name: string } {
|
|
183
|
+
if (typeof handler === "string") {
|
|
184
|
+
const [kind, name] = handler.split("/");
|
|
185
|
+
return { kind, name };
|
|
186
|
+
}
|
|
187
|
+
if (
|
|
188
|
+
handler &&
|
|
189
|
+
typeof handler === "object" &&
|
|
190
|
+
typeof handler.name === "string" &&
|
|
191
|
+
typeof handler.kind === "string"
|
|
192
|
+
) {
|
|
193
|
+
return { name: handler.name, kind: handler.kind };
|
|
194
|
+
}
|
|
195
|
+
throw new Error("Unable to resolve handler");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function resolveHandlerInputs(handler: any, requestPayload: Record<string, any>): any {
|
|
199
|
+
if (typeof handler === "string") {
|
|
200
|
+
return requestPayload;
|
|
201
|
+
}
|
|
202
|
+
if (!handler || typeof handler !== "object") {
|
|
203
|
+
return requestPayload;
|
|
204
|
+
}
|
|
205
|
+
if (!handler.inputs) {
|
|
206
|
+
return requestPayload;
|
|
207
|
+
}
|
|
208
|
+
const context = { request: requestPayload, ...requestPayload };
|
|
209
|
+
return resolveTemplateInputs(handler.inputs, context);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function resolveTemplateInputs(value: any, context: Record<string, any>): any {
|
|
213
|
+
if (typeof value === "string") {
|
|
214
|
+
const match = value.match(/^\s*\$\{\{\s*([^}]+)\s*\}\}\s*$/);
|
|
215
|
+
if (match) {
|
|
216
|
+
return resolveTemplatePath(match[1], context);
|
|
217
|
+
}
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
if (Array.isArray(value)) {
|
|
221
|
+
return value.map((item) => resolveTemplateInputs(item, context));
|
|
222
|
+
}
|
|
223
|
+
if (value && typeof value === "object") {
|
|
224
|
+
const resolved: Record<string, any> = {};
|
|
225
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
226
|
+
resolved[key] = resolveTemplateInputs(entry, context);
|
|
227
|
+
}
|
|
228
|
+
return resolved;
|
|
229
|
+
}
|
|
230
|
+
return value;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function resolveTemplatePath(pathExpression: string, context: Record<string, any>): any {
|
|
234
|
+
const parts = pathExpression.trim().split(".").filter(Boolean);
|
|
235
|
+
let current: any = context;
|
|
236
|
+
for (const part of parts) {
|
|
237
|
+
if (!current || (typeof current !== "object" && typeof current !== "function")) {
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
current = current[part];
|
|
241
|
+
}
|
|
242
|
+
return current;
|
|
243
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import swagger from "@fastify/swagger";
|
|
2
|
+
import apiReference from "@scalar/fastify-api-reference";
|
|
3
|
+
import type { ResourceContext, ResourceInstance, RuntimeResource } from "@telorun/sdk";
|
|
4
|
+
import Fastify, { FastifyInstance } from "fastify";
|
|
5
|
+
import { HttpServerApi } from "./http-api-controller.js";
|
|
6
|
+
|
|
7
|
+
type HttpRouteResource = RuntimeResource & {
|
|
8
|
+
metadata?: { path?: string; method?: string };
|
|
9
|
+
path?: string;
|
|
10
|
+
method?: string;
|
|
11
|
+
handler?: HttpHandlerSpec;
|
|
12
|
+
request?: HttpRequestSchema;
|
|
13
|
+
response?: {
|
|
14
|
+
status?: number;
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
body?: any;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
type HttpServerResource = RuntimeResource & {
|
|
21
|
+
host?: string;
|
|
22
|
+
port?: number;
|
|
23
|
+
baseUrl?: string;
|
|
24
|
+
openapi?: {
|
|
25
|
+
info: {
|
|
26
|
+
title: string;
|
|
27
|
+
version: string;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
mounts?: Array<{
|
|
31
|
+
path?: string;
|
|
32
|
+
type?: string;
|
|
33
|
+
}>;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type HttpApiResource = RuntimeResource & {
|
|
37
|
+
routes?: Array<
|
|
38
|
+
| string
|
|
39
|
+
| {
|
|
40
|
+
request?: {
|
|
41
|
+
path?: string;
|
|
42
|
+
method?: string;
|
|
43
|
+
query?: Record<string, any>;
|
|
44
|
+
body?: Record<string, any>;
|
|
45
|
+
headers?: Record<string, any>;
|
|
46
|
+
};
|
|
47
|
+
handler?: HttpHandlerSpec;
|
|
48
|
+
response?: {
|
|
49
|
+
status?: number;
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
body?: any;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
>;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
type HttpHandlerSpec =
|
|
58
|
+
| string
|
|
59
|
+
| {
|
|
60
|
+
name?: string;
|
|
61
|
+
inputs?: Record<string, any>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
type HttpRequestSchema = {
|
|
65
|
+
query?: Record<string, any>;
|
|
66
|
+
body?: Record<string, any>;
|
|
67
|
+
headers?: Record<string, any>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
class HttpServer implements ResourceInstance {
|
|
71
|
+
private releaseHold: (() => void) | null = null;
|
|
72
|
+
private readonly app: FastifyInstance;
|
|
73
|
+
private readonly host: string;
|
|
74
|
+
private readonly port: number;
|
|
75
|
+
private readonly baseUrl: string;
|
|
76
|
+
private readonly resource: HttpServerResource;
|
|
77
|
+
private readonly ctx: ResourceContext;
|
|
78
|
+
|
|
79
|
+
constructor(resource: HttpServerResource, ctx: ResourceContext) {
|
|
80
|
+
this.resource = resource;
|
|
81
|
+
this.ctx = ctx;
|
|
82
|
+
this.host = resource.host || "0.0.0.0";
|
|
83
|
+
this.port = Number(resource.port || 0);
|
|
84
|
+
this.baseUrl = resource.baseUrl ?? `http://${this.host}:${this.port}`;
|
|
85
|
+
|
|
86
|
+
if (!this.port) {
|
|
87
|
+
throw new Error("Http.Server port is required");
|
|
88
|
+
}
|
|
89
|
+
this.app = Fastify({ logger: true });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async init() {
|
|
93
|
+
this.setupPlugins();
|
|
94
|
+
this.setupRoutes();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private async setupPlugins() {
|
|
98
|
+
if (this.resource.openapi) {
|
|
99
|
+
const servers = [];
|
|
100
|
+
// const routesByName = new Map<string, HttpRouteResource>();
|
|
101
|
+
const mounts = this.resource.mounts || [];
|
|
102
|
+
const prefixes = new Set();
|
|
103
|
+
for (const mount of mounts) {
|
|
104
|
+
prefixes.add(mount.path || "");
|
|
105
|
+
}
|
|
106
|
+
for (const prefix of prefixes) {
|
|
107
|
+
servers.push({ url: this.baseUrl + prefix });
|
|
108
|
+
}
|
|
109
|
+
await this.app.register(swagger, {
|
|
110
|
+
openapi: {
|
|
111
|
+
openapi: "3.0.0",
|
|
112
|
+
info: this.resource.openapi.info,
|
|
113
|
+
servers,
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
await this.app.register(apiReference, {
|
|
117
|
+
routePrefix: "/reference",
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private setupRoutes(): void {
|
|
123
|
+
// const routesByName = new Map<string, HttpRouteResource>();
|
|
124
|
+
const mounts = this.resource.mounts || [];
|
|
125
|
+
// const resolveSchema = createSchemaResolver(this.ctx);
|
|
126
|
+
for (const mount of mounts) {
|
|
127
|
+
const type = mount.type || "";
|
|
128
|
+
const { kind, name } = parseType(type);
|
|
129
|
+
const prefix = mount.path || "";
|
|
130
|
+
|
|
131
|
+
const api: HttpServerApi = this.ctx.getResourcesByName(kind, name) as any;
|
|
132
|
+
|
|
133
|
+
if (!api) {
|
|
134
|
+
throw new Error(`Failed to mount Http.Api at "${prefix}": ${type} not found`);
|
|
135
|
+
}
|
|
136
|
+
api.register(this.app, prefix);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async run(): Promise<void> {
|
|
141
|
+
this.releaseHold = this.ctx.acquireHold();
|
|
142
|
+
try {
|
|
143
|
+
await this.app.listen({ host: this.host, port: this.port });
|
|
144
|
+
await this.ctx.emitEvent(`${this.resource.metadata.name}.Listening`, {
|
|
145
|
+
port: this.port,
|
|
146
|
+
host: this.host,
|
|
147
|
+
baseUrl: this.baseUrl,
|
|
148
|
+
mounts: this.resource.mounts,
|
|
149
|
+
openapi: this.resource.openapi,
|
|
150
|
+
});
|
|
151
|
+
} catch (error) {
|
|
152
|
+
await this.app.close();
|
|
153
|
+
if (this.releaseHold) {
|
|
154
|
+
this.releaseHold();
|
|
155
|
+
this.releaseHold = null;
|
|
156
|
+
}
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async teardown(): Promise<void> {
|
|
162
|
+
if (this.releaseHold) {
|
|
163
|
+
this.releaseHold();
|
|
164
|
+
this.releaseHold = null;
|
|
165
|
+
}
|
|
166
|
+
await this.app.close();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function create(
|
|
171
|
+
resource: HttpServerResource,
|
|
172
|
+
ctx: ResourceContext,
|
|
173
|
+
): ResourceInstance | null {
|
|
174
|
+
return new HttpServer(resource, ctx);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function parseType(type: string): { kind: string; name: string } {
|
|
178
|
+
const separator = type.lastIndexOf(".");
|
|
179
|
+
if (separator <= 0 || separator === type.length - 1) {
|
|
180
|
+
return { kind: "", name: "" };
|
|
181
|
+
}
|
|
182
|
+
return { kind: type.slice(0, separator), name: type.slice(separator + 1) };
|
|
183
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../tsconfig.base.json",
|
|
3
|
+
"files": [],
|
|
4
|
+
"include": ["src/**/*.ts", "test/**/*.ts"],
|
|
5
|
+
"compilerOptions": {
|
|
6
|
+
"strict": true,
|
|
7
|
+
"esModuleInterop": true
|
|
8
|
+
},
|
|
9
|
+
"references": [
|
|
10
|
+
{
|
|
11
|
+
"path": "tsconfig.lib.json"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"path": "tsconfig.spec.json"
|
|
15
|
+
}
|
|
16
|
+
]
|
|
17
|
+
}
|