@signalhousellc/sdk 1.5.0 → 1.6.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 (54) hide show
  1. package/README.md +5 -56
  2. package/index.d.ts +1 -0
  3. package/index.js +2 -0
  4. package/package.json +32 -34
  5. package/voice-browser.d.ts +1 -0
  6. package/voice-browser.js +2 -0
  7. package/warn.js +7 -0
  8. package/webhooks.d.ts +1 -0
  9. package/webhooks.js +2 -0
  10. package/scripts/install-skills.mjs +0 -329
  11. package/skills/VENDORED.json +0 -22
  12. package/skills/signalhouse-10dlc/SKILL.md +0 -172
  13. package/skills/signalhouse-10dlc/examples/brightsmile-onboarding.md +0 -62
  14. package/skills/signalhouse-10dlc/references/tcr-rejection-causes.md +0 -104
  15. package/skills/signalhouse-advisor/SKILL.md +0 -84
  16. package/skills/signalhouse-numbers/SKILL.md +0 -82
  17. package/skills/signalhouse-setup/SKILL.md +0 -121
  18. package/skills/signalhouse-sms/SKILL.md +0 -81
  19. package/skills/signalhouse-webhooks/SKILL.md +0 -148
  20. package/src/SignalHouseSDK.js +0 -201
  21. package/src/domains/Agents.js +0 -987
  22. package/src/domains/Auth.js +0 -225
  23. package/src/domains/Billing.js +0 -264
  24. package/src/domains/Brands.js +0 -508
  25. package/src/domains/Campaigns.js +0 -691
  26. package/src/domains/Dnc.js +0 -168
  27. package/src/domains/Groups.js +0 -187
  28. package/src/domains/Landings.js +0 -237
  29. package/src/domains/Messages.js +0 -609
  30. package/src/domains/Notifications.js +0 -62
  31. package/src/domains/Numbers.js +0 -572
  32. package/src/domains/Onboarding.js +0 -128
  33. package/src/domains/Registrations.js +0 -246
  34. package/src/domains/Shortlinks.js +0 -80
  35. package/src/domains/Subgroups.js +0 -136
  36. package/src/domains/Subscriptions.js +0 -146
  37. package/src/domains/Templates.js +0 -403
  38. package/src/domains/Tickets.js +0 -100
  39. package/src/domains/Users.js +0 -228
  40. package/src/domains/Voice.js +0 -41
  41. package/src/domains/Webhooks.js +0 -125
  42. package/src/domains/voice/Analytics.js +0 -82
  43. package/src/domains/voice/CallLogs.js +0 -111
  44. package/src/domains/voice/Calls.js +0 -118
  45. package/src/domains/voice/GlobalVoiceSettings.js +0 -54
  46. package/src/domains/voice/NumberRoutes.js +0 -82
  47. package/src/domains/voice/ProgrammableVoiceProfiles.js +0 -191
  48. package/src/domains/voice/SipProfiles.js +0 -203
  49. package/src/domains/voice/SipTrunks.js +0 -203
  50. package/src/domains/voice/Tokens.js +0 -96
  51. package/src/domains/voice/browser/Call.js +0 -366
  52. package/src/domains/voice/browser/Device.js +0 -484
  53. package/src/domains/voice/browser/index.js +0 -17
  54. package/src/webhooks/verifySignature.js +0 -66
