@open-wa/api 5.0.0-alpha.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/.turbo/turbo-build.log +19 -0
- package/.turbo/turbo-test.log +56 -0
- package/CHANGELOG.md +25 -0
- package/LICENSE.md +67 -0
- package/README.md +19 -0
- package/dist/index.cjs +1545 -0
- package/dist/index.d.cts +151 -0
- package/dist/index.d.cts.map +1 -0
- package/package.json +46 -0
- package/src/auth/api-key.ts +28 -0
- package/src/compat/args.ts +1 -0
- package/src/compat/deprecation.ts +35 -0
- package/src/compat/session-path.ts +19 -0
- package/src/createApiMiddleware.ts +184 -0
- package/src/createApiServer.ts +414 -0
- package/src/dashboard/middleware.ts +85 -0
- package/src/docs/openapi.ts +77 -0
- package/src/docs/postman.ts +42 -0
- package/src/events/EventBridge.ts +4 -0
- package/src/events/EventBroadcaster.ts +126 -0
- package/src/execution/kernel.ts +1 -0
- package/src/health/HealthStore.ts +242 -0
- package/src/index.ts +9 -0
- package/src/invoke-client-method.ts +1 -0
- package/src/middleware/rate-limit.ts +30 -0
- package/src/monitoring/elastic.ts +104 -0
- package/src/routes/agent-discovery.ts +150 -0
- package/src/routes/debug.ts +99 -0
- package/src/routes/meta.ts +512 -0
- package/src/types.ts +31 -0
- package/test/mcp-integration.test.ts +142 -0
- package/tsconfig.json +18 -0
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import * as _$hono_types0 from "hono/types";
|
|
2
|
+
import * as _$hono from "hono";
|
|
3
|
+
import { Context, Hono, Next } from "hono";
|
|
4
|
+
import { Config, HttpMethodDefinition } from "@open-wa/schema";
|
|
5
|
+
import { IScreencastPage } from "@open-wa/screencaster/server";
|
|
6
|
+
import { PluginHost } from "@open-wa/core";
|
|
7
|
+
import { ClientMethodDefinitionLike, invokeClientMethod } from "@open-wa/mcp";
|
|
8
|
+
|
|
9
|
+
//#region src/events/EventBridge.d.ts
|
|
10
|
+
interface EventBridge {
|
|
11
|
+
onAny(listener: (event: string, value: any) => void): void;
|
|
12
|
+
offAny(listener: (event: string, value: any) => void): void;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/events/EventBroadcaster.d.ts
|
|
16
|
+
interface SseEventEnvelope {
|
|
17
|
+
id: string;
|
|
18
|
+
event: string;
|
|
19
|
+
payload: unknown;
|
|
20
|
+
ts: number;
|
|
21
|
+
sessionId: string;
|
|
22
|
+
}
|
|
23
|
+
interface EventStreamOptions {
|
|
24
|
+
keepaliveMs?: number;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
topics?: string[];
|
|
27
|
+
}
|
|
28
|
+
declare class EventBroadcaster {
|
|
29
|
+
private readonly encoder;
|
|
30
|
+
private readonly sessionId;
|
|
31
|
+
private nextEventId;
|
|
32
|
+
private nextSubscriberId;
|
|
33
|
+
private subscribers;
|
|
34
|
+
constructor(sessionId?: string);
|
|
35
|
+
broadcast(event: string, payload: unknown): SseEventEnvelope;
|
|
36
|
+
createStream(options?: EventStreamOptions): ReadableStream<Uint8Array>;
|
|
37
|
+
getSubscriberCount(): number;
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/monitoring/elastic.d.ts
|
|
41
|
+
interface ElasticConfig {
|
|
42
|
+
url: string;
|
|
43
|
+
username?: string;
|
|
44
|
+
password?: string;
|
|
45
|
+
bufferSize?: number;
|
|
46
|
+
pipeline?: string;
|
|
47
|
+
indexPrefix?: string;
|
|
48
|
+
}
|
|
49
|
+
interface ElasticDoc {
|
|
50
|
+
timestamp: string;
|
|
51
|
+
level?: 'info' | 'warn' | 'error' | 'debug';
|
|
52
|
+
message: string;
|
|
53
|
+
component?: string;
|
|
54
|
+
sessionId?: string;
|
|
55
|
+
schemaId?: string;
|
|
56
|
+
requestId?: string;
|
|
57
|
+
driver?: string;
|
|
58
|
+
method?: string;
|
|
59
|
+
event?: string;
|
|
60
|
+
duration?: number;
|
|
61
|
+
statusCode?: number;
|
|
62
|
+
userAgent?: string;
|
|
63
|
+
ip?: string;
|
|
64
|
+
[key: string]: any;
|
|
65
|
+
}
|
|
66
|
+
declare class ElasticEmitter {
|
|
67
|
+
private client;
|
|
68
|
+
private config;
|
|
69
|
+
private buffer;
|
|
70
|
+
private flushInterval?;
|
|
71
|
+
constructor(config: ElasticConfig);
|
|
72
|
+
start(): Promise<void>;
|
|
73
|
+
log(logEntry: Omit<ElasticDoc, 'timestamp'>): void;
|
|
74
|
+
flush(): Promise<void>;
|
|
75
|
+
stop(): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/types.d.ts
|
|
79
|
+
type ClientMethodMap = Record<string, (...args: any[]) => Promise<any> | any>;
|
|
80
|
+
type ClientSource = ClientMethodMap | undefined | (() => ClientMethodMap | undefined);
|
|
81
|
+
interface ApiMiddlewareOptions {
|
|
82
|
+
config: Config;
|
|
83
|
+
basePath?: string;
|
|
84
|
+
useSessionIdInPath?: boolean;
|
|
85
|
+
methodDefinitions?: HttpMethodDefinition[];
|
|
86
|
+
elasticEmitter?: ElasticEmitter;
|
|
87
|
+
isSessionConnected?: () => boolean;
|
|
88
|
+
}
|
|
89
|
+
interface ApiServerOptions {
|
|
90
|
+
config: Config;
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/createApiServer.d.ts
|
|
94
|
+
declare class ApiServer {
|
|
95
|
+
private app;
|
|
96
|
+
private config;
|
|
97
|
+
private client;
|
|
98
|
+
private elasticEmitter?;
|
|
99
|
+
private latestQR;
|
|
100
|
+
private screencastManager;
|
|
101
|
+
private injectWebSocket;
|
|
102
|
+
private isDashboardActive;
|
|
103
|
+
private pluginHost?;
|
|
104
|
+
private healthStore;
|
|
105
|
+
private eventBroadcaster;
|
|
106
|
+
private eventBridge?;
|
|
107
|
+
private eventBridgeListener?;
|
|
108
|
+
private readinessProvider?;
|
|
109
|
+
constructor(options: ApiServerOptions);
|
|
110
|
+
setClient(client: ClientMethodMap | undefined): void;
|
|
111
|
+
setEventBridge(bridge: EventBridge): void;
|
|
112
|
+
setReadinessProvider(provider: (() => {
|
|
113
|
+
state?: string;
|
|
114
|
+
status?: string;
|
|
115
|
+
ready: boolean;
|
|
116
|
+
exposureSafe?: boolean;
|
|
117
|
+
pending?: string[];
|
|
118
|
+
blockers?: string[];
|
|
119
|
+
} | undefined) | undefined): void;
|
|
120
|
+
setPage(page: IScreencastPage): Promise<void>;
|
|
121
|
+
clearPage(): Promise<void>;
|
|
122
|
+
setQR(qr: string): void;
|
|
123
|
+
getApp(): Hono<_$hono_types0.BlankEnv, _$hono_types0.BlankSchema, "/">;
|
|
124
|
+
getEventBroadcaster(): EventBroadcaster;
|
|
125
|
+
mountPlugins(pluginHost: PluginHost): void;
|
|
126
|
+
start(): Promise<void>;
|
|
127
|
+
stop(): Promise<void>;
|
|
128
|
+
isDashboardRunning(): boolean;
|
|
129
|
+
private isSessionConnected;
|
|
130
|
+
private setupMiddleware;
|
|
131
|
+
private registerRoutes;
|
|
132
|
+
}
|
|
133
|
+
declare function createApiServer(config: Config): ApiServer;
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/createApiMiddleware.d.ts
|
|
136
|
+
declare function createApiMiddleware(clientSource: ClientSource, options: ApiMiddlewareOptions): Hono<_$hono_types0.BlankEnv, _$hono_types0.BlankSchema, "/">;
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/auth/api-key.d.ts
|
|
139
|
+
declare function apiKeyMiddleware(apiKey: string): (c: Context, next: Next) => Promise<void | (Response & _$hono.TypedResponse<{
|
|
140
|
+
error: string;
|
|
141
|
+
details: string;
|
|
142
|
+
}, 401, "json">)>;
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region src/middleware/rate-limit.d.ts
|
|
145
|
+
declare function rateLimitMiddleware(maxRequests?: number, windowMs?: number): (c: Context, next: Next) => Promise<void | (Response & _$hono.TypedResponse<{
|
|
146
|
+
error: string;
|
|
147
|
+
details: string;
|
|
148
|
+
}, 429, "json">)>;
|
|
149
|
+
//#endregion
|
|
150
|
+
export { type ApiMiddlewareOptions, ApiServer, type ApiServerOptions, type ClientMethodDefinitionLike, type ClientMethodMap, type ClientSource, type ElasticConfig, type ElasticDoc, ElasticEmitter, type EventBridge, EventBroadcaster, type EventStreamOptions, type SseEventEnvelope, apiKeyMiddleware, createApiMiddleware, createApiServer, invokeClientMethod, rateLimitMiddleware };
|
|
151
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/events/EventBridge.ts","../src/events/EventBroadcaster.ts","../src/monitoring/elastic.ts","../src/types.ts","../src/createApiServer.ts","../src/createApiMiddleware.ts","../src/auth/api-key.ts","../src/middleware/rate-limit.ts"],"mappings":";;;;;;;;;UAAiB,WAAA;EACf,KAAA,CAAM,QAAA,GAAW,KAAA,UAAe,KAAA;EAChC,MAAA,CAAO,QAAA,GAAW,KAAA,UAAe,KAAA;AAAA;;;UCFlB,gBAAA;EACf,EAAA;EACA,KAAA;EACA,OAAA;EACA,EAAA;EACA,SAAA;AAAA;AAAA,UAQe,kBAAA;EACf,WAAA;EACA,MAAA,GAAS,WAAA;EACT,MAAA;AAAA;AAAA,cAiBW,gBAAA;EAAA,iBACM,OAAA;EAAA,iBACA,SAAA;EAAA,QACT,WAAA;EAAA,QACA,gBAAA;EAAA,QACA,WAAA;cAEI,SAAA;EAIL,SAAA,CAAU,KAAA,UAAe,OAAA,YAAmB,gBAAA;EAsB5C,YAAA,CAAa,OAAA,GAAS,kBAAA,GAA0B,cAAA,CAAe,UAAA;EAwD/D,kBAAA,CAAA;AAAA;;;UCxHQ,aAAA;EACf,GAAA;EACA,QAAA;EACA,QAAA;EACA,UAAA;EACA,QAAA;EACA,WAAA;AAAA;AAAA,UAGe,UAAA;EACf,SAAA;EACA,KAAA;EACA,OAAA;EACA,SAAA;EACA,SAAA;EACA,QAAA;EACA,SAAA;EACA,MAAA;EACA,MAAA;EACA,KAAA;EACA,QAAA;EACA,UAAA;EACA,SAAA;EACA,EAAA;EAAA,CACC,GAAA;AAAA;AAAA,cAGU,cAAA;EAAA,QACH,MAAA;EAAA,QACA,MAAA;EAAA,QACA,MAAA;EAAA,QACA,aAAA;cAEI,MAAA,EAAQ,aAAA;EAsBP,KAAA,CAAA,GAAS,OAAA;EAOf,GAAA,CAAI,QAAA,EAAU,IAAA,CAAK,UAAA;EAYb,KAAA,CAAA,GAAS,OAAA;EAmBT,IAAA,CAAA,GAAQ,OAAA;AAAA;;;KC1FX,eAAA,GAAkB,MAAA,aAAmB,IAAA,YAAgB,OAAA;AAAA,KACrD,YAAA,GAAe,eAAA,sBAAqC,eAAA;AAAA,UAE/C,oBAAA;EACf,MAAA,EAAQ,MAAA;EACR,QAAA;EACA,kBAAA;EACA,iBAAA,GAAoB,oBAAA;EACpB,cAAA,GAAiB,cAAA;EACjB,kBAAA;AAAA;AAAA,UASe,gBAAA;EACf,MAAA,EAAQ,MAAA;AAAA;;;cCeG,SAAA;EAAA,QACH,GAAA;EAAA,QACA,MAAA;EAAA,QACA,MAAA;EAAA,QACA,cAAA;EAAA,QACA,QAAA;EAAA,QACA,iBAAA;EAAA,QACA,eAAA;EAAA,QACA,iBAAA;EAAA,QACA,UAAA;EAAA,QACA,WAAA;EAAA,QACA,gBAAA;EAAA,QACA,WAAA;EAAA,QACA,mBAAA;EAAA,QACA,iBAAA;cASI,OAAA,EAAS,gBAAA;EAoCd,SAAA,CAAU,MAAA,EAAQ,eAAA;EAIlB,cAAA,CAAe,MAAA,EAAQ,WAAA;EAevB,oBAAA,CACL,QAAA;IACE,KAAA;IACA,MAAA;IACA,KAAA;IACA,YAAA;IACA,OAAA;IACA,QAAA;EAAA;EAUS,OAAA,CAAQ,IAAA,EAAM,eAAA,GAAkB,OAAA;EAOhC,SAAA,CAAA,GAAa,OAAA;EAInB,KAAA,CAAM,EAAA;EAIN,MAAA,CAAA,GAAM,IAAA,CARoB,aAAA,CAQpB,QAAA,EAAA,aAAA,CAAA,WAAA;EAIN,mBAAA,CAAA,GAAmB,gBAAA;EAQnB,YAAA,CAAa,UAAA,EAAY,UAAA;EAYnB,KAAA,CAAA,GAAK,OAAA;EA+CL,IAAA,CAAA,GAAI,OAAA;EAOV,kBAAA,CAAA;EAAA,QAIC,kBAAA;EAAA,QAaA,eAAA;EAAA,QA+BA,cAAA;AAAA;AAAA,iBAwIM,eAAA,CAAgB,MAAA,EAAQ,MAAA,GAAM,SAAA;;;iBC1V9B,mBAAA,CAAoB,YAAA,EAAc,YAAA,EAAc,OAAA,EAAS,oBAAA,GAAoB,IAAA,CAAA,aAAA,CAAA,QAAA,EAAA,aAAA,CAAA,WAAA;;;iBC9D7E,gBAAA,CAAiB,MAAA,YACjB,CAAA,EAAG,OAAA,EAAS,IAAA,EAAM,IAAA,KAAI,OAAA,SAAA,QAAA,GAAA,MAAA,CAAA,aAAA;;;;;;iBCUtB,mBAAA,CAAoB,WAAA,WAAmB,QAAA,aACvC,CAAA,EAAG,OAAA,EAAS,IAAA,EAAM,IAAA,KAAI,OAAA,SAAA,QAAA,GAAA,MAAA,CAAA,aAAA"}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@open-wa/api",
|
|
3
|
+
"version": "5.0.0-alpha.0",
|
|
4
|
+
"description": "Reusable Easy API transport and runtime explorer layer for open-wa",
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"types": "./dist/index.d.cts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"import": "./dist/index.cjs",
|
|
10
|
+
"require": "./dist/index.cjs",
|
|
11
|
+
"types": "./dist/index.d.cts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@elastic/elasticsearch": "^9.2.0",
|
|
16
|
+
"@hono/node-server": "^1.19.12",
|
|
17
|
+
"@hono/node-ws": "^1.3.0",
|
|
18
|
+
"hono": "^4.12.9",
|
|
19
|
+
"tree-kill": "^1.2.2",
|
|
20
|
+
"@open-wa/mcp": "5.0.0-alpha.0",
|
|
21
|
+
"@open-wa/schema": "5.0.0-alpha.0",
|
|
22
|
+
"@open-wa/screencaster": "5.0.0-alpha.0"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"vite": "*"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^25.9.1",
|
|
29
|
+
"typescript": "^6.0.3",
|
|
30
|
+
"vitest": "4.1.2"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "https://github.com/open-wa/wa-automate-nodejs.git"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsdown src/index.ts --format cjs",
|
|
41
|
+
"dev": "tsdown src/index.ts --format cjs --watch",
|
|
42
|
+
"lint": "oxlint src",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:watch": "vitest"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Context, Next } from 'hono';
|
|
2
|
+
import { applyDeprecationHeaders } from '../compat/deprecation';
|
|
3
|
+
|
|
4
|
+
export function apiKeyMiddleware(apiKey: string) {
|
|
5
|
+
return async (c: Context, next: Next) => {
|
|
6
|
+
const queryKey = c.req.query('api_key') || c.req.query('key');
|
|
7
|
+
const headerKey =
|
|
8
|
+
c.req.header('X-API-Key') ||
|
|
9
|
+
c.req.header('api_key') ||
|
|
10
|
+
c.req.header('key');
|
|
11
|
+
|
|
12
|
+
const resolvedKey = queryKey || headerKey;
|
|
13
|
+
|
|
14
|
+
if (c.req.query('api_key') || c.req.query('key') || c.req.header('api_key') || c.req.header('key')) {
|
|
15
|
+
applyDeprecationHeaders(c, {
|
|
16
|
+
route: 'legacy-api-key-alias',
|
|
17
|
+
message: 'Legacy API key aliases are deprecated.',
|
|
18
|
+
replacement: 'X-API-Key header',
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (!resolvedKey || resolvedKey !== apiKey) {
|
|
23
|
+
return c.json({ error: 'Unauthorized', details: 'Invalid or missing API key' }, 401);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return await next();
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { normalizeMethodPayload } from '@open-wa/mcp';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface DeprecationNotice {
|
|
2
|
+
route: string;
|
|
3
|
+
message: string;
|
|
4
|
+
replacement?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function applyDeprecationHeaders(c: any, notice: DeprecationNotice) {
|
|
8
|
+
const parts = [notice.message];
|
|
9
|
+
|
|
10
|
+
if (notice.replacement) {
|
|
11
|
+
parts.push(`Use ${notice.replacement} instead.`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
c.header('X-OpenWA-Deprecated', notice.route);
|
|
15
|
+
c.header('Warning', `299 open-wa "${parts.join(' ')}"`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function deprecatedJson(
|
|
19
|
+
c: any,
|
|
20
|
+
notice: DeprecationNotice,
|
|
21
|
+
status = 200,
|
|
22
|
+
extra: Record<string, unknown> = {}
|
|
23
|
+
) {
|
|
24
|
+
applyDeprecationHeaders(c, notice);
|
|
25
|
+
return c.json(
|
|
26
|
+
{
|
|
27
|
+
deprecated: true,
|
|
28
|
+
route: notice.route,
|
|
29
|
+
message: notice.message,
|
|
30
|
+
replacement: notice.replacement,
|
|
31
|
+
...extra,
|
|
32
|
+
},
|
|
33
|
+
status as any
|
|
34
|
+
);
|
|
35
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function assertSessionPath(
|
|
2
|
+
expectedSessionId: string,
|
|
3
|
+
requestedSessionId: string | undefined,
|
|
4
|
+
useSessionIdInPath: boolean
|
|
5
|
+
): { ok: true } | { ok: false; status: number; error: string } {
|
|
6
|
+
if (!useSessionIdInPath) {
|
|
7
|
+
return { ok: true };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
if (!requestedSessionId) {
|
|
11
|
+
return { ok: false, status: 404, error: 'Session id missing from request path' };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (requestedSessionId !== expectedSessionId) {
|
|
15
|
+
return { ok: false, status: 404, error: `Unknown session path: ${requestedSessionId}` };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return { ok: true };
|
|
19
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema';
|
|
3
|
+
import '@open-wa/schema/methods';
|
|
4
|
+
import { apiKeyMiddleware } from './auth/api-key';
|
|
5
|
+
import { rateLimitMiddleware } from './middleware/rate-limit';
|
|
6
|
+
import { normalizeMethodPayload } from './compat/args';
|
|
7
|
+
import { assertSessionPath } from './compat/session-path';
|
|
8
|
+
import { invokeClientMethod } from './invoke-client-method';
|
|
9
|
+
import { executeCapability } from './execution/kernel';
|
|
10
|
+
import type { ApiMiddlewareOptions, ClientMethodMap, ClientSource } from './types';
|
|
11
|
+
|
|
12
|
+
function resolveClient(clientSource: ClientSource): ClientMethodMap | undefined {
|
|
13
|
+
return typeof clientSource === 'function' ? clientSource() : clientSource;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function readRequestBody(c: any): Promise<Record<string, unknown>> {
|
|
17
|
+
try {
|
|
18
|
+
return await c.req.json();
|
|
19
|
+
} catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function readQueryParams(c: any): Record<string, unknown> {
|
|
25
|
+
const url = new URL(c.req.url);
|
|
26
|
+
return Object.fromEntries(url.searchParams.entries());
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function toLocalPath(path: string, basePath: string): string {
|
|
30
|
+
const normalizedBase = basePath === '/' ? '' : basePath.replace(/\/+$/, '');
|
|
31
|
+
if (!normalizedBase) {
|
|
32
|
+
return path || '/';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (!path.startsWith(normalizedBase)) {
|
|
36
|
+
return path || '/';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const stripped = path.slice(normalizedBase.length);
|
|
40
|
+
return stripped.startsWith('/') ? stripped : `/${stripped}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function createMethodMap(methodDefinitions: HttpMethodDefinition[]) {
|
|
44
|
+
const entries: Array<[string, HttpMethodDefinition]> = [];
|
|
45
|
+
for (const definition of methodDefinitions) {
|
|
46
|
+
for (const name of definition.invocationNames) {
|
|
47
|
+
entries.push([name, definition]);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return new Map(entries);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function shouldBlockForLifecycle(options: ApiMiddlewareOptions): boolean {
|
|
55
|
+
if (!options.isSessionConnected) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (options.config.apiLifecycle === 'immediate') {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return !options.isSessionConnected();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createApiMiddleware(clientSource: ClientSource, options: ApiMiddlewareOptions) {
|
|
67
|
+
const app = new Hono();
|
|
68
|
+
const basePath = options.basePath || '/api';
|
|
69
|
+
const methodDefinitions = options.methodDefinitions || getHttpMethodDefinitions(basePath);
|
|
70
|
+
const methods = createMethodMap(methodDefinitions);
|
|
71
|
+
const useSessionIdInPath = options.useSessionIdInPath || false;
|
|
72
|
+
|
|
73
|
+
app.use('/*', rateLimitMiddleware(100, 60000));
|
|
74
|
+
|
|
75
|
+
if (options.config.apiKey) {
|
|
76
|
+
app.use('/*', apiKeyMiddleware(options.config.apiKey));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const handleInvocation = async (
|
|
80
|
+
c: any,
|
|
81
|
+
routeMethod: string | undefined,
|
|
82
|
+
routeSessionId?: string,
|
|
83
|
+
routeDefinition?: HttpMethodDefinition,
|
|
84
|
+
) => {
|
|
85
|
+
if (shouldBlockForLifecycle(options)) {
|
|
86
|
+
return c.json({ error: 'API not available until the session is truly ready', status: 503 }, 503);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const sessionCheck = assertSessionPath(options.config.sessionId, routeSessionId, useSessionIdInPath);
|
|
90
|
+
|
|
91
|
+
if (!sessionCheck.ok) {
|
|
92
|
+
return c.json({ error: sessionCheck.error }, sessionCheck.status as any);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const startTime = Date.now();
|
|
96
|
+
const query = readQueryParams(c);
|
|
97
|
+
const body = c.req.method === 'GET' || c.req.method === 'DELETE' ? {} : await readRequestBody(c);
|
|
98
|
+
const payload = { ...body, ...query };
|
|
99
|
+
const methodName = routeMethod || routeDefinition?.functionName || (typeof payload.method === 'string' ? payload.method : undefined);
|
|
100
|
+
|
|
101
|
+
if (!methodName) {
|
|
102
|
+
return c.json({ error: 'Missing method name' }, 400);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const definition = routeDefinition || methods.get(methodName);
|
|
106
|
+
|
|
107
|
+
if (!definition) {
|
|
108
|
+
return c.json({ error: `Unknown method: ${methodName}` }, 404);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const result = await executeCapability({
|
|
112
|
+
client: resolveClient(clientSource),
|
|
113
|
+
definition,
|
|
114
|
+
payload,
|
|
115
|
+
elasticEmitter: options.elasticEmitter,
|
|
116
|
+
sessionId: options.config.sessionId,
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
if (result.success) {
|
|
120
|
+
return c.json({ success: true, data: result.data });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return c.json(
|
|
124
|
+
{
|
|
125
|
+
error: result.error,
|
|
126
|
+
details: result.details,
|
|
127
|
+
},
|
|
128
|
+
result.status as any,
|
|
129
|
+
);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const redirectToCanonical = (definition: HttpMethodDefinition, c: any) => {
|
|
133
|
+
c.header('X-OpenWA-Aliases', definition.routeSignatures.join(', '));
|
|
134
|
+
const query = new URL(c.req.url).search;
|
|
135
|
+
return c.redirect(`${definition.path}${query}`, 308);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
for (const definition of methodDefinitions) {
|
|
139
|
+
const localCanonicalPath = toLocalPath(definition.path, basePath);
|
|
140
|
+
app.on(definition.httpMethod, localCanonicalPath, (c) =>
|
|
141
|
+
handleInvocation(c, definition.functionName, undefined, definition),
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
for (const aliasRoute of definition.aliasRoutes) {
|
|
145
|
+
const localAliasPath = toLocalPath(aliasRoute.path, basePath);
|
|
146
|
+
app.on(definition.httpMethod, localAliasPath, (c) => redirectToCanonical(definition, c));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
app.post('/', (c) => handleInvocation(c, undefined));
|
|
151
|
+
app.post('/:method', (c) => handleInvocation(c, c.req.param('method')));
|
|
152
|
+
app.post('/:namespace/:method', (c) => handleInvocation(c, `${c.req.param('namespace')}.${c.req.param('method')}`));
|
|
153
|
+
|
|
154
|
+
if (useSessionIdInPath) {
|
|
155
|
+
app.post('/:sessionId', (c) => handleInvocation(c, undefined, c.req.param('sessionId')));
|
|
156
|
+
app.post('/:sessionId/:method', (c) =>
|
|
157
|
+
handleInvocation(c, c.req.param('method'), c.req.param('sessionId'))
|
|
158
|
+
);
|
|
159
|
+
app.post('/:sessionId/:namespace/:method', (c) =>
|
|
160
|
+
handleInvocation(
|
|
161
|
+
c,
|
|
162
|
+
`${c.req.param('namespace')}.${c.req.param('method')}`,
|
|
163
|
+
c.req.param('sessionId'),
|
|
164
|
+
)
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
app.get('/', (c) =>
|
|
169
|
+
c.json({
|
|
170
|
+
endpoints: methodDefinitions.map((def) => ({
|
|
171
|
+
method: def.httpMethod,
|
|
172
|
+
path: def.path,
|
|
173
|
+
name: def.functionName,
|
|
174
|
+
namespacedName: def.namespacedName,
|
|
175
|
+
description: def.description,
|
|
176
|
+
category: def.namespace,
|
|
177
|
+
aliases: def.aliases,
|
|
178
|
+
routeSignatures: def.routeSignatures,
|
|
179
|
+
})),
|
|
180
|
+
})
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
return app;
|
|
184
|
+
}
|