@uns-kit/api 2.0.40 → 2.0.41

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Aljoša Vister
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Aljoša Vister
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,172 +1,172 @@
1
- # @uns-kit/api
2
-
3
- `@uns-kit/api` exposes Express-based HTTP endpoints for UNS deployments. The plugin attaches a `createApiProxy` method to `UnsProxyProcess`, handles JWT/JWKS access control, automatically publishes API metadata back into the Unified Namespace, and serves a Swagger UI for every registered endpoint.
4
-
5
- Note: Apps built with uns-kit are intended to be managed by the **UNS Datahub controller**.
6
- For the MQTT topic registry published by the API plugin, see `../../docs/uns-topics.md`.
7
-
8
- ## uns-kit in context
9
-
10
- | Package | Description |
11
- | --- | --- |
12
- | [`@uns-kit/core`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-core) | Base runtime (UnsProxyProcess, MQTT helpers, config tooling, gRPC gateway). |
13
- | [`@uns-kit/api`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-api) | Express plugin — HTTP endpoints, JWT/JWKS auth, Swagger, UNS metadata. |
14
- | [`@uns-kit/cron`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-cron) | Cron-driven scheduler that emits UNS events on a fixed cadence. |
15
- | [`@uns-kit/cli`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-cli) | CLI for scaffolding new UNS applications. |
16
-
17
- ## Installation
18
-
19
- ```bash
20
- pnpm add @uns-kit/api
21
- # or
22
- npm install @uns-kit/api
23
- ```
24
-
25
- `@uns-kit/core` must also be present — the plugin augments its `UnsProxyProcess` type.
26
-
27
- ## How it works
28
-
29
- 1. Import `@uns-kit/api` as a side-effect to register the plugin.
30
- 2. Call `process.createApiProxy(instanceName, options)` to start an Express server.
31
- 3. Register endpoints with `api.get(...)` or `api.post(...)`.
32
- 4. Listen to `apiGetEvent` / `apiPostEvent` to handle incoming requests.
33
-
34
- Every registered endpoint is:
35
- - Automatically secured with JWT/JWKS or a shared secret.
36
- - Published to the UNS controller as an API metadata record (topic, host, path, method).
37
- - Added to the Swagger spec served at `/<processName>/<instanceName>/swagger.json`.
38
-
39
- ## GET endpoint example
40
-
41
- ```ts
42
- import UnsProxyProcess from "@uns-kit/core/uns/uns-proxy-process";
43
- import type { UnsEvents } from "@uns-kit/core";
44
- import "@uns-kit/api";
45
- import { type UnsProxyProcessWithApi } from "@uns-kit/api";
46
-
47
- const config = await ConfigFile.loadConfig();
48
- const proc = new UnsProxyProcess(config.infra.host!, { processName: config.uns.processName }) as UnsProxyProcessWithApi;
49
-
50
- const api = await proc.createApiProxy("my-service", {
51
- jwks: { wellKnownJwksUrl: config.uns.jwksWellKnownUrl },
52
- // or for simple/dev deployments: jwtSecret: "CHANGEME"
53
- });
54
-
55
- // Register a GET endpoint
56
- // Signature: api.get(topic, asset, objectType, objectId, attribute, options?)
57
- await api.get(
58
- "enterprise/site/area/line/",
59
- "line-3-furnace",
60
- "energy-resource",
61
- "main-bus",
62
- "current",
63
- {
64
- tags: ["Energy"],
65
- apiDescription: "Current reading for line-3-furnace main-bus",
66
- queryParams: [
67
- { name: "from", type: "string", required: false, description: "Start of time range (ISO 8601)", chatCanonical: "from" },
68
- { name: "to", type: "string", required: false, description: "End of time range (ISO 8601)", chatCanonical: "to" },
69
- { name: "limit", type: "number", required: false, description: "Maximum records", chatCanonical: "limit", defaultValue: 100 },
70
- ],
71
- chatDefaults: { limit: 100 },
72
- }
73
- );
74
-
75
- // Handle incoming GET requests
76
- api.event.on("apiGetEvent", (event: UnsEvents["apiGetEvent"]) => {
77
- const { from, to, limit } = event.req.query;
78
- // fetch your data here
79
- event.res.json({ status: "ok", data: [] });
80
- });
81
- ```
82
-
83
- ## POST endpoint example
84
-
85
- ```ts
86
- // Register a POST endpoint
87
- // Signature: api.post(topic, asset, objectType, objectId, attribute, options?)
88
- await api.post(
89
- "enterprise/site/area/line/",
90
- "line-3-furnace",
91
- "energy-resource",
92
- "main-bus",
93
- "setpoint",
94
- {
95
- tags: ["Energy"],
96
- apiDescription: "Write a new setpoint for line-3-furnace main-bus",
97
- requestBody: {
98
- description: "Setpoint payload",
99
- required: true,
100
- schema: {
101
- type: "object",
102
- required: ["value"],
103
- properties: {
104
- value: { type: "number", description: "Target setpoint value" },
105
- unit: { type: "string", description: "Unit of measurement, e.g. A" },
106
- },
107
- },
108
- },
109
- }
110
- );
111
-
112
- // Handle incoming POST requests — body is pre-parsed JSON
113
- api.event.on("apiPostEvent", (event: UnsEvents["apiPostEvent"]) => {
114
- const { value, unit } = event.req.body;
115
- // write/command logic here
116
- event.res.json({ status: "ok", received: { value, unit } });
117
- });
118
- ```
119
-
120
- ## Endpoint signature
121
-
122
- ```
123
- api.get(topic, asset, objectType, objectId, attribute, options?)
124
- api.post(topic, asset, objectType, objectId, attribute, options?)
125
- ```
126
-
127
- | Parameter | Type | Description |
128
- |---|---|---|
129
- | `topic` | `UnsTopics` | UNS topic path prefix (e.g. `"enterprise/site/area/line/"`) |
130
- | `asset` | `UnsAsset` | Asset identifier (e.g. `"line-3-furnace"`) |
131
- | `objectType` | `UnsObjectType` | UNS object type (e.g. `"energy-resource"`) |
132
- | `objectId` | `UnsObjectId` | Object instance id (e.g. `"main-bus"`) |
133
- | `attribute` | `UnsAttribute` | Attribute name (e.g. `"current"`) |
134
- | `options` | `IGetEndpointOptions` / `IPostEndpointOptions` | Tags, description, query params / request body |
135
-
136
- ## Auth options
137
-
138
- | Option | When to use |
139
- |---|---|
140
- | `jwks.wellKnownJwksUrl` | Production — verifies RS256 tokens from the UNS controller JWKS endpoint |
141
- | `jwks.activeKidUrl` | Optional companion to JWKS — narrows which key ID is active |
142
- | `jwtSecret` | Development / simple deployments — symmetric secret |
143
-
144
- Requests that fail auth return `401 Unauthorized`. Requests whose token `accessRules` do not match the endpoint path return `403 Forbidden`.
145
-
146
- ## Unregistering an endpoint
147
-
148
- ```ts
149
- await api.unregister(topic, asset, objectType, objectId, attribute, "GET");
150
- await api.unregister(topic, asset, objectType, objectId, attribute, "POST");
151
- ```
152
-
153
- This removes the route from Express, the Swagger spec, and the internal UNS endpoint registry.
154
-
155
- ## registerCatchAll (uns-api-global only)
156
-
157
- `api.registerCatchAll()` is reserved for the **uns-api-global** microservice, which acts as a
158
- catch-all gateway for an entire topic namespace. **Regular microservices must not call this** —
159
- use `api.get()` / `api.post()` for per-attribute endpoints instead.
160
-
161
- ## Scripts
162
-
163
- ```bash
164
- pnpm run typecheck
165
- pnpm run build
166
- ```
167
-
168
- `build` emits both JavaScript and type declarations to `dist/`.
169
-
170
- ## License
171
-
172
- MIT © Aljoša Vister
1
+ # @uns-kit/api
2
+
3
+ `@uns-kit/api` exposes Express-based HTTP endpoints for UNS deployments. The plugin attaches a `createApiProxy` method to `UnsProxyProcess`, handles JWT/JWKS access control, automatically publishes API metadata back into the Unified Namespace, and serves a Swagger UI for every registered endpoint.
4
+
5
+ Note: Apps built with uns-kit are intended to be managed by the **UNS Datahub controller**.
6
+ For the MQTT topic registry published by the API plugin, see `../../docs/uns-topics.md`.
7
+
8
+ ## uns-kit in context
9
+
10
+ | Package | Description |
11
+ | --- | --- |
12
+ | [`@uns-kit/core`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-core) | Base runtime (UnsProxyProcess, MQTT helpers, config tooling, gRPC gateway). |
13
+ | [`@uns-kit/api`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-api) | Express plugin — HTTP endpoints, JWT/JWKS auth, Swagger, UNS metadata. |
14
+ | [`@uns-kit/cron`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-cron) | Cron-driven scheduler that emits UNS events on a fixed cadence. |
15
+ | [`@uns-kit/cli`](https://github.com/uns-datahub/uns-kit/tree/main/packages/uns-cli) | CLI for scaffolding new UNS applications. |
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pnpm add @uns-kit/api
21
+ # or
22
+ npm install @uns-kit/api
23
+ ```
24
+
25
+ `@uns-kit/core` must also be present — the plugin augments its `UnsProxyProcess` type.
26
+
27
+ ## How it works
28
+
29
+ 1. Import `@uns-kit/api` as a side-effect to register the plugin.
30
+ 2. Call `process.createApiProxy(instanceName, options)` to start an Express server.
31
+ 3. Register endpoints with `api.get(...)` or `api.post(...)`.
32
+ 4. Listen to `apiGetEvent` / `apiPostEvent` to handle incoming requests.
33
+
34
+ Every registered endpoint is:
35
+ - Automatically secured with JWT/JWKS or a shared secret.
36
+ - Published to the UNS controller as an API metadata record (topic, host, path, method).
37
+ - Added to the Swagger spec served at `/<processName>/<instanceName>/swagger.json`.
38
+
39
+ ## GET endpoint example
40
+
41
+ ```ts
42
+ import UnsProxyProcess from "@uns-kit/core/uns/uns-proxy-process";
43
+ import type { UnsEvents } from "@uns-kit/core";
44
+ import "@uns-kit/api";
45
+ import { type UnsProxyProcessWithApi } from "@uns-kit/api";
46
+
47
+ const config = await ConfigFile.loadConfig();
48
+ const proc = new UnsProxyProcess(config.infra.host!, { processName: config.uns.processName }) as UnsProxyProcessWithApi;
49
+
50
+ const api = await proc.createApiProxy("my-service", {
51
+ jwks: { wellKnownJwksUrl: config.uns.jwksWellKnownUrl },
52
+ // or for simple/dev deployments: jwtSecret: "CHANGEME"
53
+ });
54
+
55
+ // Register a GET endpoint
56
+ // Signature: api.get(topic, asset, objectType, objectId, attribute, options?)
57
+ await api.get(
58
+ "enterprise/site/area/line/",
59
+ "line-3-furnace",
60
+ "energy-resource",
61
+ "main-bus",
62
+ "current",
63
+ {
64
+ tags: ["Energy"],
65
+ apiDescription: "Current reading for line-3-furnace main-bus",
66
+ queryParams: [
67
+ { name: "from", type: "string", required: false, description: "Start of time range (ISO 8601)", chatCanonical: "from" },
68
+ { name: "to", type: "string", required: false, description: "End of time range (ISO 8601)", chatCanonical: "to" },
69
+ { name: "limit", type: "number", required: false, description: "Maximum records", chatCanonical: "limit", defaultValue: 100 },
70
+ ],
71
+ chatDefaults: { limit: 100 },
72
+ }
73
+ );
74
+
75
+ // Handle incoming GET requests
76
+ api.event.on("apiGetEvent", (event: UnsEvents["apiGetEvent"]) => {
77
+ const { from, to, limit } = event.req.query;
78
+ // fetch your data here
79
+ event.res.json({ status: "ok", data: [] });
80
+ });
81
+ ```
82
+
83
+ ## POST endpoint example
84
+
85
+ ```ts
86
+ // Register a POST endpoint
87
+ // Signature: api.post(topic, asset, objectType, objectId, attribute, options?)
88
+ await api.post(
89
+ "enterprise/site/area/line/",
90
+ "line-3-furnace",
91
+ "energy-resource",
92
+ "main-bus",
93
+ "setpoint",
94
+ {
95
+ tags: ["Energy"],
96
+ apiDescription: "Write a new setpoint for line-3-furnace main-bus",
97
+ requestBody: {
98
+ description: "Setpoint payload",
99
+ required: true,
100
+ schema: {
101
+ type: "object",
102
+ required: ["value"],
103
+ properties: {
104
+ value: { type: "number", description: "Target setpoint value" },
105
+ unit: { type: "string", description: "Unit of measurement, e.g. A" },
106
+ },
107
+ },
108
+ },
109
+ }
110
+ );
111
+
112
+ // Handle incoming POST requests — body is pre-parsed JSON
113
+ api.event.on("apiPostEvent", (event: UnsEvents["apiPostEvent"]) => {
114
+ const { value, unit } = event.req.body;
115
+ // write/command logic here
116
+ event.res.json({ status: "ok", received: { value, unit } });
117
+ });
118
+ ```
119
+
120
+ ## Endpoint signature
121
+
122
+ ```
123
+ api.get(topic, asset, objectType, objectId, attribute, options?)
124
+ api.post(topic, asset, objectType, objectId, attribute, options?)
125
+ ```
126
+
127
+ | Parameter | Type | Description |
128
+ |---|---|---|
129
+ | `topic` | `UnsTopics` | UNS topic path prefix (e.g. `"enterprise/site/area/line/"`) |
130
+ | `asset` | `UnsAsset` | Asset identifier (e.g. `"line-3-furnace"`) |
131
+ | `objectType` | `UnsObjectType` | UNS object type (e.g. `"energy-resource"`) |
132
+ | `objectId` | `UnsObjectId` | Object instance id (e.g. `"main-bus"`) |
133
+ | `attribute` | `UnsAttribute` | Attribute name (e.g. `"current"`) |
134
+ | `options` | `IGetEndpointOptions` / `IPostEndpointOptions` | Tags, description, query params / request body |
135
+
136
+ ## Auth options
137
+
138
+ | Option | When to use |
139
+ |---|---|
140
+ | `jwks.wellKnownJwksUrl` | Production — verifies RS256 tokens from the UNS controller JWKS endpoint |
141
+ | `jwks.activeKidUrl` | Optional companion to JWKS — narrows which key ID is active |
142
+ | `jwtSecret` | Development / simple deployments — symmetric secret |
143
+
144
+ Requests that fail auth return `401 Unauthorized`. Requests whose token `accessRules` do not match the endpoint path return `403 Forbidden`.
145
+
146
+ ## Unregistering an endpoint
147
+
148
+ ```ts
149
+ await api.unregister(topic, asset, objectType, objectId, attribute, "GET");
150
+ await api.unregister(topic, asset, objectType, objectId, attribute, "POST");
151
+ ```
152
+
153
+ This removes the route from Express, the Swagger spec, and the internal UNS endpoint registry.
154
+
155
+ ## registerCatchAll (uns-api-global only)
156
+
157
+ `api.registerCatchAll()` is reserved for the **uns-api-global** microservice, which acts as a
158
+ catch-all gateway for an entire topic namespace. **Regular microservices must not call this** —
159
+ use `api.get()` / `api.post()` for per-attribute endpoints instead.
160
+
161
+ ## Scripts
162
+
163
+ ```bash
164
+ pnpm run typecheck
165
+ pnpm run build
166
+ ```
167
+
168
+ `build` emits both JavaScript and type declarations to `dist/`.
169
+
170
+ ## License
171
+
172
+ MIT © Aljoša Vister
@@ -1 +1 @@
1
- export type { IApiProxyOptions, IGetEndpointOptions, QueryParamDef } from "@uns-kit/core/uns/uns-interfaces.js";
1
+ export type { IApiProxyOptions, IGetEndpointOptions, QueryParamDef } from "@uns-kit/core/uns/uns-interfaces.js";
package/dist/app.d.ts CHANGED
@@ -1,48 +1,48 @@
1
- /**
2
- * Module dependencies.
3
- */
4
- import { type Router } from "express";
5
- import * as http from "http";
6
- type MountConfig = {
7
- apiBasePrefix?: string;
8
- swaggerBasePrefix?: string;
9
- disableDefaultApiMount?: boolean;
10
- };
11
- export default class App {
12
- private expressApplication;
13
- server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
14
- private port;
15
- router: Router;
16
- private processName;
17
- private instanceName;
18
- private apiBasePrefix;
19
- private swaggerBasePrefix;
20
- swaggerSpec: {
21
- openapi: string;
22
- info: {
23
- title: string;
24
- version: string;
25
- };
26
- paths: Record<string, any>;
27
- servers?: Array<{
28
- url: string;
29
- }>;
30
- };
31
- private swaggerDocs;
32
- constructor(port: number, processName: string, instanceName: string, appContext?: any, mountConfig?: MountConfig);
33
- static getExternalIPv4(): string | null;
34
- getSwaggerSpec(): {
35
- openapi: string;
36
- info: {
37
- title: string;
38
- version: string;
39
- };
40
- paths: Record<string, any>;
41
- servers?: Array<{
42
- url: string;
43
- }>;
44
- };
45
- registerSwaggerDoc(path: string, doc: Record<string, unknown>): void;
46
- start(): Promise<void>;
47
- }
48
- export {};
1
+ /**
2
+ * Module dependencies.
3
+ */
4
+ import { type Router } from "express";
5
+ import * as http from "http";
6
+ type MountConfig = {
7
+ apiBasePrefix?: string;
8
+ swaggerBasePrefix?: string;
9
+ disableDefaultApiMount?: boolean;
10
+ };
11
+ export default class App {
12
+ private expressApplication;
13
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
14
+ private port;
15
+ router: Router;
16
+ private processName;
17
+ private instanceName;
18
+ private apiBasePrefix;
19
+ private swaggerBasePrefix;
20
+ swaggerSpec: {
21
+ openapi: string;
22
+ info: {
23
+ title: string;
24
+ version: string;
25
+ };
26
+ paths: Record<string, any>;
27
+ servers?: Array<{
28
+ url: string;
29
+ }>;
30
+ };
31
+ private swaggerDocs;
32
+ constructor(port: number, processName: string, instanceName: string, appContext?: any, mountConfig?: MountConfig);
33
+ static getExternalIPv4(): string | null;
34
+ getSwaggerSpec(): {
35
+ openapi: string;
36
+ info: {
37
+ title: string;
38
+ version: string;
39
+ };
40
+ paths: Record<string, any>;
41
+ servers?: Array<{
42
+ url: string;
43
+ }>;
44
+ };
45
+ registerSwaggerDoc(path: string, doc: Record<string, unknown>): void;
46
+ start(): Promise<void>;
47
+ }
48
+ export {};