@@ -1,203 +0,0 @@
1
- /** @typedef {import('../../SignalHouseSDK.js').RequestOptions} RequestOptions */
2
- /**
3
- * @template T
4
- * @typedef {import('../../SignalHouseSDK.js').SdkResponse<T>} SdkResponse
5
- */
6
-
7
- /**
8
- * @typedef {Object} SipTrunkHost
9
- * @property {string} host - IP address, hostname, FQDN, or CIDR.
10
- * @property {string} [port] - Port number as a string (1025-65535). Destination hosts only.
11
- */
12
-
13
- /**
14
- * @typedef {Object} CreateSipTrunkData
15
- * @property {string} name - Trunk name (required, 1-255 chars).
16
- * @property {string} region - SIP POP region the trunk lives in (required), e.g. "us-east-1".
17
- * @property {"IP_AUTH"|"REGISTRATION"} connectionType - IP_AUTH authenticates by source-IP allow-list; REGISTRATION authenticates via SIP REGISTER with username/password.
18
- * @property {string[]} [allowedIps] - Allowed source IPs (IP_AUTH only). Defaults to [].
19
- * @property {"tcp"|"udp"|"tls"} [transport] - SIP transport protocol. Defaults to "tcp".
20
- * @property {number} [maxSpendPerMinute] - Per-minute spend cap override for this trunk.
21
- * @property {SipTrunkHost[]} [destinationHosts] - Where to send outbound SIP traffic. Defaults to [].
22
- * @property {SipTrunkHost[]} [sourceHosts] - Allowed source hosts for inbound traffic. Defaults to [].
23
- */
24
-
25
- /**
26
- * @typedef {Object} UpdateSipTrunkData
27
- * @property {string} [name] - Trunk name (1-255 chars).
28
- * @property {string} [region] - SIP POP region.
29
- * @property {"IP_AUTH"|"REGISTRATION"} [connectionType] - Connection/auth type.
30
- * @property {string[]} [allowedIps] - Allowed source IPs (IP_AUTH only).
31
- * @property {"tcp"|"udp"|"tls"} [transport] - SIP transport protocol.
32
- * @property {number} [maxSpendPerMinute] - Per-minute spend cap override.
33
- * @property {SipTrunkHost[]} [destinationHosts] - Outbound SIP destinations.
34
- * @property {SipTrunkHost[]} [sourceHosts] - Allowed inbound source hosts.
35
- */
36
-
37
- /**
38
- * SIP Trunk management. Calls the voice-backend service mounted under /voice.
39
- * Accessed via `sdk.voice.sipTrunks`.
40
- */
41
- export class SipTrunks {
42
- constructor(client, enableAdmin) {
43
- this.client = client;
44
- this.enableAdmin = enableAdmin;
45
- }
46
-
47
- /**
48
- * List all SIP trunks belonging to the current account.
49
- * @async
50
- * @roles api, admin, developer, billing, user
51
- * @param {Object} [params] - Request parameters.
52
- * @param {RequestOptions} [params.options] - Additional options for the request.
53
- * @returns {Promise<SdkResponse<any>>} The list of SIP trunks: `{ sipTrunks: [...] }`.
54
- */
55
- async list({ options = {} } = {}) {
56
- return this.client(`/voice/sip-trunks`, { method: "GET", ...options });
57
- }
58
-
59
- /**
60
- * Get a single SIP trunk by ID.
61
- * @async
62
- * @roles api, admin, developer, billing, user
63
- * @param {Object} params - Request parameters.
64
- * @param {string} params.id - The SIP trunk UUID.
65
- * @param {RequestOptions} [params.options] - Additional options for the request.
66
- * @throws {Error} If id is missing.
67
- * @returns {Promise<SdkResponse<any>>} The SIP trunk: `{ sipTrunk: {...} }`.
68
- */
69
- async get({ id, options = {} }) {
70
- this.client._require({ id });
71
- const safeId = encodeURIComponent(id);
72
- return this.client(`/voice/sip-trunks/${safeId}`, { method: "GET", ...options });
73
- }
74
-
75
- /**
76
- * Create a new SIP trunk.
77
- * @async
78
- * @roles api, admin, developer, billing, user
79
- * @param {Object} params - Request parameters.
80
- * @param {CreateSipTrunkData} params.trunkData - The SIP trunk to create.
81
- * @param {RequestOptions} [params.options] - Additional options for the request.
82
- * @throws {Error} If trunkData is missing.
83
- * @returns {Promise<SdkResponse<any>>} The created SIP trunk: `{ sipTrunk: {...} }`.
84
- */
85
- async create({ trunkData, options = {} }) {
86
- this.client._require({ trunkData });
87
- return this.client(`/voice/sip-trunks`, { method: "POST", body: trunkData, ...options });
88
- }
89
-
90
- /**
91
- * Update an existing SIP trunk.
92
- * @async
93
- * @roles api, admin, developer, billing, user
94
- * @param {Object} params - Request parameters.
95
- * @param {string} params.id - The SIP trunk UUID.
96
- * @param {UpdateSipTrunkData} params.updateData - Fields to update.
97
- * @param {RequestOptions} [params.options] - Additional options for the request.
98
- * @throws {Error} If id or updateData is missing.
99
- * @returns {Promise<SdkResponse<any>>} The updated SIP trunk: `{ sipTrunk: {...} }`.
100
- */
101
- async update({ id, updateData, options = {} }) {
102
- this.client._require({ id, updateData });
103
- const safeId = encodeURIComponent(id);
104
- return this.client(`/voice/sip-trunks/${safeId}`, { method: "PATCH", body: updateData, ...options });
105
- }
106
-
107
- /**
108
- * Delete a SIP trunk by ID.
109
- * @async
110
- * @roles api, admin, developer, billing, user
111
- * @param {Object} params - Request parameters.
112
- * @param {string} params.id - The SIP trunk UUID.
113
- * @param {RequestOptions} [params.options] - Additional options for the request.
114
- * @throws {Error} If id is missing.
115
- * @returns {Promise<SdkResponse<any>>} `{ success: boolean, message: string }`.
116
- */
117
- async delete({ id, options = {} }) {
118
- this.client._require({ id });
119
- const safeId = encodeURIComponent(id);
120
- return this.client(`/voice/sip-trunks/${safeId}`, { method: "DELETE", ...options });
121
- }
122
-
123
- /**
124
- * Toggle a SIP trunk's active/inactive status.
125
- * @async
126
- * @roles api, admin, developer, billing, user
127
- * @param {Object} params - Request parameters.
128
- * @param {string} params.id - The SIP trunk UUID.
129
- * @param {RequestOptions} [params.options] - Additional options for the request.
130
- * @throws {Error} If id is missing.
131
- * @returns {Promise<SdkResponse<any>>} The updated SIP trunk: `{ sipTrunk: {...} }`.
132
- */
133
- async toggleActive({ id, options = {} }) {
134
- this.client._require({ id });
135
- const safeId = encodeURIComponent(id);
136
- return this.client(`/voice/sip-trunks/${safeId}/toggle-active`, { method: "POST", ...options });
137
- }
138
-
139
- /**
140
- * Regenerate the SIP password for a REGISTRATION-type trunk.
141
- * @async
142
- * @roles api, admin, developer, billing, user
143
- * @param {Object} params - Request parameters.
144
- * @param {string} params.id - The SIP trunk UUID.
145
- * @param {RequestOptions} [params.options] - Additional options for the request.
146
- * @throws {Error} If id is missing.
147
- * @returns {Promise<SdkResponse<any>>} `{ password: string }`.
148
- */
149
- async regeneratePassword({ id, options = {} }) {
150
- this.client._require({ id });
151
- const safeId = encodeURIComponent(id);
152
- return this.client(`/voice/sip-trunks/${safeId}/regenerate-password`, { method: "POST", ...options });
153
- }
154
-
155
- /**
156
- * List available SIP Points of Presence (POPs) and their domains/ports.
157
- * @async
158
- * @roles api, admin, developer, billing, user
159
- * @param {Object} [params] - Request parameters.
160
- * @param {RequestOptions} [params.options] - Additional options for the request.
161
- * @returns {Promise<SdkResponse<any>>} `{ sipPops: [...] }`.
162
- */
163
- async getPops({ options = {} } = {}) {
164
- return this.client(`/voice/sip-trunks/pops`, { method: "GET", ...options });
165
- }
166
-
167
- /**
168
- * Attach one or more phone numbers (by E.164) to a SIP trunk — routes each
169
- * DID down the trunk. Idempotent; numbers already configured on a SIP profile
170
- * are skipped and returned in `skipped` with a reason.
171
- * @async
172
- * @roles api, admin, developer
173
- * @param {Object} params - Request parameters.
174
- * @param {string} params.id - The SIP trunk UUID.
175
- * @param {string[]} params.phoneNumbers - Phone numbers in E.164 (a leading "+" is optional).
176
- * @param {RequestOptions} [params.options] - Additional options for the request.
177
- * @throws {Error} If id or phoneNumbers is missing.
178
- * @returns {Promise<SdkResponse<any>>} `{ assigned: string[], skipped: { e164, reason }[] }`.
179
- */
180
- async assignNumbers({ id, phoneNumbers, options = {} }) {
181
- this.client._require({ id, phoneNumbers });
182
- const safeId = encodeURIComponent(id);
183
- return this.client(`/voice/sip-trunks/${safeId}/assign-numbers`, { method: "POST", body: { phoneNumbers }, ...options });
184
- }
185
-
186
- /**
187
- * Detach one or more phone numbers (by E.164) from a SIP trunk — removes each
188
- * number's SIP_TRUNK inbound route when it points at this trunk.
189
- * @async
190
- * @roles api, admin, developer
191
- * @param {Object} params - Request parameters.
192
- * @param {string} params.id - The SIP trunk UUID.
193
- * @param {string[]} params.phoneNumbers - Phone numbers in E.164 (a leading "+" is optional).
194
- * @param {RequestOptions} [params.options] - Additional options for the request.
195
- * @throws {Error} If id or phoneNumbers is missing.
196
- * @returns {Promise<SdkResponse<any>>} `{ unassigned: string[] }`.
197
- */
198
- async unassignNumbers({ id, phoneNumbers, options = {} }) {
199
- this.client._require({ id, phoneNumbers });
200
- const safeId = encodeURIComponent(id);
201
- return this.client(`/voice/sip-trunks/${safeId}/unassign-numbers`, { method: "POST", body: { phoneNumbers }, ...options });
202
- }
203
- }
@@ -1,96 +0,0 @@
1
- /** @typedef {import('../../SignalHouseSDK.js').RequestOptions} RequestOptions */
2
- /**
3
- * @template T
4
- * @typedef {import('../../SignalHouseSDK.js').SdkResponse<T>} SdkResponse
5
- */
6
-
7
- /**
8
- * @typedef {Object} VoiceGrants
9
- * @property {Object} [voice] - Voice grants object.
10
- * @property {Object} [voice.incoming] - Inbound call grants.
11
- * @property {boolean} [voice.incoming.allow] - Allow inbound calls to this identity.
12
- * @property {Object} [voice.outgoing] - Outbound call grants.
13
- * @property {string[]} [voice.outgoing.allowedNumbers] - E.164 numbers this identity may present as caller ID.
14
- */
15
-
16
- /**
17
- * @typedef {Object} CreateTokenData
18
- * @property {string} [identity] - Customer-facing logical identity name (e.g. "alice"). Persisted as `requested_identity` so server-initiated `calls.create({to_identity: "alice"})` can resolve it later. Defaults to "anonymous".
19
- * @property {number} [ttl] - Token TTL in seconds. Clamped to the server's max. Defaults to VOICE_TOKEN_DEFAULT_TTL_SEC.
20
- * @property {VoiceGrants} [grants] - Capability grants attached to the token.
21
- */
22
-
23
- /**
24
- * @typedef {Object} SipCredentials
25
- * @property {string} username - Server-generated SIP username (e.g. "wrtc_<hex>"). Use for the SIP-over-WSS registration.
26
- * @property {string} password - Plaintext SIP password — sent ONCE, never recoverable. Use for digest auth on REGISTER + INVITE.
27
- * @property {string} domain - SIP domain to register against (the part after `@` in the URI).
28
- * @property {string} wss_url - WebSocket Secure URL the SDK opens to send SIP traffic.
29
- */
30
-
31
- /**
32
- * @typedef {Object} CreateTokenResponse
33
- * @property {string} token - JWT to pass to the SignalHouse browser voice SDK.
34
- * @property {string} identity - The server-generated SIP username (wrtc_<hex>). Distinct from the logical `requested_identity` passed in.
35
- * @property {string} expires_at - ISO-8601 expiry timestamp.
36
- * @property {SipCredentials} sip_credentials - Ephemeral SIP creds embedded in the token; surfaced separately for direct SIP clients.
37
- */
38
-
39
- /**
40
- * WebRTC voice tokens. Mints ephemeral SIP identities the browser/mobile voice
41
- * SDK uses to register against the SignalHouse voice fabric. Wraps voice-
42
- * backend's `/voice/tokens` endpoint. Accessed via `sdk.voice.tokens`.
43
- *
44
- * Customer flow:
45
- * 1. Backend calls `sdk.voice.tokens.create({ identity: "alice", ttl: 1800 })`
46
- * and returns the resulting `token` to the customer's browser/app.
47
- * 2. Browser SDK registers using the embedded `sip_credentials`.
48
- * 3. Outbound calls from the SDK go through OpenSIPS → Asterisk → carrier;
49
- * the server-side `calls.create({ to_identity: "alice", ... })` flow can
50
- * also ring this identity for click-to-call patterns.
51
- */
52
- export class Tokens {
53
- constructor(client, enableAdmin) {
54
- this.client = client;
55
- this.enableAdmin = enableAdmin;
56
- }
57
-
58
- /**
59
- * Mint an ephemeral voice token + SIP credentials.
60
- * @async
61
- * @roles api, admin, developer, billing, user
62
- * @param {Object} [params] - Request parameters.
63
- * @param {CreateTokenData} [params.tokenData] - Token mint options (identity, ttl, grants). All fields optional.
64
- * @param {RequestOptions} [params.options] - Additional options for the request.
65
- * @returns {Promise<SdkResponse<CreateTokenResponse>>} The token + embedded SIP credentials.
66
- */
67
- async create({ tokenData = {}, options = {} } = {}) {
68
- return this.client(`/voice/tokens`, { method: "POST", body: tokenData, ...options });
69
- }
70
-
71
- /**
72
- * Refresh (extend) an existing voice token in place — identity-preserving.
73
- * Wraps voice-backend's `/voice/tokens/refresh`. Keeps the same wrtc_
74
- * identity + SIP credentials and only pushes out `expires_at`, so a
75
- * long-lived softphone stays registered without re-establishing its SIP
76
- * registration (unlike `create()`, which mints a NEW identity). Provide the
77
- * current `token` (its identity is decoded server-side) or the `identity`
78
- * directly. Rejects with a 404 when the token no longer exists for the
79
- * account — mint a fresh one with `create()` in that case.
80
- * @async
81
- * @roles api, admin, developer, billing, user
82
- * @param {Object} [params] - Request parameters.
83
- * @param {string} [params.token] - The current voice token (JWT) whose identity to extend.
84
- * @param {string} [params.identity] - The wrtc_ identity to extend, if held directly (from a prior mint/refresh response).
85
- * @param {number} [params.ttl] - New TTL in seconds. Defaults to the server default, capped at the server maximum.
86
- * @param {RequestOptions} [params.options] - Additional options for the request.
87
- * @returns {Promise<SdkResponse<CreateTokenResponse>>} The refreshed token + embedded SIP credentials (same shape as create()).
88
- */
89
- async refresh({ token, identity, ttl, options = {} } = {}) {
90
- const body = {};
91
- if (token) body.token = token;
92
- if (identity) body.identity = identity;
93
- if (ttl != null) body.ttl = ttl;
94
- return this.client(`/voice/tokens/refresh`, { method: "POST", body, ...options });
95
- }
96
- }
@@ -1,366 +0,0 @@
1
- /**
2
- * @typedef {"inbound"|"outbound"} CallDirection
3
- * @typedef {"initial"|"ringing"|"in_progress"|"ended"|"failed"} CallStatus
4
- */
5
-
6
- /**
7
- * Wraps a single SIP session — outbound or inbound — and exposes a
8
- * Twilio-shape Call API on top of the underlying JsSIP RTCSession.
9
- *
10
- * Lifecycle (outbound):
11
- * new (status="initial") → ringing → in_progress → ended | failed
12
- *
13
- * Lifecycle (inbound, before .accept()):
14
- * new (status="ringing") → in_progress (on accept) → ended | failed
15
- *
16
- * Custom SIP headers from inbound INVITEs are exposed on the instance
17
- * (notably `initiatorId` from `X-SignalHouse-Initiator`) so the host app
18
- * can correlate a server-initiated callback to its triggering REST call.
19
- *
20
- * Methods reject when the session is no longer in a state that supports
21
- * them (e.g., `.accept()` on an already-accepted call).
22
- */
23
- export class Call {
24
- /**
25
- * @param {Object} init - Initializer.
26
- * @param {Object} init.session - The JsSIP RTCSession.
27
- * @param {CallDirection} init.direction
28
- * @param {Object} [init.request] - Inbound INVITE request, when direction === "inbound".
29
- */
30
- constructor({ session, direction, request }) {
31
- this._session = session;
32
- this._listeners = new Map();
33
- this._remoteAudio = null;
34
- /** @type {boolean} Set true before accept/connect to route remote audio yourself instead of the hidden <audio>. */
35
- this.disableDefaultAudioOutput = false;
36
-
37
- this.direction = direction;
38
- this.id = session.id || session._request?.call_id || null;
39
- this.status = direction === "inbound" ? "ringing" : "initial";
40
-
41
- // From / To URIs. For inbound the session._request carries them; for
42
- // outbound JsSIP populates from session.remote_identity / local_identity
43
- // once the dialog is established.
44
- this.from = session.remote_identity?.uri?.toString?.() ?? request?.from?.uri?.toString?.() ?? null;
45
- this.to = session.local_identity?.uri?.toString?.() ?? request?.to?.uri?.toString?.() ?? null;
46
-
47
- // Surface useful inbound headers. Most important: X-SignalHouse-Initiator,
48
- // which carries the call_id of the REST POST /v1/calls that triggered a
49
- // server-side two-leg-with-bridge ring. Host app can compare against its
50
- // pending dial set to decide whether to auto-accept.
51
- this.headers = {};
52
- if (request && typeof request.getHeader === "function") {
53
- for (const name of [
54
- "X-SignalHouse-Initiator",
55
- "X-Call-UUID",
56
- "X-Call-Type",
57
- "X-Route-Type",
58
- "X-Dest",
59
- ]) {
60
- const v = request.getHeader(name);
61
- if (v) this.headers[name] = v;
62
- }
63
- }
64
- this.initiatorId = this.headers["X-SignalHouse-Initiator"] || null;
65
- this.callUuid = this.headers["X-Call-UUID"] || null;
66
-
67
- this._wireSessionEvents();
68
- }
69
-
70
- // ─── Public API ─────────────────────────────────────────────────────────
71
-
72
- /**
73
- * Accept an inbound call. No-op (warning) if outbound or already accepted.
74
- * @param {Object} [opts]
75
- * @param {MediaStream} [opts.mediaStream] - Pre-acquired stream from getUserMedia.
76
- * If omitted, the SDK calls getUserMedia({audio: true}) and uses the result.
77
- * @param {RTCConfiguration} [opts.pcConfig] - WebRTC peer-connection config.
78
- * Falls back to {iceServers: [{urls: "stun:stun.l.google.com:19302"}]}.
79
- * @returns {Promise<void>}
80
- */
81
- async accept({ mediaStream, pcConfig } = {}) {
82
- if (this.direction !== "inbound") {
83
- console.warn("[Call.accept] no-op: only inbound calls can be accepted");
84
- return;
85
- }
86
- if (this.status !== "ringing") {
87
- console.warn(`[Call.accept] no-op: call is not ringing (status=${this.status})`);
88
- return;
89
- }
90
- const stream = mediaStream || (await navigator.mediaDevices.getUserMedia({ audio: true, video: false }));
91
- this._session.answer({
92
- mediaConstraints: { audio: true, video: false },
93
- mediaStream: stream,
94
- // Default: no STUN (rtpengine trust-address handles NAT). Override via pcConfig.
95
- pcConfig: pcConfig || { iceServers: [] },
96
- });
97
- }
98
-
99
- /**
100
- * Reject an inbound call with 486 Busy (or supplied SIP code).
101
- * @param {Object} [opts]
102
- * @param {number} [opts.statusCode=486]
103
- * @param {string} [opts.reason="Busy Here"]
104
- */
105
- reject({ statusCode = 486, reason = "Busy Here" } = {}) {
106
- if (this.direction !== "inbound" || this.status !== "ringing") {
107
- console.warn("[Call.reject] no-op: only ringing inbound calls can be rejected");
108
- return;
109
- }
110
- try {
111
- this._session.terminate({ status_code: statusCode, reason_phrase: reason });
112
- } catch (err) {
113
- // JsSIP throws if the session is already gone — non-fatal here
114
- console.warn(`[Call.reject] terminate threw: ${err?.message || err}`);
115
- }
116
- }
117
-
118
- /**
119
- * Hang up an in-progress or ringing outbound call. Idempotent.
120
- */
121
- hangup() {
122
- if (this.status === "ended" || this.status === "failed") return;
123
- try {
124
- this._session.terminate();
125
- } catch (err) {
126
- console.warn(`[Call.hangup] terminate threw: ${err?.message || err}`);
127
- }
128
- }
129
-
130
- /**
131
- * Send DTMF digits during an in-progress call. Accepts 0-9, *, #, w (wait).
132
- * @param {string} digits
133
- */
134
- sendDigits(digits) {
135
- if (this.status !== "in_progress") {
136
- console.warn(`[Call.sendDigits] no-op: call is not in_progress (status=${this.status})`);
137
- return;
138
- }
139
- try {
140
- this._session.sendDTMF(String(digits));
141
- } catch (err) {
142
- console.warn(`[Call.sendDigits] sendDTMF threw: ${err?.message || err}`);
143
- }
144
- }
145
-
146
- /**
147
- * Mute or unmute the local microphone. Twilio-shape: pass `true` to mute,
148
- * `false` to unmute. Stops/resumes sending audio RTP at the media layer —
149
- * no SIP signaling, so it works regardless of server support.
150
- * @param {boolean} [shouldMute=true]
151
- */
152
- mute(shouldMute = true) {
153
- if (this.status !== "in_progress") {
154
- console.warn(`[Call.mute] no-op: call is not in_progress (status=${this.status})`);
155
- return;
156
- }
157
- try {
158
- if (shouldMute) this._session.mute({ audio: true });
159
- else this._session.unmute({ audio: true });
160
- } catch (err) {
161
- console.warn(`[Call.mute] threw: ${err?.message || err}`);
162
- }
163
- }
164
-
165
- /** Unmute the local microphone. Convenience for `mute(false)`. */
166
- unmute() {
167
- this.mute(false);
168
- }
169
-
170
- /**
171
- * @returns {boolean} whether the local microphone is currently muted.
172
- */
173
- isMuted() {
174
- try {
175
- return Boolean(this._session.isMuted?.()?.audio);
176
- } catch {
177
- return false;
178
- }
179
- }
180
-
181
- /**
182
- * Put the call on hold, or resume it. Sends a re-INVITE with the audio
183
- * direction set to sendonly (hold) / sendrecv (resume); the media server
184
- * (rtpengine) handles it. Pass `false` to resume.
185
- * @param {boolean} [shouldHold=true]
186
- * @returns {boolean} whether the (un)hold was initiated.
187
- */
188
- hold(shouldHold = true) {
189
- if (this.status !== "in_progress") {
190
- console.warn(`[Call.hold] no-op: call is not in_progress (status=${this.status})`);
191
- return false;
192
- }
193
- try {
194
- return shouldHold ? this._session.hold() : this._session.unhold();
195
- } catch (err) {
196
- console.warn(`[Call.hold] threw: ${err?.message || err}`);
197
- return false;
198
- }
199
- }
200
-
201
- /** Resume a held call. Convenience for `hold(false)`. */
202
- unhold() {
203
- return this.hold(false);
204
- }
205
-
206
- /**
207
- * @returns {boolean} whether this leg is locally on hold.
208
- */
209
- isOnHold() {
210
- try {
211
- return Boolean(this._session.isOnHold?.()?.local);
212
- } catch {
213
- return false;
214
- }
215
- }
216
-
217
- /**
218
- * Blind-transfer (cold transfer) the call to another destination via SIP
219
- * REFER. The far end is re-routed to `target` and this leg ends once the
220
- * transfer is accepted. `target` may be a phone number (E.164 or bare
221
- * digits) or a full SIP URI — bare numbers are normalized against the
222
- * registered SIP domain by the underlying stack.
223
- *
224
- * NOTE: completing the transfer requires the SIP server to honor the REFER
225
- * (route the new leg / bridge the parties). The client only initiates it.
226
- * @param {string} target - Destination number or SIP URI.
227
- */
228
- transfer(target) {
229
- if (this.status !== "in_progress") {
230
- console.warn(`[Call.transfer] no-op: call is not in_progress (status=${this.status})`);
231
- return;
232
- }
233
- if (!target) {
234
- console.warn("[Call.transfer] no-op: a transfer target is required");
235
- return;
236
- }
237
- try {
238
- this._session.refer(target);
239
- } catch (err) {
240
- console.warn(`[Call.transfer] refer threw: ${err?.message || err}`);
241
- }
242
- }
243
-
244
- /**
245
- * Attach an event listener. Events:
246
- * "accepted" — 200 OK received (outbound) or sent (inbound after accept)
247
- * "confirmed" — ACK exchanged, media flowing
248
- * "ended" — normal hangup; payload: {cause}
249
- * "failed" — error before/during; payload: {cause, status_code, reason}
250
- * "track" — remote MediaStreamTrack added; payload: {track, streams}
251
- * @param {string} event
252
- * @param {Function} handler
253
- */
254
- on(event, handler) {
255
- if (!this._listeners.has(event)) this._listeners.set(event, new Set());
256
- this._listeners.get(event).add(handler);
257
- }
258
-
259
- /**
260
- * Remove a previously-registered listener.
261
- */
262
- off(event, handler) {
263
- this._listeners.get(event)?.delete(handler);
264
- }
265
-
266
- // ─── Internal: wire JsSIP RTCSession events to Call events ───────────────
267
-
268
- _emit(event, payload) {
269
- for (const fn of this._listeners.get(event) || []) {
270
- try { fn(payload); }
271
- catch (err) { console.error(`[Call.${event} handler]`, err); }
272
- }
273
- }
274
-
275
- _wireSessionEvents() {
276
- const s = this._session;
277
-
278
- // Attach the RTCPeerConnection "track" listener as soon as the PC
279
- // exists. The browser can fire `track` when the remote SDP is applied,
280
- // which happens BEFORE JsSIP emits "confirmed" — waiting until then
281
- // can drop the event entirely (call connects, no audio).
282
- //
283
- // For outbound calls JsSIP creates the PC inside `ua.call()`, so
284
- // session.connection may already exist by the time our Call is
285
- // constructed — handle that synchronously. For inbound calls the PC
286
- // is created inside session.answer(); JsSIP emits "peerconnection"
287
- // when it's ready — attach there.
288
- if (s.connection) this._attachTrackListener(s.connection);
289
- s.on("peerconnection", (e) => {
290
- const pc = e?.peerconnection || s.connection;
291
- if (pc) this._attachTrackListener(pc);
292
- });
293
-
294
- s.on("progress", (e) => {
295
- this.status = "ringing";
296
- this._emit("progress", { response: e.response });
297
- });
298
-
299
- s.on("accepted", () => {
300
- this.status = "in_progress";
301
- this._emit("accepted");
302
- });
303
-
304
- s.on("confirmed", () => {
305
- this.status = "in_progress";
306
- // Defensive: in case "peerconnection" never fired but a PC exists by now.
307
- if (this._session.connection) this._attachTrackListener(this._session.connection);
308
- this._emit("confirmed");
309
- });
310
-
311
- s.on("ended", (e) => {
312
- this.status = "ended";
313
- this._cleanupRemoteAudio();
314
- this._emit("ended", { cause: e?.cause });
315
- });
316
-
317
- s.on("failed", (e) => {
318
- this.status = "failed";
319
- this._cleanupRemoteAudio();
320
- this._emit("failed", {
321
- cause: e?.cause,
322
- statusCode: e?.message?.status_code,
323
- reason: e?.message?.reason_phrase,
324
- });
325
- });
326
- }
327
-
328
- /**
329
- * Idempotent — wires the RTCPeerConnection "track" handler. Uses
330
- * addEventListener (not pc.ontrack) so host apps can attach their own
331
- * track listener without clobbering ours, and vice versa.
332
- *
333
- * When a remote track arrives:
334
- * - Emit "track" so the host app can route audio anywhere it wants.
335
- * - If `call.disableDefaultAudioOutput` is falsy, attach the stream to
336
- * a hidden <audio> element so the user just hears the call. Host
337
- * apps that want custom audio routing should set
338
- * `call.disableDefaultAudioOutput = true` before accepting/connecting.
339
- */
340
- _attachTrackListener(pc) {
341
- if (this._trackListenerAttached) return;
342
- this._trackListenerAttached = true;
343
-
344
- pc.addEventListener("track", (evt) => {
345
- this._emit("track", { track: evt.track, streams: evt.streams });
346
- if (this.disableDefaultAudioOutput) return;
347
- if (!this._remoteAudio) {
348
- this._remoteAudio = document.createElement("audio");
349
- this._remoteAudio.autoplay = true;
350
- this._remoteAudio.setAttribute("data-signalhouse-call", this.id || "");
351
- document.body.appendChild(this._remoteAudio);
352
- }
353
- this._remoteAudio.srcObject = evt.streams[0];
354
- });
355
- }
356
-
357
- _cleanupRemoteAudio() {
358
- if (this._remoteAudio) {
359
- try {
360
- this._remoteAudio.srcObject = null;
361
- this._remoteAudio.remove();
362
- } catch {}
363
- this._remoteAudio = null;
364
- }
365
- }
366
- }