@layr8/sdk 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.
Files changed (46) hide show
  1. package/README.md +582 -0
  2. package/dist/backoff.d.ts +10 -0
  3. package/dist/backoff.d.ts.map +1 -0
  4. package/dist/backoff.js +20 -0
  5. package/dist/backoff.js.map +1 -0
  6. package/dist/channel.d.ts +88 -0
  7. package/dist/channel.d.ts.map +1 -0
  8. package/dist/channel.js +522 -0
  9. package/dist/channel.js.map +1 -0
  10. package/dist/client.d.ts +119 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +509 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/config.d.ts +49 -0
  15. package/dist/config.d.ts.map +1 -0
  16. package/dist/config.js +42 -0
  17. package/dist/config.js.map +1 -0
  18. package/dist/credentials.d.ts +55 -0
  19. package/dist/credentials.d.ts.map +1 -0
  20. package/dist/credentials.js +5 -0
  21. package/dist/credentials.js.map +1 -0
  22. package/dist/errors.d.ts +91 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +132 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/handler.d.ts +28 -0
  27. package/dist/handler.d.ts.map +1 -0
  28. package/dist/handler.js +51 -0
  29. package/dist/handler.js.map +1 -0
  30. package/dist/index.d.ts +16 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +8 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/message.d.ts +67 -0
  35. package/dist/message.d.ts.map +1 -0
  36. package/dist/message.js +77 -0
  37. package/dist/message.js.map +1 -0
  38. package/dist/presentations.d.ts +24 -0
  39. package/dist/presentations.d.ts.map +1 -0
  40. package/dist/presentations.js +5 -0
  41. package/dist/presentations.js.map +1 -0
  42. package/dist/rest.d.ts +33 -0
  43. package/dist/rest.d.ts.map +1 -0
  44. package/dist/rest.js +150 -0
  45. package/dist/rest.js.map +1 -0
  46. package/package.json +38 -0
