@sirosfoundation/wmp-js 0.2.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/dist/relay.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * WMP Relay profile — rendezvous relay with offline message queue.
3
+ *
4
+ * Per wmp-transport.md §6.2–6.5, a relay:
5
+ * - Accepts registrations via wmp.relay.register
6
+ * - Routes incoming traffic to registered participants
7
+ * - Queues messages when a participant is offline
8
+ */
9
+ import { Method, ErrorCode } from "./types.js";
10
+ import { WMPError } from "./jsonrpc.js";
11
+ // ---------------------------------------------------------------------------
12
+ // Relay
13
+ // ---------------------------------------------------------------------------
14
+ const DEFAULT_MAX_QUEUE = 1000;
15
+ const DEFAULT_MSG_TTL = 24 * 60 * 60 * 1000; // 24h
16
+ const DEFAULT_REG_TTL = 60 * 60 * 1000; // 1h
17
+ export class Relay {
18
+ maxQueueSize;
19
+ messageTTL;
20
+ registrationTTL;
21
+ onForward;
22
+ registrations = new Map();
23
+ queues = new Map();
24
+ constructor(config) {
25
+ this.maxQueueSize = config?.maxQueueSize ?? DEFAULT_MAX_QUEUE;
26
+ this.messageTTL = config?.messageTTL ?? DEFAULT_MSG_TTL;
27
+ this.registrationTTL = config?.registrationTTL ?? DEFAULT_REG_TTL;
28
+ this.onForward = config?.onForward;
29
+ }
30
+ // --- MethodHandler ---
31
+ methods() {
32
+ return [Method.RelayRegister];
33
+ }
34
+ async handleMethod(method, params) {
35
+ if (method !== Method.RelayRegister) {
36
+ throw new WMPError(ErrorCode.MethodNotFound, `Unknown relay method: ${method}`);
37
+ }
38
+ const p = params;
39
+ if (!p.wmp?.sender) {
40
+ throw new WMPError(ErrorCode.InvalidParams, "sender required");
41
+ }
42
+ const now = Date.now();
43
+ this.registrations.set(p.wmp.sender, {
44
+ participant: p.wmp.sender,
45
+ registeredAt: now,
46
+ expiresAt: now + this.registrationTTL,
47
+ });
48
+ const result = {
49
+ wmp: { version: "0.1" },
50
+ registered: true,
51
+ ttl: Math.floor(this.registrationTTL / 1000),
52
+ };
53
+ return result;
54
+ }
55
+ // --- Relay operations ---
56
+ /** Check if a participant is currently registered. */
57
+ isRegistered(participant) {
58
+ const reg = this.registrations.get(participant);
59
+ return reg !== undefined && Date.now() < reg.expiresAt;
60
+ }
61
+ /** Enqueue a message for offline delivery. */
62
+ enqueue(participant, data) {
63
+ let queue = this.queues.get(participant) ?? [];
64
+ // Purge expired
65
+ const now = Date.now();
66
+ queue = queue.filter((m) => now < m.expiresAt);
67
+ if (queue.length >= this.maxQueueSize) {
68
+ throw new WMPError(ErrorCode.QueueFull, "Message queue is full");
69
+ }
70
+ queue.push({
71
+ data,
72
+ queuedAt: now,
73
+ expiresAt: now + this.messageTTL,
74
+ });
75
+ this.queues.set(participant, queue);
76
+ }
77
+ /** Drain all queued messages for a participant. */
78
+ drain(participant) {
79
+ const queue = this.queues.get(participant);
80
+ if (!queue || queue.length === 0)
81
+ return [];
82
+ const now = Date.now();
83
+ const result = queue.filter((m) => now < m.expiresAt);
84
+ this.queues.delete(participant);
85
+ return result;
86
+ }
87
+ /** Get the number of queued messages. */
88
+ queueLength(participant) {
89
+ return this.queues.get(participant)?.length ?? 0;
90
+ }
91
+ /** Remove a participant's registration. */
92
+ unregister(participant) {
93
+ this.registrations.delete(participant);
94
+ }
95
+ /** Purge expired registrations and messages. */
96
+ purgeExpired() {
97
+ const now = Date.now();
98
+ for (const [id, reg] of this.registrations) {
99
+ if (now >= reg.expiresAt) {
100
+ this.registrations.delete(id);
101
+ }
102
+ }
103
+ for (const [id, queue] of this.queues) {
104
+ const filtered = queue.filter((m) => now < m.expiresAt);
105
+ if (filtered.length === 0) {
106
+ this.queues.delete(id);
107
+ }
108
+ else {
109
+ this.queues.set(id, filtered);
110
+ }
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * WMP JSON Schema validation.
3
+ *
4
+ * Validates WMP messages against the JSON Schema 2020-12 definitions
5
+ * from the WMP specification. Schemas are loaded from the wmp/schema
6
+ * directory at build time (via file paths) or at runtime (via URLs).
7
+ *
8
+ * Usage:
9
+ * import { createValidator } from '@sirosfoundation/wmp-js/schema';
10
+ * const validator = await createValidator(schemaDir);
11
+ * const errors = validator.validateMethod('wmp.session.create', message);
12
+ */
13
+ export interface ValidationError {
14
+ path: string;
15
+ message: string;
16
+ }
17
+ export interface Validator {
18
+ /** Validate a request message for the given method. Returns null if valid. */
19
+ validateMethod(method: string, message: unknown): ValidationError[] | null;
20
+ /** Validate a response for the given method. Returns null if valid. */
21
+ validateResponse(method: string, message: unknown): ValidationError[] | null;
22
+ /** Validate a WMP metadata object. Returns null if valid. */
23
+ validateMetadata(metadata: unknown): ValidationError[] | null;
24
+ /** List methods that have request schemas. */
25
+ methodSchemas(): string[];
26
+ }
27
+ /**
28
+ * Create a schema validator by loading schemas from the filesystem.
29
+ *
30
+ * @param schemaDir Path to the wmp/schema directory containing the JSON Schema files.
31
+ */
32
+ export declare function createValidator(schemaDir: string): Validator;
package/dist/schema.js ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * WMP JSON Schema validation.
3
+ *
4
+ * Validates WMP messages against the JSON Schema 2020-12 definitions
5
+ * from the WMP specification. Schemas are loaded from the wmp/schema
6
+ * directory at build time (via file paths) or at runtime (via URLs).
7
+ *
8
+ * Usage:
9
+ * import { createValidator } from '@sirosfoundation/wmp-js/schema';
10
+ * const validator = await createValidator(schemaDir);
11
+ * const errors = validator.validateMethod('wmp.session.create', message);
12
+ */
13
+ import Ajv2020 from "ajv/dist/2020.js";
14
+ import addFormats from "ajv-formats";
15
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
16
+ import { join, resolve } from "node:path";
17
+ // Method → request schema file mapping.
18
+ const METHOD_SCHEMAS = {
19
+ "wmp.session.create": "methods/session-create-request.json",
20
+ "wmp.session.close": "methods/session-close.json",
21
+ "wmp.flow.start": "methods/flow-start.json",
22
+ "wmp.flow.progress": "methods/flow-progress.json",
23
+ "wmp.flow.action": "methods/flow-action.json",
24
+ "wmp.flow.complete": "methods/flow-complete.json",
25
+ "wmp.flow.error": "methods/flow-error.json",
26
+ "wmp.resolve": "methods/resolve-request.json",
27
+ "wmp.message.deliver": "methods/message-deliver.json",
28
+ "wmp.message.ack": "methods/message-ack.json",
29
+ "wmp.capability.update": "methods/capability-update-request.json",
30
+ };
31
+ // Method → response schema file mapping.
32
+ const RESPONSE_SCHEMAS = {
33
+ "wmp.session.create": "methods/session-create-response.json",
34
+ "wmp.resolve": "methods/resolve-response.json",
35
+ "wmp.capability.list": "methods/capability-list-response.json",
36
+ };
37
+ /**
38
+ * Create a schema validator by loading schemas from the filesystem.
39
+ *
40
+ * @param schemaDir Path to the wmp/schema directory containing the JSON Schema files.
41
+ */
42
+ export function createValidator(schemaDir) {
43
+ const ajv = new Ajv2020({
44
+ strict: false,
45
+ allErrors: true,
46
+ });
47
+ addFormats(ajv);
48
+ const absDir = resolve(schemaDir);
49
+ // Load top-level schemas.
50
+ const topFiles = readdirSync(absDir).filter((f) => f.endsWith(".json"));
51
+ for (const file of topFiles) {
52
+ const content = JSON.parse(readFileSync(join(absDir, file), "utf-8"));
53
+ const id = content.$id || file;
54
+ try {
55
+ ajv.addSchema(content, id);
56
+ if (id !== file)
57
+ ajv.addSchema(content, file);
58
+ }
59
+ catch {
60
+ // Schema may already be added.
61
+ }
62
+ }
63
+ // Load method schemas.
64
+ const methodDir = join(absDir, "methods");
65
+ if (existsSync(methodDir)) {
66
+ const methodFiles = readdirSync(methodDir).filter((f) => f.endsWith(".json"));
67
+ for (const file of methodFiles) {
68
+ const content = JSON.parse(readFileSync(join(methodDir, file), "utf-8"));
69
+ const id = content.$id || `methods/${file}`;
70
+ try {
71
+ ajv.addSchema(content, id);
72
+ if (id !== `methods/${file}`)
73
+ ajv.addSchema(content, `methods/${file}`);
74
+ }
75
+ catch {
76
+ // Schema may already be added.
77
+ }
78
+ }
79
+ }
80
+ function validate(schemaId, data) {
81
+ const valid = ajv.validate(schemaId, data);
82
+ if (valid)
83
+ return null;
84
+ return (ajv.errors ?? []).map((e) => ({
85
+ path: e.instancePath || "/",
86
+ message: e.message ?? "unknown error",
87
+ }));
88
+ }
89
+ return {
90
+ validateMethod(method, message) {
91
+ const schema = METHOD_SCHEMAS[method];
92
+ if (!schema)
93
+ return null; // No schema for this method.
94
+ return validate(schema, message);
95
+ },
96
+ validateResponse(method, message) {
97
+ const schema = RESPONSE_SCHEMAS[method];
98
+ if (!schema)
99
+ return null;
100
+ return validate(schema, message);
101
+ },
102
+ validateMetadata(metadata) {
103
+ return validate("wmp-metadata.json", metadata);
104
+ },
105
+ methodSchemas() {
106
+ return Object.keys(METHOD_SCHEMAS);
107
+ },
108
+ };
109
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Transport interface and implementations — mirrors go-wmp/pkg/wmp/transport.go.
3
+ *
4
+ * Two transport implementations:
5
+ * - WebSocketTransport: bidirectional, persistent connection
6
+ * - HttpSseTransport: POST for sending + SSE EventSource for receiving
7
+ */
8
+ import { type Message } from "./jsonrpc.js";
9
+ export interface TransportEvents {
10
+ message: (msg: Message) => void;
11
+ error: (err: Error) => void;
12
+ close: () => void;
13
+ open: () => void;
14
+ }
15
+ export type TransportEventName = keyof TransportEvents;
16
+ /**
17
+ * Transport abstracts the underlying connection.
18
+ * Mirrors go-wmp Transport but adapted for async JS.
19
+ */
20
+ export interface Transport {
21
+ /** Send a JSON-RPC message over the transport. */
22
+ send(msg: Message): Promise<void>;
23
+ /** Close the transport. */
24
+ close(): void;
25
+ /** Register an event listener. */
26
+ on<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
27
+ /** Remove an event listener. */
28
+ off<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
29
+ }
30
+ type Listener = (...args: unknown[]) => void;
31
+ declare class Emitter {
32
+ private listeners;
33
+ on(event: string, fn: Listener): void;
34
+ off(event: string, fn: Listener): void;
35
+ protected emit(event: string, ...args: unknown[]): void;
36
+ }
37
+ export interface WebSocketTransportOptions {
38
+ /** WebSocket subprotocol. Default: "wmp.v1" */
39
+ protocols?: string | string[];
40
+ }
41
+ /**
42
+ * WebSocket transport — bidirectional, persistent connection.
43
+ * Works in browsers (native WebSocket) and Node.js (e.g., ws package).
44
+ */
45
+ export declare class WebSocketTransport extends Emitter implements Transport {
46
+ private ws;
47
+ constructor(url: string, opts?: WebSocketTransportOptions);
48
+ send(msg: Message): Promise<void>;
49
+ close(): void;
50
+ on<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
51
+ off<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
52
+ }
53
+ export interface HttpSseTransportOptions {
54
+ /** Authorization header value (e.g., "Bearer <token>"). */
55
+ authorization?: string;
56
+ /** Last-Event-ID for SSE replay. */
57
+ lastEventId?: string;
58
+ /** Custom fetch implementation (default: global fetch). */
59
+ fetch?: typeof globalThis.fetch;
60
+ /** Custom EventSource constructor (for polyfills that support headers). */
61
+ EventSource?: typeof EventSource;
62
+ }
63
+ /**
64
+ * HTTP+SSE transport — POST for outgoing, EventSource for incoming.
65
+ *
66
+ * POST endpoint receives JSON-RPC requests.
67
+ * SSE endpoint streams server-initiated JSON-RPC notifications/responses.
68
+ */
69
+ export declare class HttpSseTransport extends Emitter implements Transport {
70
+ private rpcUrl;
71
+ private eventsUrl;
72
+ private authorization?;
73
+ private sessionId?;
74
+ private eventSource;
75
+ private fetchFn;
76
+ private EventSourceCtor;
77
+ private closed;
78
+ constructor(rpcUrl: string, eventsUrl: string, opts?: HttpSseTransportOptions);
79
+ /**
80
+ * Update the authorization header (e.g., after token refresh).
81
+ * Takes effect on the next POST request.
82
+ */
83
+ setAuthorization(authorization: string): void;
84
+ /**
85
+ * Bind a session ID to this transport. The session ID is sent as:
86
+ * - `Wmp-Session-Id` header on POST requests (per WMP spec §4.5)
87
+ * - `session_id` query parameter on SSE connections
88
+ */
89
+ setSessionId(sessionId: string): void;
90
+ /**
91
+ * Connect the SSE stream. Call this after constructing the transport.
92
+ * Separated from the constructor so callers can register listeners first.
93
+ */
94
+ connectSSE(lastEventId?: string): void;
95
+ send(msg: Message): Promise<void>;
96
+ close(): void;
97
+ on<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
98
+ off<K extends TransportEventName>(event: K, listener: TransportEvents[K]): void;
99
+ }
100
+ export {};
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Transport interface and implementations — mirrors go-wmp/pkg/wmp/transport.go.
3
+ *
4
+ * Two transport implementations:
5
+ * - WebSocketTransport: bidirectional, persistent connection
6
+ * - HttpSseTransport: POST for sending + SSE EventSource for receiving
7
+ */
8
+ import { decodeMessage } from "./jsonrpc.js";
9
+ class Emitter {
10
+ listeners = new Map();
11
+ on(event, fn) {
12
+ let set = this.listeners.get(event);
13
+ if (!set) {
14
+ set = new Set();
15
+ this.listeners.set(event, set);
16
+ }
17
+ set.add(fn);
18
+ }
19
+ off(event, fn) {
20
+ this.listeners.get(event)?.delete(fn);
21
+ }
22
+ emit(event, ...args) {
23
+ this.listeners.get(event)?.forEach((fn) => fn(...args));
24
+ }
25
+ }
26
+ /**
27
+ * WebSocket transport — bidirectional, persistent connection.
28
+ * Works in browsers (native WebSocket) and Node.js (e.g., ws package).
29
+ */
30
+ export class WebSocketTransport extends Emitter {
31
+ ws;
32
+ constructor(url, opts) {
33
+ super();
34
+ const protocols = opts?.protocols ?? "wmp.v1";
35
+ this.ws = new WebSocket(url, protocols);
36
+ this.ws.onopen = () => this.emit("open");
37
+ this.ws.onclose = () => this.emit("close");
38
+ this.ws.onerror = (ev) => {
39
+ const err = ev instanceof ErrorEvent ? new Error(ev.message) : new Error("WebSocket error");
40
+ this.emit("error", err);
41
+ };
42
+ this.ws.onmessage = (ev) => {
43
+ try {
44
+ const msg = decodeMessage(String(ev.data));
45
+ this.emit("message", msg);
46
+ }
47
+ catch (err) {
48
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
49
+ }
50
+ };
51
+ }
52
+ async send(msg) {
53
+ if (this.ws.readyState !== WebSocket.OPEN) {
54
+ throw new Error("WebSocket is not open");
55
+ }
56
+ this.ws.send(JSON.stringify(msg));
57
+ }
58
+ close() {
59
+ this.ws.close();
60
+ }
61
+ on(event, listener) {
62
+ super.on(event, listener);
63
+ }
64
+ off(event, listener) {
65
+ super.off(event, listener);
66
+ }
67
+ }
68
+ /**
69
+ * HTTP+SSE transport — POST for outgoing, EventSource for incoming.
70
+ *
71
+ * POST endpoint receives JSON-RPC requests.
72
+ * SSE endpoint streams server-initiated JSON-RPC notifications/responses.
73
+ */
74
+ export class HttpSseTransport extends Emitter {
75
+ rpcUrl;
76
+ eventsUrl;
77
+ authorization;
78
+ sessionId;
79
+ eventSource = null;
80
+ fetchFn;
81
+ EventSourceCtor;
82
+ closed = false;
83
+ constructor(rpcUrl, eventsUrl, opts) {
84
+ super();
85
+ this.rpcUrl = rpcUrl;
86
+ this.eventsUrl = eventsUrl;
87
+ this.authorization = opts?.authorization;
88
+ this.fetchFn = opts?.fetch ?? globalThis.fetch.bind(globalThis);
89
+ this.EventSourceCtor = opts?.EventSource ?? globalThis.EventSource;
90
+ }
91
+ /**
92
+ * Update the authorization header (e.g., after token refresh).
93
+ * Takes effect on the next POST request.
94
+ */
95
+ setAuthorization(authorization) {
96
+ this.authorization = authorization;
97
+ }
98
+ /**
99
+ * Bind a session ID to this transport. The session ID is sent as:
100
+ * - `Wmp-Session-Id` header on POST requests (per WMP spec §4.5)
101
+ * - `session_id` query parameter on SSE connections
102
+ */
103
+ setSessionId(sessionId) {
104
+ this.sessionId = sessionId;
105
+ }
106
+ /**
107
+ * Connect the SSE stream. Call this after constructing the transport.
108
+ * Separated from the constructor so callers can register listeners first.
109
+ */
110
+ connectSSE(lastEventId) {
111
+ // Build the SSE URL with session_id (required for tenant routing)
112
+ // and optional lastEventId for event replay.
113
+ let url = this.eventsUrl;
114
+ if (this.sessionId) {
115
+ const sep = url.includes("?") ? "&" : "?";
116
+ url += `${sep}session_id=${encodeURIComponent(this.sessionId)}`;
117
+ }
118
+ if (lastEventId) {
119
+ const sep = url.includes("?") ? "&" : "?";
120
+ url += `${sep}lastEventId=${encodeURIComponent(lastEventId)}`;
121
+ }
122
+ this.eventSource = new this.EventSourceCtor(url);
123
+ this.eventSource.onopen = () => this.emit("open");
124
+ this.eventSource.onerror = () => {
125
+ if (!this.closed) {
126
+ this.emit("error", new Error("SSE connection error"));
127
+ }
128
+ };
129
+ // WMP events use the "wmp" event type per the spec.
130
+ this.eventSource.addEventListener("wmp", (ev) => {
131
+ try {
132
+ const msg = decodeMessage(ev.data);
133
+ this.emit("message", msg);
134
+ }
135
+ catch (err) {
136
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
137
+ }
138
+ });
139
+ // Also handle default "message" events for compatibility.
140
+ this.eventSource.onmessage = (ev) => {
141
+ try {
142
+ const msg = decodeMessage(ev.data);
143
+ this.emit("message", msg);
144
+ }
145
+ catch (err) {
146
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
147
+ }
148
+ };
149
+ }
150
+ async send(msg) {
151
+ if (this.closed) {
152
+ throw new Error("Transport is closed");
153
+ }
154
+ const headers = {
155
+ "Content-Type": "application/json",
156
+ };
157
+ if (this.authorization) {
158
+ headers["Authorization"] = this.authorization;
159
+ }
160
+ if (this.sessionId) {
161
+ headers["Wmp-Session-Id"] = this.sessionId;
162
+ }
163
+ const resp = await this.fetchFn(this.rpcUrl, {
164
+ method: "POST",
165
+ headers,
166
+ body: JSON.stringify(msg),
167
+ });
168
+ if (!resp.ok) {
169
+ throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
170
+ }
171
+ // If the server returns a JSON-RPC response in the POST body,
172
+ // emit it as an incoming message.
173
+ const ct = resp.headers.get("Content-Type") ?? "";
174
+ if (ct.includes("application/json")) {
175
+ const text = await resp.text();
176
+ if (text.trim()) {
177
+ try {
178
+ const respMsg = decodeMessage(text);
179
+ this.emit("message", respMsg);
180
+ }
181
+ catch {
182
+ // Non-JSON-RPC body — ignore.
183
+ }
184
+ }
185
+ }
186
+ }
187
+ close() {
188
+ this.closed = true;
189
+ this.eventSource?.close();
190
+ this.eventSource = null;
191
+ this.emit("close");
192
+ }
193
+ on(event, listener) {
194
+ super.on(event, listener);
195
+ }
196
+ off(event, listener) {
197
+ super.off(event, listener);
198
+ }
199
+ }