@@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M,CAAC,QAAQ,CAAC,mBAAmB,CAAU;IACrD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAU;IAEjD,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;gBAGzB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EAC/B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,gBAAgB,EAC3B,OAAO,CAAC,EAAE,OAAO;IAOb,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;YAKzD,IAAI;YAyDJ,IAAI;IAoElB,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC;IA6C3D,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAaxD,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI;IAI5B,WAAW,IAAI,MAAM;IAIrB,sFAAsF;IACtF,aAAa,IAAI,OAAO;IAIxB,KAAK,IAAI,IAAI;IAgCb,OAAO,CAAC,aAAa;IAgDrB,OAAO,CAAC,aAAa;IAmCrB,OAAO,CAAC,cAAc;IAgCtB;;;;;;OAMG;IACH,OAAO,CAAC,eAAe;IAavB,OAAO,CAAC,WAAW;IAiBnB,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,kBAAkB;YAYZ,aAAa;IAmC3B,OAAO,CAAC,iBAAiB;IAQzB,OAAO,CAAC,OAAO;IAKf,OAAO,CAAC,QAAQ;CAMjB"}
@@ -0,0 +1,522 @@
1
+ import WebSocket from "ws";
2
+ import { Backoff } from "./backoff.js";
3
+ import { DEFAULT_DID_SPEC } from "./config.js";
4
+ import { ConnectionError, NotConnectedError } from "./errors.js";
5
+ function marshalPhoenixMsg(msg) {
6
+ return JSON.stringify([
7
+ msg.joinRef,
8
+ msg.ref,
9
+ msg.topic,
10
+ msg.event,
11
+ msg.payload,
12
+ ]);
13
+ }
14
+ function unmarshalPhoenixMsg(data) {
15
+ const arr = JSON.parse(data);
16
+ if (!Array.isArray(arr) || arr.length !== 5) {
17
+ throw new Error(`expected 5-element array, got ${Array.isArray(arr) ? arr.length : typeof arr}`);
18
+ }
19
+ return {
20
+ joinRef: arr[0] ?? null,
21
+ ref: arr[1] ?? null,
22
+ topic: arr[2],
23
+ event: arr[3],
24
+ payload: arr[4],
25
+ };
26
+ }
27
+ /** Returns true if host is "localhost" or a subdomain of it (RFC 6761). */
28
+ function isLocalhost(host) {
29
+ return host === "localhost" || host.endsWith(".localhost");
30
+ }
31
+ /**
32
+ * Rewrite a WebSocket URL so that *.localhost hostnames resolve to 127.0.0.1.
33
+ * Returns [rewrittenUrl, hostHeader] — hostHeader is set when rewriting occurred.
34
+ */
35
+ function rewriteLocalhostUrl(wsUrl) {
36
+ const parsed = new URL(wsUrl);
37
+ if (isLocalhost(parsed.hostname)) {
38
+ const hostHeader = parsed.host; // includes port if present
39
+ parsed.hostname = "127.0.0.1";
40
+ return [parsed.toString(), hostHeader];
41
+ }
42
+ return [wsUrl, undefined];
43
+ }
44
+ /**
45
+ * Phoenix Channel transport over WebSocket.
46
+ * Implements the same protocol as the Go SDK's phoenixChannel.
47
+ */
48
+ export class PhoenixChannel {
49
+ wsUrl;
50
+ apiKey;
51
+ ws = null;
52
+ refCounter = 0;
53
+ joinRef = "";
54
+ topic;
55
+ callbacks;
56
+ pendingJoinResolve = null;
57
+ closed = false;
58
+ reconnecting = false;
59
+ protocols = [];
60
+ heartbeatTimer = null;
61
+ /**
62
+ * Monotonic timestamp (Date.now()) of the most recently observed inbound
63
+ * frame — any message, pong, or phx_reply. Used by the Phoenix-level
64
+ * watchdog in startHeartbeat to detect "TCP healthy but Phoenix Channel
65
+ * GenServer hung" failures: when the heartbeat tick observes no frames
66
+ * for HEARTBEAT_MAX_SILENT_MS, it forces a close that the existing
67
+ * reconnect path picks up.
68
+ */
69
+ lastFrameAt = Date.now();
70
+ /**
71
+ * Timer that periodically emits a WS-level `{:ping, _}` frame. Independent
72
+ * of the Phoenix heartbeat — covers the TCP / NAT / LB half-dead case
73
+ * where the connection is unilaterally killed without a FIN.
74
+ */
75
+ wsPingTimer = null;
76
+ /**
77
+ * Timer armed each time we emit a WS ping. Cleared on any inbound frame
78
+ * (pong, message, phx_reply — anything proves liveness). If it fires we
79
+ * force-close the WS so the existing reconnect path takes over.
80
+ */
81
+ pongWaitTimer = null;
82
+ assignedDIDVal = "";
83
+ pendingRefs = new Map();
84
+ // Liveness detection constants. The Phoenix-level watchdog (HEARTBEAT_*)
85
+ // covers application-layer hangs; the WS-level ping/pong (WS_PING_* /
86
+ // PONG_WAIT_*) covers transport-layer hangs. Independent layers — both
87
+ // are needed because cowboy auto-pongs at the WS layer even when the
88
+ // Phoenix Channel GenServer has stopped processing.
89
+ //
90
+ // 75 000 ms = 2.5× heartbeat interval: tolerates one missed reply, trips
91
+ // on two consecutive misses.
92
+ static HEARTBEAT_INTERVAL_MS = 30_000;
93
+ static HEARTBEAT_MAX_SILENT_MS = 75_000;
94
+ static WS_PING_INTERVAL_MS = 25_000;
95
+ static WS_PONG_WAIT_MS = 35_000;
96
+ replyProtocolEnabled = false;
97
+ didSpec;
98
+ constructor(wsUrl, apiKey, agentDid, callbacks, didSpec) {
99
+ this.wsUrl = wsUrl;
100
+ this.apiKey = apiKey;
101
+ this.topic = `plugins:${agentDid}`;
102
+ this.callbacks = callbacks;
103
+ this.didSpec = { ...DEFAULT_DID_SPEC, ...didSpec, verificationMethods: didSpec?.verificationMethods ?? DEFAULT_DID_SPEC.verificationMethods };
104
+ }
105
+ async connect(protocols, signal) {
106
+ this.protocols = protocols;
107
+ return this.dial(signal);
108
+ }
109
+ async dial(signal) {
110
+ this.refCounter = 0;
111
+ const parsed = new URL(this.wsUrl);
112
+ parsed.searchParams.set("api_key", this.apiKey);
113
+ parsed.searchParams.set("vsn", "2.0.0");
114
+ const [url, hostHeader] = rewriteLocalhostUrl(parsed.toString());
115
+ const wsOpts = {
116
+ handshakeTimeout: 10_000,
117
+ };
118
+ if (hostHeader) {
119
+ wsOpts.headers = { Host: hostHeader };
120
+ }
121
+ return new Promise((resolve, reject) => {
122
+ if (signal?.aborted) {
123
+ reject(signal.reason ?? new Error("aborted"));
124
+ return;
125
+ }
126
+ const ws = new WebSocket(url, wsOpts);
127
+ const onAbort = () => {
128
+ ws.close();
129
+ reject(signal.reason ?? new Error("aborted"));
130
+ };
131
+ signal?.addEventListener("abort", onAbort, { once: true });
132
+ ws.on("error", (err) => {
133
+ signal?.removeEventListener("abort", onAbort);
134
+ reject(new ConnectionError(this.wsUrl, err.message));
135
+ });
136
+ ws.on("open", async () => {
137
+ signal?.removeEventListener("abort", onAbort);
138
+ this.ws = ws;
139
+ // Reset the watchdog clock so the first heartbeat tick after
140
+ // (re)connect measures silence from "just now", not from before
141
+ // the disconnect.
142
+ this.lastFrameAt = Date.now();
143
+ this.setupReadLoop();
144
+ this.startHeartbeat();
145
+ this.startWsPingLoop();
146
+ try {
147
+ await this.join(this.protocols, signal);
148
+ resolve();
149
+ }
150
+ catch (err) {
151
+ ws.close();
152
+ reject(err);
153
+ }
154
+ });
155
+ });
156
+ }
157
+ async join(protocols, signal) {
158
+ const ref = this.nextRef();
159
+ this.joinRef = ref;
160
+ const spec = this.didSpec;
161
+ const didSpecPayload = {
162
+ mode: spec.mode,
163
+ storage: spec.storage,
164
+ type: spec.type,
165
+ verificationMethods: spec.verificationMethods,
166
+ };
167
+ if (spec.label) {
168
+ didSpecPayload.label = spec.label;
169
+ }
170
+ if (spec.controller) {
171
+ didSpecPayload.controller = spec.controller;
172
+ }
173
+ const joinPayload = {
174
+ payload_types: protocols,
175
+ did_spec: didSpecPayload,
176
+ reply_protocol: true,
177
+ };
178
+ return new Promise((resolve, reject) => {
179
+ if (signal?.aborted) {
180
+ reject(signal.reason ?? new Error("aborted"));
181
+ return;
182
+ }
183
+ const onAbort = () => {
184
+ this.pendingJoinResolve = null;
185
+ reject(signal.reason ?? new Error("aborted"));
186
+ };
187
+ signal?.addEventListener("abort", onAbort, { once: true });
188
+ this.pendingJoinResolve = (payload) => {
189
+ signal?.removeEventListener("abort", onAbort);
190
+ const reply = payload;
191
+ if (reply.status !== "ok") {
192
+ const reason = reply.response?.reason ?? `join rejected: ${reply.status}`;
193
+ reject(new ConnectionError(this.wsUrl, reason));
194
+ return;
195
+ }
196
+ if (reply.response?.did) {
197
+ this.assignedDIDVal = reply.response.did;
198
+ }
199
+ const caps = reply.response?.capabilities ?? [];
200
+ this.replyProtocolEnabled = caps.includes("reply_protocol/1");
201
+ resolve();
202
+ };
203
+ this.writeMsg({
204
+ joinRef: ref,
205
+ ref,
206
+ topic: this.topic,
207
+ event: "phx_join",
208
+ payload: joinPayload,
209
+ });
210
+ });
211
+ }
212
+ send(event, payload) {
213
+ if (this.reconnecting) {
214
+ return Promise.reject(new NotConnectedError());
215
+ }
216
+ const ref = this.nextRef();
217
+ return new Promise((resolve, reject) => {
218
+ const timer = setTimeout(() => {
219
+ const pending = this.pendingRefs.get(ref);
220
+ if (pending) {
221
+ this.pendingRefs.delete(ref);
222
+ reject(new Error("server reply timeout"));
223
+ }
224
+ }, 15_000); // 15 second timeout for server reply
225
+ this.pendingRefs.set(ref, {
226
+ resolve: (reply) => {
227
+ clearTimeout(timer);
228
+ this.pendingRefs.delete(ref);
229
+ resolve(reply);
230
+ },
231
+ reject: (err) => {
232
+ clearTimeout(timer);
233
+ this.pendingRefs.delete(ref);
234
+ reject(err);
235
+ },
236
+ timer,
237
+ });
238
+ try {
239
+ this.writeMsg({
240
+ joinRef: null,
241
+ ref,
242
+ topic: this.topic,
243
+ event,
244
+ payload,
245
+ });
246
+ }
247
+ catch (err) {
248
+ clearTimeout(timer);
249
+ this.pendingRefs.delete(ref);
250
+ reject(err);
251
+ }
252
+ });
253
+ }
254
+ sendFireAndForget(event, payload) {
255
+ if (this.reconnecting) {
256
+ throw new NotConnectedError();
257
+ }
258
+ this.writeMsg({
259
+ joinRef: null,
260
+ ref: this.nextRef(),
261
+ topic: this.topic,
262
+ event,
263
+ payload,
264
+ });
265
+ }
266
+ sendAck(ids) {
267
+ this.sendFireAndForget("ack", { ids });
268
+ }
269
+ assignedDID() {
270
+ return this.assignedDIDVal;
271
+ }
272
+ /** Whether the server supports the reply protocol (capability negotiated at join). */
273
+ replyProtocol() {
274
+ return this.replyProtocolEnabled;
275
+ }
276
+ close() {
277
+ if (this.closed)
278
+ return;
279
+ this.closed = true;
280
+ this.reconnecting = false;
281
+ this.stopLivenessTimers();
282
+ // Reject all pending refs
283
+ for (const [, pending] of this.pendingRefs) {
284
+ clearTimeout(pending.timer);
285
+ pending.reject(new Error("channel closed"));
286
+ }
287
+ this.pendingRefs.clear();
288
+ if (this.ws) {
289
+ // Send phx_leave before closing
290
+ try {
291
+ this.writeMsg({
292
+ joinRef: null,
293
+ ref: this.nextRef(),
294
+ topic: this.topic,
295
+ event: "phx_leave",
296
+ payload: {},
297
+ });
298
+ }
299
+ catch {
300
+ // ignore write errors during close
301
+ }
302
+ this.ws.close();
303
+ this.ws = null;
304
+ }
305
+ }
306
+ setupReadLoop() {
307
+ if (!this.ws)
308
+ return;
309
+ this.ws.on("message", (data) => {
310
+ // Any inbound frame proves the connection is alive end-to-end —
311
+ // disarm both watchdogs before dispatch. Heartbeat ack, message
312
+ // event, phx_reply, phx_error, all count.
313
+ this.lastFrameAt = Date.now();
314
+ this.disarmPongWait();
315
+ try {
316
+ const msg = unmarshalPhoenixMsg(data.toString());
317
+ this.handleInbound(msg);
318
+ }
319
+ catch {
320
+ // Phoenix wire format parse failure — not a DIDComm error.
321
+ // Transport-level noise (e.g., truncated frames), matches Go SDK behavior.
322
+ }
323
+ });
324
+ // WS-level pong arrival in response to our ping (or unsolicited).
325
+ // Either way, the transport is alive — clear pong_wait. We also
326
+ // bump lastFrameAt for the Phoenix-level watchdog, since a pong
327
+ // round-trip proves cowboy + TCP are healthy.
328
+ this.ws.on("pong", () => {
329
+ this.lastFrameAt = Date.now();
330
+ this.disarmPongWait();
331
+ });
332
+ this.ws.on("close", () => {
333
+ if (!this.closed) {
334
+ this.rejectPendingRefs();
335
+ if (this.callbacks.onDisconnect) {
336
+ this.callbacks.onDisconnect(new Error("WebSocket closed"));
337
+ }
338
+ this.reconnectLoop();
339
+ }
340
+ });
341
+ this.ws.on("error", (err) => {
342
+ if (!this.closed) {
343
+ this.rejectPendingRefs();
344
+ if (this.callbacks.onDisconnect) {
345
+ this.callbacks.onDisconnect(err);
346
+ }
347
+ this.reconnectLoop();
348
+ }
349
+ });
350
+ }
351
+ handleInbound(msg) {
352
+ switch (msg.event) {
353
+ case "phx_reply":
354
+ // Join reply
355
+ if (this.pendingJoinResolve && msg.ref === this.joinRef) {
356
+ const resolve = this.pendingJoinResolve;
357
+ this.pendingJoinResolve = null;
358
+ resolve(msg.payload);
359
+ return;
360
+ }
361
+ // Message send reply (ref tracking)
362
+ if (msg.ref) {
363
+ const pending = this.pendingRefs.get(msg.ref);
364
+ if (pending) {
365
+ const reply = msg.payload;
366
+ pending.resolve({
367
+ status: reply?.status ?? "",
368
+ reason: reply?.response?.reason ?? "",
369
+ });
370
+ }
371
+ }
372
+ break;
373
+ case "message":
374
+ this.callbacks.onMessage(msg.payload);
375
+ break;
376
+ case "phx_error":
377
+ case "phx_close":
378
+ if (this.callbacks.onDisconnect) {
379
+ this.callbacks.onDisconnect(new Error(`channel ${msg.event}`));
380
+ }
381
+ break;
382
+ }
383
+ }
384
+ startHeartbeat() {
385
+ this.heartbeatTimer = setInterval(() => {
386
+ if (this.closed || !this.ws)
387
+ return;
388
+ const silentMs = Date.now() - this.lastFrameAt;
389
+ if (silentMs > PhoenixChannel.HEARTBEAT_MAX_SILENT_MS) {
390
+ // Application-layer hang: cloud-node's Phoenix Channel GenServer
391
+ // is no longer responding (we'd have seen heartbeat acks or
392
+ // other frames by now). Terminate the socket and let the
393
+ // existing reconnect path take over.
394
+ try {
395
+ this.ws.terminate();
396
+ }
397
+ catch {
398
+ // ignore
399
+ }
400
+ return;
401
+ }
402
+ try {
403
+ this.writeMsg({
404
+ joinRef: null,
405
+ ref: this.nextRef(),
406
+ topic: "phoenix",
407
+ event: "heartbeat",
408
+ payload: {},
409
+ });
410
+ }
411
+ catch {
412
+ // heartbeat write failed — connection likely dead
413
+ }
414
+ }, PhoenixChannel.HEARTBEAT_INTERVAL_MS);
415
+ }
416
+ /**
417
+ * WS-level ping every WS_PING_INTERVAL_MS. Cowboy (Phoenix's HTTP/WS
418
+ * server) auto-pongs at the protocol layer — even if the application
419
+ * Channel is hung. When the underlying TCP / NAT / LB has silently
420
+ * dropped the connection, ping write may succeed locally but no pong
421
+ * comes back; pongWaitTimer fires and we force-close.
422
+ */
423
+ startWsPingLoop() {
424
+ this.wsPingTimer = setInterval(() => {
425
+ if (this.closed || !this.ws)
426
+ return;
427
+ try {
428
+ this.ws.ping();
429
+ this.armPongWait();
430
+ }
431
+ catch {
432
+ // ping write failed — connection likely dead; let
433
+ // ws.on("error") path handle it
434
+ }
435
+ }, PhoenixChannel.WS_PING_INTERVAL_MS);
436
+ }
437
+ armPongWait() {
438
+ if (this.pongWaitTimer) {
439
+ clearTimeout(this.pongWaitTimer);
440
+ }
441
+ this.pongWaitTimer = setTimeout(() => {
442
+ this.pongWaitTimer = null;
443
+ if (this.closed || !this.ws)
444
+ return;
445
+ // No pong (or any frame) within WS_PONG_WAIT_MS of the last ping —
446
+ // transport is dead. Terminate; reconnect path takes over.
447
+ try {
448
+ this.ws.terminate();
449
+ }
450
+ catch {
451
+ // ignore
452
+ }
453
+ }, PhoenixChannel.WS_PONG_WAIT_MS);
454
+ }
455
+ disarmPongWait() {
456
+ if (this.pongWaitTimer) {
457
+ clearTimeout(this.pongWaitTimer);
458
+ this.pongWaitTimer = null;
459
+ }
460
+ }
461
+ stopLivenessTimers() {
462
+ if (this.heartbeatTimer) {
463
+ clearInterval(this.heartbeatTimer);
464
+ this.heartbeatTimer = null;
465
+ }
466
+ if (this.wsPingTimer) {
467
+ clearInterval(this.wsPingTimer);
468
+ this.wsPingTimer = null;
469
+ }
470
+ this.disarmPongWait();
471
+ }
472
+ async reconnectLoop() {
473
+ if (this.reconnecting)
474
+ return;
475
+ this.reconnecting = true;
476
+ // Close existing ws
477
+ if (this.ws) {
478
+ this.ws.removeAllListeners();
479
+ this.ws.close();
480
+ this.ws = null;
481
+ }
482
+ // Stop all liveness timers — dial() will re-arm them after the new
483
+ // socket opens.
484
+ this.stopLivenessTimers();
485
+ const bo = new Backoff(1000, 30000);
486
+ while (!this.closed) {
487
+ const delay = bo.next();
488
+ await new Promise(resolve => setTimeout(resolve, delay));
489
+ if (this.closed)
490
+ return;
491
+ try {
492
+ await this.dial();
493
+ this.reconnecting = false;
494
+ if (this.callbacks.onReconnect) {
495
+ this.callbacks.onReconnect();
496
+ }
497
+ return;
498
+ }
499
+ catch {
500
+ // will retry
501
+ }
502
+ }
503
+ }
504
+ rejectPendingRefs() {
505
+ for (const [, pending] of this.pendingRefs) {
506
+ clearTimeout(pending.timer);
507
+ pending.reject(new Error("disconnected"));
508
+ }
509
+ this.pendingRefs.clear();
510
+ }
511
+ nextRef() {
512
+ this.refCounter++;
513
+ return String(this.refCounter);
514
+ }
515
+ writeMsg(msg) {
516
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
517
+ throw new NotConnectedError();
518
+ }
519
+ this.ws.send(marshalPhoenixMsg(msg));
520
+ }
521
+ }
522
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,IAAI,CAAC;AAC3B,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAA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ACf,CAAC;QACH,CAAC;IACH,CAAC;IAEO,iBAAiB;QACvB,KAAK,MAAM,CAAC,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YAC3C,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5B,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;QAC5C,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC3B,CAAC;IAEO,OAAO;QACb,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACjC,CAAC;IAEO,QAAQ,CAAC,GAAmB;QAClC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EAAE,CAAC;YACtD,MAAM,IAAI,iBAAiB,EAAE,CAAC;QAChC,CAAC;QACD,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC;IACvC,CAAC"}
@@ -0,0 +1,119 @@
1
+ import { EventEmitter } from "node:events";
2
+ import type { Config } from "./config.js";
3
+ import type { Credential, SignCredentialOptions, VerifiedCredential, VerifyCredentialOptions, StoreCredentialOptions, StoredCredential, ListCredentialsOptions } from "./credentials.js";
4
+ import type { SignPresentationOptions, VerifiedPresentation, VerifyPresentationOptions } from "./presentations.js";
5
+ import type { ErrorHandler } from "./errors.js";
6
+ import type { HandlerFn, HandlerOptions } from "./handler.js";
7
+ import type { Message } from "./message.js";
8
+ /** Options for request(). */
9
+ export interface RequestOptions {
10
+ /** Set pthid for nested thread correlation. */
11
+ parentThread?: string;
12
+ /** AbortSignal for timeout/cancellation control. */
13
+ signal?: AbortSignal;
14
+ }
15
+ /** Options for send(). */
16
+ export interface SendOptions {
17
+ /** Skip waiting for server acknowledgment. */
18
+ fireAndForget?: boolean;
19
+ }
20
+ /**
21
+ * Layr8Client is the main entry point for interacting with the Layr8 platform.
22
+ *
23
+ * Lifecycle: new Layr8Client → handle (register handlers) → connect → ... → close
24
+ *
25
+ * Extends EventEmitter for "disconnect" and "reconnect" events.
26
+ */
27
+ export declare class Layr8Client extends EventEmitter {
28
+ private readonly cfg;
29
+ private readonly onError;
30
+ private readonly registry;
31
+ private channel;
32
+ private connected;
33
+ private isClosed;
34
+ private agentDid;
35
+ private readonly rest;
36
+ /** Correlation map for Request/Response pattern: threadId → {resolve, reject} */
37
+ private readonly pending;
38
+ constructor(onError: ErrorHandler, cfg?: Config);
39
+ /** The agent's DID — either provided in Config or assigned by the node on connect(). */
40
+ get did(): string;
41
+ /**
42
+ * Register a handler for a DIDComm message type.
43
+ * Must be called BEFORE connect(). Throws AlreadyConnectedError after.
44
+ */
45
+ handle(msgType: string, fn: HandlerFn, opts?: HandlerOptions): void;
46
+ /**
47
+ * Register a catch-all handler for any message type not matched by a specific handler.
48
+ * Must be called BEFORE connect(). Throws AlreadyConnectedError after.
49
+ */
50
+ handleAll(fn: HandlerFn, opts?: HandlerOptions): void;
51
+ /**
52
+ * EventEmitter.emit() is synchronous and propagates listener exceptions.
53
+ * For SDK-internal events that fire on hot paths (inbound dispatch,
54
+ * outbound send), a throwing listener must NOT break the path — otherwise
55
+ * a pending request() can hang indefinitely. Route any throw to onError.
56
+ */
57
+ private safeEmit;
58
+ /**
59
+ * Establish WebSocket connection and join the Phoenix Channel
60
+ * with protocols derived from registered handlers.
61
+ */
62
+ connect(signal?: AbortSignal): Promise<void>;
63
+ /** Gracefully shut down the client connection. */
64
+ close(): Promise<void>;
65
+ /**
66
+ * Send a message. By default waits for server acknowledgment.
67
+ * Pass `{ fireAndForget: true }` to skip waiting for the server reply.
68
+ */
69
+ send(msg: Partial<Message>, opts?: SendOptions): Promise<void>;
70
+ /**
71
+ * Send a message and wait for a correlated response.
72
+ * Throws on timeout (AbortSignal), ProblemReportError, or NotConnectedError.
73
+ */
74
+ request(msg: Partial<Message>, opts?: RequestOptions): Promise<Message>;
75
+ /**
76
+ * Sign a W3C Verifiable Credential using the issuer's assertion key.
77
+ * Defaults: issuer = client.did, format = "compact_jwt".
78
+ */
79
+ signCredential(credential: Credential, options?: SignCredentialOptions): Promise<string>;
80
+ /**
81
+ * Verify a signed credential using the verifier DID's assertion key.
82
+ * Defaults: verifier = client.did.
83
+ */
84
+ verifyCredential(signedCredential: string, options?: VerifyCredentialOptions): Promise<VerifiedCredential>;
85
+ /**
86
+ * Store a signed credential JWT for a holder.
87
+ * Defaults: holder = client.did.
88
+ */
89
+ storeCredential(credentialJwt: string, options?: StoreCredentialOptions): Promise<StoredCredential>;
90
+ /**
91
+ * List all stored credentials for a holder.
92
+ * Defaults: holder = client.did.
93
+ */
94
+ listCredentials(options?: ListCredentialsOptions): Promise<StoredCredential[]>;
95
+ /** Retrieve a stored credential by ID. */
96
+ getCredential(credentialId: string): Promise<StoredCredential>;
97
+ /**
98
+ * Sign a W3C Verifiable Presentation wrapping one or more signed credentials.
99
+ * Uses the holder's authentication key (not assertion key).
100
+ * Defaults: holder = client.did, format = "compact_jwt".
101
+ */
102
+ signPresentation(credentials: string[], options?: SignPresentationOptions): Promise<string>;
103
+ /**
104
+ * Verify a signed presentation using the verifier DID's authentication key.
105
+ * Defaults: verifier = client.did.
106
+ */
107
+ verifyPresentation(signedPresentation: string, options?: VerifyPresentationOptions): Promise<VerifiedPresentation>;
108
+ private sendReplyMessage;
109
+ private handleInboundMessage;
110
+ private runHandler;
111
+ private runHandlerWithReply;
112
+ private sendDispatchReply;
113
+ private sendProblemReport;
114
+ private fillMessage;
115
+ private sendMessageAcked;
116
+ private sendMessageFireAndForget;
117
+ private sendMessage;
118
+ }
119
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CA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