@signalwire/sdk 2.0.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/.github/workflows/publish.yml +27 -0
- package/.github/workflows/test.yml +17 -0
- package/CLAUDE.md +112 -0
- package/README.md +254 -0
- package/docs/MIGRATION-2.0.md +81 -0
- package/docs/agent-guide.md +869 -0
- package/docs/agent_guide.md +1026 -0
- package/docs/api-reference.md +2420 -0
- package/docs/api_reference.md +1301 -0
- package/docs/architecture.md +843 -0
- package/docs/cli-guide.md +579 -0
- package/docs/cli_guide.md +448 -0
- package/docs/cloud_functions_guide.md +474 -0
- package/docs/configuration.md +422 -0
- package/docs/contexts-guide.md +787 -0
- package/docs/contexts_guide.md +511 -0
- package/docs/datamap-guide.md +1141 -0
- package/docs/datamap_guide.md +595 -0
- package/docs/llm_parameters.md +239 -0
- package/docs/mcp_gateway_reference.md +648 -0
- package/docs/mcp_integration.md +108 -0
- package/docs/prefabs-guide.md +800 -0
- package/docs/sdk_features.md +477 -0
- package/docs/security.md +436 -0
- package/docs/serverless-guide.md +513 -0
- package/docs/skills-guide.md +857 -0
- package/docs/skills-system.md +301 -0
- package/docs/skills_parameter_schema.md +392 -0
- package/docs/skills_system.md +467 -0
- package/docs/swaig-reference.md +1627 -0
- package/docs/swaig_reference.md +910 -0
- package/docs/swml_service_guide.md +600 -0
- package/docs/third_party_skills.md +533 -0
- package/docs/web_service.md +677 -0
- package/examples/README.md +131 -0
- package/examples/advanced-datamap.ts +100 -0
- package/examples/advanced-dynamic-config.ts +70 -0
- package/examples/auto-vivified.ts +94 -0
- package/examples/call-flow.ts +63 -0
- package/examples/comprehensive-dynamic.ts +125 -0
- package/examples/contexts-steps.ts +65 -0
- package/examples/custom-path.ts +45 -0
- package/examples/datamap-tools.ts +55 -0
- package/examples/datasphere-multi-instance.ts +63 -0
- package/examples/datasphere-serverless-env.ts +68 -0
- package/examples/datasphere-webhook-env.ts +66 -0
- package/examples/datasphere.ts +37 -0
- package/examples/declarative.ts +100 -0
- package/examples/dynamic-config.ts +54 -0
- package/examples/dynamic-info-gatherer.ts +69 -0
- package/examples/dynamic-swml-service.ts +67 -0
- package/examples/gather-info.ts +71 -0
- package/examples/gather-per-question-functions-demo.ts +140 -0
- package/examples/joke-agent.ts +34 -0
- package/examples/kubernetes-agent.ts +45 -0
- package/examples/llm-params.ts +69 -0
- package/examples/mcp-agent.ts +84 -0
- package/examples/mcp-gateway.ts +35 -0
- package/examples/multi-agent.ts +73 -0
- package/examples/multi-endpoint.ts +79 -0
- package/examples/pom-prompt.ts +71 -0
- package/examples/prefab-concierge.ts +47 -0
- package/examples/prefab-faq.ts +54 -0
- package/examples/prefab-info-gatherer.ts +33 -0
- package/examples/prefab-receptionist.ts +36 -0
- package/examples/prefab-survey.ts +68 -0
- package/examples/record-call.ts +67 -0
- package/examples/relay-demo.ts +33 -0
- package/examples/room-and-sip.ts +94 -0
- package/examples/serverless-lambda.ts +35 -0
- package/examples/session-state.ts +83 -0
- package/examples/simple-agent.ts +36 -0
- package/examples/simple-static.ts +29 -0
- package/examples/skills-demo.ts +38 -0
- package/examples/step-function-inheritance-demo.ts +124 -0
- package/examples/swaig-features.ts +187 -0
- package/examples/swml-service-routing.ts +66 -0
- package/examples/swml-service.ts +38 -0
- package/examples/tap.ts +68 -0
- package/examples/verb-methods.ts +45 -0
- package/examples/web-search-multi-instance.ts +72 -0
- package/examples/web-search.ts +38 -0
- package/examples/wikipedia.ts +36 -0
- package/livewire/README.md +140 -0
- package/livewire/docs/migration-guide.md +228 -0
- package/livewire/examples/livewire-basic-agent.ts +74 -0
- package/livewire/examples/livewire-handoff.ts +197 -0
- package/livewire/examples/livewire-multi-tool.ts +117 -0
- package/package.json +38 -0
- package/relay/README.md +70 -0
- package/relay/RELAY_IMPLEMENTATION_GUIDE.md +1257 -0
- package/relay/docs/call-methods.md +474 -0
- package/relay/docs/client-reference.md +142 -0
- package/relay/docs/events.md +134 -0
- package/relay/docs/getting-started.md +134 -0
- package/relay/docs/guide.md +306 -0
- package/relay/docs/messaging.md +182 -0
- package/relay/examples/relay-inbound.ts +66 -0
- package/relay/examples/relay-messaging.ts +71 -0
- package/relay/examples/relay-outbound.ts +76 -0
- package/rest/README.md +95 -0
- package/rest/docs/calling.md +273 -0
- package/rest/docs/client-reference.md +107 -0
- package/rest/docs/compat.md +204 -0
- package/rest/docs/fabric.md +183 -0
- package/rest/docs/getting-started.md +110 -0
- package/rest/docs/guide.md +351 -0
- package/rest/docs/namespaces.md +285 -0
- package/rest/examples/rest-10dlc-registration.ts +161 -0
- package/rest/examples/rest-calling-ivr-and-ai.ts +102 -0
- package/rest/examples/rest-calling-play-and-record.ts +91 -0
- package/rest/examples/rest-client.ts +65 -0
- package/rest/examples/rest-compat-laml.ts +210 -0
- package/rest/examples/rest-datasphere-search.ts +82 -0
- package/rest/examples/rest-fabric-conferences-and-routing.ts +144 -0
- package/rest/examples/rest-fabric-subscribers-and-sip.ts +108 -0
- package/rest/examples/rest-fabric-swml-and-callflows.ts +99 -0
- package/rest/examples/rest-manage-resources.ts +65 -0
- package/rest/examples/rest-phone-number-management.ts +197 -0
- package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
- package/rest/examples/rest-video-rooms.ts +186 -0
- package/src/AgentBase.ts +2489 -0
- package/src/AgentServer.ts +415 -0
- package/src/AuthHandler.ts +256 -0
- package/src/ConfigLoader.ts +447 -0
- package/src/ContextBuilder.ts +1150 -0
- package/src/DataMap.ts +449 -0
- package/src/FunctionResult.ts +866 -0
- package/src/Logger.ts +337 -0
- package/src/PomBuilder.ts +439 -0
- package/src/PromptManager.ts +133 -0
- package/src/SWMLHandler.ts +298 -0
- package/src/SWMLService.ts +717 -0
- package/src/SchemaUtils.ts +361 -0
- package/src/SecurityUtils.ts +153 -0
- package/src/ServerlessAdapter.ts +221 -0
- package/src/SessionManager.ts +311 -0
- package/src/SslConfig.ts +118 -0
- package/src/SwaigFunction.ts +276 -0
- package/src/SwmlBuilder.ts +258 -0
- package/src/SwmlVerbMethods.generated.ts +234 -0
- package/src/TypeInference.ts +181 -0
- package/src/WebService.ts +619 -0
- package/src/cli/agent-loader.ts +166 -0
- package/src/cli/mock-data.ts +111 -0
- package/src/cli/swaig-test.ts +452 -0
- package/src/generateVerbTypes.ts +322 -0
- package/src/index.ts +167 -0
- package/src/livewire/index.ts +950 -0
- package/src/prefabs/ConciergeAgent.ts +287 -0
- package/src/prefabs/FAQBotAgent.ts +384 -0
- package/src/prefabs/InfoGathererAgent.ts +339 -0
- package/src/prefabs/ReceptionistAgent.ts +366 -0
- package/src/prefabs/SurveyAgent.ts +646 -0
- package/src/prefabs/index.ts +27 -0
- package/src/relay/Action.ts +314 -0
- package/src/relay/Call.ts +854 -0
- package/src/relay/Deferred.ts +71 -0
- package/src/relay/Message.ts +148 -0
- package/src/relay/RelayClient.ts +1036 -0
- package/src/relay/RelayError.ts +14 -0
- package/src/relay/RelayEvent.ts +892 -0
- package/src/relay/constants.ts +132 -0
- package/src/relay/index.ts +123 -0
- package/src/relay/types.ts +149 -0
- package/src/rest/HttpClient.ts +103 -0
- package/src/rest/RestError.ts +31 -0
- package/src/rest/base/BaseResource.ts +19 -0
- package/src/rest/base/CrudResource.ts +51 -0
- package/src/rest/base/CrudWithAddresses.ts +26 -0
- package/src/rest/index.ts +200 -0
- package/src/rest/namespaces/addresses.ts +32 -0
- package/src/rest/namespaces/calling.ts +187 -0
- package/src/rest/namespaces/chat.ts +20 -0
- package/src/rest/namespaces/compat.ts +352 -0
- package/src/rest/namespaces/datasphere.ts +45 -0
- package/src/rest/namespaces/fabric.ts +222 -0
- package/src/rest/namespaces/imported-numbers.ts +20 -0
- package/src/rest/namespaces/logs.ts +84 -0
- package/src/rest/namespaces/lookup.ts +21 -0
- package/src/rest/namespaces/mfa.ts +30 -0
- package/src/rest/namespaces/number-groups.ts +38 -0
- package/src/rest/namespaces/phone-numbers.ts +44 -0
- package/src/rest/namespaces/project.ts +36 -0
- package/src/rest/namespaces/pubsub.ts +20 -0
- package/src/rest/namespaces/queues.ts +33 -0
- package/src/rest/namespaces/recordings.ts +28 -0
- package/src/rest/namespaces/registry.ts +101 -0
- package/src/rest/namespaces/short-codes.ts +28 -0
- package/src/rest/namespaces/sip-profile.ts +25 -0
- package/src/rest/namespaces/verified-callers.ts +27 -0
- package/src/rest/namespaces/video.ts +165 -0
- package/src/rest/pagination.ts +84 -0
- package/src/rest/types.ts +61 -0
- package/src/schema.json +12250 -0
- package/src/skills/SkillBase.ts +547 -0
- package/src/skills/SkillManager.ts +415 -0
- package/src/skills/SkillRegistry.ts +367 -0
- package/src/skills/builtin/api_ninjas_trivia.ts +280 -0
- package/src/skills/builtin/ask_claude.ts +241 -0
- package/src/skills/builtin/claude_skills.ts +978 -0
- package/src/skills/builtin/custom_skills.ts +312 -0
- package/src/skills/builtin/datasphere.ts +438 -0
- package/src/skills/builtin/datasphere_serverless.ts +339 -0
- package/src/skills/builtin/datetime.ts +130 -0
- package/src/skills/builtin/google_maps.ts +651 -0
- package/src/skills/builtin/index.ts +88 -0
- package/src/skills/builtin/info_gatherer.ts +405 -0
- package/src/skills/builtin/joke.ts +191 -0
- package/src/skills/builtin/math.ts +142 -0
- package/src/skills/builtin/mcp_gateway.ts +677 -0
- package/src/skills/builtin/native_vector_search.ts +901 -0
- package/src/skills/builtin/play_background_file.ts +358 -0
- package/src/skills/builtin/spider.ts +869 -0
- package/src/skills/builtin/swml_transfer.ts +635 -0
- package/src/skills/builtin/weather_api.ts +248 -0
- package/src/skills/builtin/web_search.ts +1074 -0
- package/src/skills/builtin/wikipedia_search.ts +299 -0
- package/src/skills/index.ts +12 -0
- package/src/types.ts +132 -0
- package/tests/AgentBase.test.ts +1093 -0
- package/tests/AgentServer.test.ts +126 -0
- package/tests/AuthHandler.test.ts +133 -0
- package/tests/ConfigLoader.test.ts +151 -0
- package/tests/ContextBuilder.test.ts +108 -0
- package/tests/DataMap.test.ts +367 -0
- package/tests/EphemeralSkillCopy.test.ts +107 -0
- package/tests/FunctionResult.test.ts +298 -0
- package/tests/GracefulShutdown.test.ts +46 -0
- package/tests/Logger.test.ts +420 -0
- package/tests/PomBuilder.test.ts +228 -0
- package/tests/ProxyDetection.test.ts +228 -0
- package/tests/SWMLService.test.ts +320 -0
- package/tests/SWMLVerbHandler.test.ts +523 -0
- package/tests/SchemaUtils.test.ts +106 -0
- package/tests/SchemaUtils.verb.test.ts +206 -0
- package/tests/SecurityUtils.test.ts +192 -0
- package/tests/ServerlessAdapter.test.ts +222 -0
- package/tests/SessionManager.test.ts +257 -0
- package/tests/SkillBaseFeatures.test.ts +130 -0
- package/tests/SkillMultiInstance.test.ts +102 -0
- package/tests/SkillParameterSchemas.test.ts +134 -0
- package/tests/SkillRegistrySchema.test.ts +84 -0
- package/tests/SslConfig.test.ts +97 -0
- package/tests/SwmlBuilder.test.ts +400 -0
- package/tests/TypeInference.test.ts +165 -0
- package/tests/VerbHandlerRegistry.test.ts +128 -0
- package/tests/cli/mock-data.test.ts +113 -0
- package/tests/cli/swaig-test.test.ts +108 -0
- package/tests/examples.test.ts +194 -0
- package/tests/fixtures/scrape-parity/README.md +53 -0
- package/tests/fixtures/scrape-parity/expected/01_simple_article.json +5 -0
- package/tests/fixtures/scrape-parity/expected/02_class_based_noise.json +5 -0
- package/tests/fixtures/scrape-parity/expected/03_nested_containers.json +5 -0
- package/tests/fixtures/scrape-parity/expected/04_bare_body.json +5 -0
- package/tests/fixtures/scrape-parity/expected/05_malformed.json +5 -0
- package/tests/fixtures/scrape-parity/expected/06_multi_class.json +5 -0
- package/tests/fixtures/scrape-parity/expected/07_anchor_pattern.json +5 -0
- package/tests/fixtures/scrape-parity/expected/08_inline_script.json +5 -0
- package/tests/fixtures/scrape-parity/expected/09_whitespace_nbsp.json +5 -0
- package/tests/fixtures/scrape-parity/expected/10_entity_unicode.json +5 -0
- package/tests/fixtures/scrape-parity/expected/11_cdata_comments.json +5 -0
- package/tests/fixtures/scrape-parity/expected/12_deep_nested_removals.json +5 -0
- package/tests/fixtures/scrape-parity/html/01_simple_article.html +18 -0
- package/tests/fixtures/scrape-parity/html/02_class_based_noise.html +18 -0
- package/tests/fixtures/scrape-parity/html/03_nested_containers.html +13 -0
- package/tests/fixtures/scrape-parity/html/04_bare_body.html +9 -0
- package/tests/fixtures/scrape-parity/html/05_malformed.html +11 -0
- package/tests/fixtures/scrape-parity/html/06_multi_class.html +18 -0
- package/tests/fixtures/scrape-parity/html/07_anchor_pattern.html +12 -0
- package/tests/fixtures/scrape-parity/html/08_inline_script.html +17 -0
- package/tests/fixtures/scrape-parity/html/09_whitespace_nbsp.html +21 -0
- package/tests/fixtures/scrape-parity/html/10_entity_unicode.html +10 -0
- package/tests/fixtures/scrape-parity/html/11_cdata_comments.html +13 -0
- package/tests/fixtures/scrape-parity/html/12_deep_nested_removals.html +24 -0
- package/tests/fixtures/scrape-parity/python_extract.py +109 -0
- package/tests/livewire/livewire.test.ts +780 -0
- package/tests/mcp.test.ts +221 -0
- package/tests/prefabs/prefabs.test.ts +1093 -0
- package/tests/relay/Action.test.ts +392 -0
- package/tests/relay/Call.test.ts +535 -0
- package/tests/relay/Deferred.test.ts +71 -0
- package/tests/relay/Message.test.ts +164 -0
- package/tests/relay/RelayClient.test.ts +779 -0
- package/tests/relay/RelayEvent.test.ts +463 -0
- package/tests/relay/helpers.ts +79 -0
- package/tests/rest/HttpClient.test.ts +274 -0
- package/tests/rest/RestError.test.ts +53 -0
- package/tests/rest/calling.test.ts +156 -0
- package/tests/rest/client.test.ts +197 -0
- package/tests/rest/compat.test.ts +335 -0
- package/tests/rest/datasphere.test.ts +71 -0
- package/tests/rest/fabric.test.ts +186 -0
- package/tests/rest/helpers.ts +95 -0
- package/tests/rest/logs.test.ts +68 -0
- package/tests/rest/pagination.test.ts +133 -0
- package/tests/rest/registry.test.ts +94 -0
- package/tests/rest/relay-rest.test.ts +290 -0
- package/tests/rest/video.test.ts +173 -0
- package/tests/setup.ts +6 -0
- package/tests/skills/SkillBase.test.ts +108 -0
- package/tests/skills/SkillManager.test.ts +268 -0
- package/tests/skills/SkillRegistry.test.ts +176 -0
- package/tests/skills/builtin.test.ts +1472 -0
- package/tests/skills/claude-skills.test.ts +54 -0
- package/tests/skills/custom-skills.test.ts +53 -0
- package/tests/skills/datasphere-serverless.test.ts +70 -0
- package/tests/skills/datasphere.test.ts +107 -0
- package/tests/skills/datetime.test.ts +101 -0
- package/tests/skills/google-maps.test.ts +78 -0
- package/tests/skills/info-gatherer.test.ts +411 -0
- package/tests/skills/joke.test.ts +81 -0
- package/tests/skills/math.test.ts +68 -0
- package/tests/skills/mcp-gateway.test.ts +101 -0
- package/tests/skills/play-background.test.ts +54 -0
- package/tests/skills/spider.test.ts +108 -0
- package/tests/skills/swml-transfer.test.ts +178 -0
- package/tests/skills/trivia.test.ts +54 -0
- package/tests/skills/vector-search.test.ts +135 -0
- package/tests/skills/weather-api.test.ts +77 -0
- package/tests/skills/web-search-parity.test.ts +59 -0
- package/tests/skills/web-search.test.ts +103 -0
- package/tests/skills/wikipedia.test.ts +63 -0
- package/tsconfig.json +18 -0
- package/vitest.config.ts +9 -0
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RelayClient — WebSocket + JSON-RPC 2.0 protocol + event dispatch.
|
|
3
|
+
*
|
|
4
|
+
* One instance = one persistent WebSocket connection to SignalWire RELAY.
|
|
5
|
+
*
|
|
6
|
+
* Architecture:
|
|
7
|
+
* - JSON-RPC requests tracked by `id` in `_pending`; responses resolve deferreds
|
|
8
|
+
* - signalwire.event messages ACKed back to server, then dispatched to Call/Message
|
|
9
|
+
* - Result code checking accepts any 2xx (regex /^2\d{2}$/)
|
|
10
|
+
* - signalwire.connect responses skip code checking
|
|
11
|
+
* - Execute queue for requests while disconnected
|
|
12
|
+
* - Auto-reconnect with exponential backoff
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
16
|
+
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
18
|
+
import { getLogger } from '../Logger.js';
|
|
19
|
+
import { Call } from './Call.js';
|
|
20
|
+
import { createDeferred, type Deferred } from './Deferred.js';
|
|
21
|
+
import {
|
|
22
|
+
AGENT_STRING,
|
|
23
|
+
PROTOCOL_VERSION,
|
|
24
|
+
DEFAULT_RELAY_HOST,
|
|
25
|
+
EVENT_AUTHORIZATION_STATE,
|
|
26
|
+
EVENT_CALL_DIAL,
|
|
27
|
+
EVENT_CALL_RECEIVE,
|
|
28
|
+
EVENT_CALL_STATE,
|
|
29
|
+
EVENT_MESSAGING_RECEIVE,
|
|
30
|
+
EVENT_MESSAGING_STATE,
|
|
31
|
+
METHOD_SIGNALWIRE_CONNECT,
|
|
32
|
+
METHOD_SIGNALWIRE_DISCONNECT,
|
|
33
|
+
METHOD_SIGNALWIRE_EVENT,
|
|
34
|
+
METHOD_SIGNALWIRE_PING,
|
|
35
|
+
METHOD_SIGNALWIRE_RECEIVE,
|
|
36
|
+
METHOD_SIGNALWIRE_UNRECEIVE,
|
|
37
|
+
RECONNECT_BACKOFF_FACTOR,
|
|
38
|
+
RECONNECT_MAX_DELAY,
|
|
39
|
+
RECONNECT_MIN_DELAY,
|
|
40
|
+
CLIENT_PING_INTERVAL,
|
|
41
|
+
CLIENT_PING_MAX_FAILURES,
|
|
42
|
+
SERVER_PING_TIMEOUT,
|
|
43
|
+
REQUEST_TIMEOUT,
|
|
44
|
+
EXECUTE_QUEUE_MAX,
|
|
45
|
+
} from './constants.js';
|
|
46
|
+
import { Message } from './Message.js';
|
|
47
|
+
import { RelayError } from './RelayError.js';
|
|
48
|
+
import type { CallHandler, MessageHandler, RelayClientOptions } from './types.js';
|
|
49
|
+
|
|
50
|
+
// Polyfill Symbol.asyncDispose for runtimes that don't have it yet (Node <20.4)
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
52
|
+
(Symbol as any).asyncDispose ??= Symbol.for('Symbol.asyncDispose');
|
|
53
|
+
|
|
54
|
+
const logger = getLogger('relay_client');
|
|
55
|
+
|
|
56
|
+
// Any 2xx code is considered success
|
|
57
|
+
const SUCCESS_CODE_RE = /^2\d{2}$/;
|
|
58
|
+
|
|
59
|
+
// Safety limits
|
|
60
|
+
const DEFAULT_MAX_ACTIVE_CALLS = 1000;
|
|
61
|
+
|
|
62
|
+
// Max concurrent RelayClient connections per process (env: RELAY_MAX_CONNECTIONS)
|
|
63
|
+
// Mirrors Python _MAX_CONNECTIONS (relay/client.py:81-88). Default 1, min 1,
|
|
64
|
+
// invalid env values fall back to 1.
|
|
65
|
+
function _parseMaxConnections(): number {
|
|
66
|
+
const raw = process.env.RELAY_MAX_CONNECTIONS;
|
|
67
|
+
if (raw == null || raw === '') return 1;
|
|
68
|
+
const parsed = parseInt(raw, 10);
|
|
69
|
+
if (isNaN(parsed)) return 1;
|
|
70
|
+
return Math.max(1, parsed);
|
|
71
|
+
}
|
|
72
|
+
const _MAX_CONNECTIONS = _parseMaxConnections();
|
|
73
|
+
|
|
74
|
+
// Process-wide tracking of active RelayClient instances. Python uses id(self);
|
|
75
|
+
// TS has no such helper, so we track instance refs — identity equality is fine.
|
|
76
|
+
const _activeClients: Set<RelayClient> = new Set();
|
|
77
|
+
|
|
78
|
+
type WsLike = {
|
|
79
|
+
send(data: string): void;
|
|
80
|
+
close(code?: number, reason?: string): void;
|
|
81
|
+
on(event: string, listener: (...args: any[]) => void): void;
|
|
82
|
+
removeAllListeners(): void;
|
|
83
|
+
readyState: number;
|
|
84
|
+
ping?(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export class RelayClient {
|
|
88
|
+
readonly project: string;
|
|
89
|
+
readonly token: string;
|
|
90
|
+
readonly jwtToken: string;
|
|
91
|
+
readonly host: string;
|
|
92
|
+
readonly contexts: string[];
|
|
93
|
+
|
|
94
|
+
private _ws: WsLike | null = null;
|
|
95
|
+
private _pending = new Map<string, Deferred<Record<string, unknown>>>();
|
|
96
|
+
private _pendingMethods = new Map<string, string>();
|
|
97
|
+
private _calls = new Map<string, Call>();
|
|
98
|
+
private _messages = new Map<string, Message>();
|
|
99
|
+
private _pendingDials = new Map<string, Deferred<Call>>();
|
|
100
|
+
private _dialCallsByTag = new Map<string, Call[]>();
|
|
101
|
+
private _executeQueue: Array<{
|
|
102
|
+
message: Record<string, unknown>;
|
|
103
|
+
deferred: Deferred<Record<string, unknown>>;
|
|
104
|
+
}> = [];
|
|
105
|
+
|
|
106
|
+
private _onCallHandler: CallHandler | null = null;
|
|
107
|
+
private _onMessageHandler: MessageHandler | null = null;
|
|
108
|
+
|
|
109
|
+
private _connected = false;
|
|
110
|
+
private _closing = false;
|
|
111
|
+
private _reconnectDelay = RECONNECT_MIN_DELAY;
|
|
112
|
+
private _relayProtocol = '';
|
|
113
|
+
private _identity = '';
|
|
114
|
+
private _authorizationState = '';
|
|
115
|
+
private _pingInterval: ReturnType<typeof setInterval> | null = null;
|
|
116
|
+
private _pingFailures = 0;
|
|
117
|
+
private _serverPingTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
118
|
+
private _maxActiveCalls = DEFAULT_MAX_ACTIVE_CALLS;
|
|
119
|
+
|
|
120
|
+
// For run() — resolves when shutdown requested
|
|
121
|
+
private _shutdownDeferred: Deferred<void> | null = null;
|
|
122
|
+
private _signalHandlers: Array<() => void> = [];
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* WebSocket constructor override for testing.
|
|
126
|
+
* @internal
|
|
127
|
+
*/
|
|
128
|
+
_wsFactory: ((url: string) => WsLike) | null = null;
|
|
129
|
+
|
|
130
|
+
constructor(options: RelayClientOptions = {}) {
|
|
131
|
+
this.project = options.project ?? process.env.SIGNALWIRE_PROJECT_ID ?? '';
|
|
132
|
+
this.token = options.token ?? process.env.SIGNALWIRE_API_TOKEN ?? '';
|
|
133
|
+
this.jwtToken = options.jwtToken ?? process.env.SIGNALWIRE_JWT_TOKEN ?? '';
|
|
134
|
+
this.host = options.host ?? process.env.SIGNALWIRE_SPACE ?? DEFAULT_RELAY_HOST;
|
|
135
|
+
this.contexts = options.contexts ?? [];
|
|
136
|
+
|
|
137
|
+
if (this.jwtToken) {
|
|
138
|
+
// JWT auth — project/token not required
|
|
139
|
+
} else if (!this.project || !this.token) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
'project and token are required (or provide jwt_token). ' +
|
|
142
|
+
'Pass them directly or set SIGNALWIRE_PROJECT_ID / SIGNALWIRE_API_TOKEN env vars.',
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Validate host
|
|
147
|
+
if (/[@/?#\r\n ]/.test(this.host)) {
|
|
148
|
+
throw new Error(`Invalid host: ${this.host}. Must be a hostname, not a URL.`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Max concurrent calls (constructor > env var > default)
|
|
152
|
+
if (options.maxActiveCalls != null) {
|
|
153
|
+
this._maxActiveCalls = Math.max(1, options.maxActiveCalls);
|
|
154
|
+
} else {
|
|
155
|
+
const envVal = process.env.RELAY_MAX_ACTIVE_CALLS ?? '';
|
|
156
|
+
const parsed = parseInt(envVal, 10);
|
|
157
|
+
this._maxActiveCalls = envVal && !isNaN(parsed) ? Math.max(1, parsed) : DEFAULT_MAX_ACTIVE_CALLS;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
get relayProtocol(): string {
|
|
162
|
+
return this._relayProtocol;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Async disposable support — equivalent to Python's `__aexit__`.
|
|
167
|
+
*
|
|
168
|
+
* Enables usage with `await using`:
|
|
169
|
+
* ```ts
|
|
170
|
+
* await using client = new RelayClient({ ... });
|
|
171
|
+
* await client.connect();
|
|
172
|
+
* // ... automatically disconnects when scope exits
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* For environments without `await using`, use try/finally:
|
|
176
|
+
* ```ts
|
|
177
|
+
* const client = new RelayClient({ ... });
|
|
178
|
+
* try { await client.connect(); ... }
|
|
179
|
+
* finally { await client.disconnect(); }
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
183
|
+
await this.disconnect();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ─── Handler Registration ──────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
/** Register the inbound call handler. Returns the handler to support decorator usage. */
|
|
189
|
+
onCall(handler: CallHandler): CallHandler {
|
|
190
|
+
this._onCallHandler = handler;
|
|
191
|
+
return handler;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Register the inbound message handler. Returns the handler to support decorator usage. */
|
|
195
|
+
onMessage(handler: MessageHandler): MessageHandler {
|
|
196
|
+
this._onMessageHandler = handler;
|
|
197
|
+
return handler;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ─── Connection Lifecycle ──────────────────────────────────────
|
|
201
|
+
|
|
202
|
+
/** Connect to RELAY and authenticate. */
|
|
203
|
+
async connect(): Promise<void> {
|
|
204
|
+
// Guard against connection leaks — enforce per-process limit.
|
|
205
|
+
// Don't count ourselves (allows reconnect without double-counting).
|
|
206
|
+
// Mirrors Python relay/client.py:216-228.
|
|
207
|
+
let otherCount = 0;
|
|
208
|
+
for (const c of _activeClients) {
|
|
209
|
+
if (c !== this) otherCount++;
|
|
210
|
+
}
|
|
211
|
+
if (otherCount >= _MAX_CONNECTIONS) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
`RelayClient connection limit reached (${_MAX_CONNECTIONS}). ` +
|
|
214
|
+
`There are already ${otherCount} active connection(s) in this process. ` +
|
|
215
|
+
`Call disconnect() on existing clients first, or set ` +
|
|
216
|
+
`RELAY_MAX_CONNECTIONS env var to allow more.`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
_activeClients.add(this);
|
|
220
|
+
|
|
221
|
+
const uri = `wss://${this.host}`;
|
|
222
|
+
logger.info(`Connecting to ${uri}`);
|
|
223
|
+
|
|
224
|
+
const ws = this._wsFactory
|
|
225
|
+
? this._wsFactory(uri)
|
|
226
|
+
: await this._createWebSocket(uri);
|
|
227
|
+
|
|
228
|
+
this._ws = ws;
|
|
229
|
+
this._connected = true;
|
|
230
|
+
this._reconnectDelay = RECONNECT_MIN_DELAY;
|
|
231
|
+
|
|
232
|
+
// Set up message handling
|
|
233
|
+
this._setupWsListeners(ws);
|
|
234
|
+
|
|
235
|
+
// Authenticate
|
|
236
|
+
await this._authenticate();
|
|
237
|
+
|
|
238
|
+
// Start client ping loop
|
|
239
|
+
this._pingFailures = 0;
|
|
240
|
+
this._startPingLoop();
|
|
241
|
+
|
|
242
|
+
// Flush queued requests
|
|
243
|
+
this._flushExecuteQueue();
|
|
244
|
+
|
|
245
|
+
logger.info('Connected and authenticated to RELAY');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Create a real WebSocket (uses dynamic import for ws). */
|
|
249
|
+
private async _createWebSocket(uri: string): Promise<WsLike> {
|
|
250
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
251
|
+
const wsModule = await import('ws');
|
|
252
|
+
const WS = wsModule.default ?? wsModule;
|
|
253
|
+
return new WS(uri, { maxPayload: 10 * 1024 * 1024 }) as unknown as WsLike;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private _setupWsListeners(ws: WsLike): void {
|
|
257
|
+
ws.on('message', (data: any) => {
|
|
258
|
+
const raw = typeof data === 'string' ? data : data.toString();
|
|
259
|
+
let msg: Record<string, any>;
|
|
260
|
+
try {
|
|
261
|
+
msg = JSON.parse(raw);
|
|
262
|
+
} catch {
|
|
263
|
+
logger.warn(`Invalid JSON received: ${raw}`);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
logger.debug(`<< ${raw}`);
|
|
267
|
+
this._handleMessage(msg).catch((err) => {
|
|
268
|
+
logger.error(`Error handling message: ${err}`);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
ws.on('close', () => {
|
|
273
|
+
logger.info('WebSocket connection closed');
|
|
274
|
+
this._connected = false;
|
|
275
|
+
this._stopPingLoop();
|
|
276
|
+
this._cancelServerPingTimeout();
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
ws.on('error', (err: any) => {
|
|
280
|
+
logger.error(`WebSocket error: ${err}`);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// Server ping (if ws supports it)
|
|
284
|
+
ws.on('ping', () => {
|
|
285
|
+
this._resetServerPingTimeout();
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Send signalwire.connect and wait for the response. */
|
|
290
|
+
private async _authenticate(): Promise<void> {
|
|
291
|
+
let authentication: Record<string, unknown>;
|
|
292
|
+
if (this.jwtToken) {
|
|
293
|
+
authentication = { jwt_token: this.jwtToken };
|
|
294
|
+
} else {
|
|
295
|
+
authentication = { project: this.project, token: this.token };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const params: Record<string, unknown> = {
|
|
299
|
+
version: PROTOCOL_VERSION,
|
|
300
|
+
agent: AGENT_STRING,
|
|
301
|
+
event_acks: true,
|
|
302
|
+
authentication,
|
|
303
|
+
};
|
|
304
|
+
if (this.contexts.length > 0) {
|
|
305
|
+
params.contexts = this.contexts;
|
|
306
|
+
}
|
|
307
|
+
if (this._relayProtocol) {
|
|
308
|
+
params.protocol = this._relayProtocol;
|
|
309
|
+
}
|
|
310
|
+
if (this._authorizationState) {
|
|
311
|
+
params.authorization_state = this._authorizationState;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const result = await this._sendRequest(METHOD_SIGNALWIRE_CONNECT, params);
|
|
315
|
+
|
|
316
|
+
this._relayProtocol = (result.protocol as string) ?? this._relayProtocol;
|
|
317
|
+
this._identity = (result.identity as string) ?? this._identity;
|
|
318
|
+
logger.debug(`Auth response: protocol=${this._relayProtocol} identity=${this._identity}`);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Cleanly close the connection. */
|
|
322
|
+
async disconnect(): Promise<void> {
|
|
323
|
+
this._closing = true;
|
|
324
|
+
this._connected = false;
|
|
325
|
+
// Mirrors Python relay/client.py:290 — remove from per-process active set.
|
|
326
|
+
// Safe to call even if we never connected (Set.delete is idempotent).
|
|
327
|
+
_activeClients.delete(this);
|
|
328
|
+
this._stopPingLoop();
|
|
329
|
+
this._cancelServerPingTimeout();
|
|
330
|
+
|
|
331
|
+
if (this._ws) {
|
|
332
|
+
this._ws.removeAllListeners();
|
|
333
|
+
this._ws.close();
|
|
334
|
+
this._ws = null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Reject all pending
|
|
338
|
+
this._clearPendingRequests();
|
|
339
|
+
|
|
340
|
+
// Cancel queued requests
|
|
341
|
+
for (const { deferred } of this._executeQueue) {
|
|
342
|
+
if (!deferred.settled) {
|
|
343
|
+
deferred.reject(new RelayError(-1, 'Connection closed'));
|
|
344
|
+
deferred.promise.catch(() => {});
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
this._executeQueue = [];
|
|
348
|
+
|
|
349
|
+
// Cancel pending dials
|
|
350
|
+
for (const deferred of Array.from(this._pendingDials.values())) {
|
|
351
|
+
if (!deferred.settled) {
|
|
352
|
+
deferred.reject(new RelayError(-1, 'Connection closed during dial'));
|
|
353
|
+
deferred.promise.catch(() => {});
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
this._pendingDials.clear();
|
|
357
|
+
this._dialCallsByTag.clear();
|
|
358
|
+
|
|
359
|
+
logger.info('Disconnected from RELAY');
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ─── Public RPC Interface ──────────────────────────────────────
|
|
363
|
+
|
|
364
|
+
/** Send a JSON-RPC request and await the response. */
|
|
365
|
+
async execute(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
366
|
+
return this._sendRequest(method, params);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Initiate an outbound call. Returns a Call when answered.
|
|
371
|
+
*
|
|
372
|
+
* @param devices - Array of device lists (serial/parallel dial).
|
|
373
|
+
* @param options.tag - Client-provided tag for event correlation. Auto-generated if not supplied.
|
|
374
|
+
* @param options.maxDuration - Optional max call duration in minutes.
|
|
375
|
+
* @param options.dialTimeout - How long (seconds) to wait for the dial to complete. Defaults to 120.
|
|
376
|
+
*/
|
|
377
|
+
async dial(
|
|
378
|
+
devices: Record<string, unknown>[][],
|
|
379
|
+
options: {
|
|
380
|
+
tag?: string;
|
|
381
|
+
maxDuration?: number;
|
|
382
|
+
/** Dial timeout in seconds (default 120). */
|
|
383
|
+
dialTimeout?: number;
|
|
384
|
+
} = {},
|
|
385
|
+
): Promise<Call> {
|
|
386
|
+
const dialTag = options.tag ?? randomUUID();
|
|
387
|
+
const params: Record<string, unknown> = {
|
|
388
|
+
tag: dialTag,
|
|
389
|
+
devices,
|
|
390
|
+
};
|
|
391
|
+
if (options.maxDuration != null) params.max_duration = options.maxDuration;
|
|
392
|
+
|
|
393
|
+
// Register a deferred that _handleEvent will resolve
|
|
394
|
+
const dialDeferred = createDeferred<Call>();
|
|
395
|
+
this._pendingDials.set(dialTag, dialDeferred);
|
|
396
|
+
this._dialCallsByTag.set(dialTag, []);
|
|
397
|
+
|
|
398
|
+
try {
|
|
399
|
+
await this.execute('calling.dial', params);
|
|
400
|
+
|
|
401
|
+
const timeoutSec = options.dialTimeout ?? 120;
|
|
402
|
+
const timeoutMs = timeoutSec * 1000;
|
|
403
|
+
const call = await new Promise<Call>((resolve, reject) => {
|
|
404
|
+
const timer = setTimeout(() => {
|
|
405
|
+
reject(new RelayError(-1, `Dial timed out waiting for answer (tag=${dialTag})`));
|
|
406
|
+
}, timeoutMs);
|
|
407
|
+
dialDeferred.promise.then(
|
|
408
|
+
(v) => { clearTimeout(timer); resolve(v); },
|
|
409
|
+
(e) => { clearTimeout(timer); reject(e); },
|
|
410
|
+
);
|
|
411
|
+
});
|
|
412
|
+
return call;
|
|
413
|
+
} catch (err) {
|
|
414
|
+
if (!dialDeferred.settled) {
|
|
415
|
+
dialDeferred.reject(err);
|
|
416
|
+
dialDeferred.promise.catch(() => {});
|
|
417
|
+
}
|
|
418
|
+
throw err;
|
|
419
|
+
} finally {
|
|
420
|
+
this._pendingDials.delete(dialTag);
|
|
421
|
+
this._dialCallsByTag.delete(dialTag);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Send an outbound SMS/MMS message. Returns a Message.
|
|
427
|
+
*
|
|
428
|
+
* @param options.toNumber - Destination phone number in E.164 format.
|
|
429
|
+
* @param options.fromNumber - Sender phone number in E.164 format.
|
|
430
|
+
* @param options.context - Context for receiving state events. Defaults to the relay protocol.
|
|
431
|
+
* @param options.body - Text body of the message.
|
|
432
|
+
* @param options.media - List of media URLs for MMS.
|
|
433
|
+
* @param options.tags - Optional tags for the message.
|
|
434
|
+
* @param options.region - Optional origination region.
|
|
435
|
+
* @param options.onCompleted - Optional callback fired when a terminal state is reached.
|
|
436
|
+
*/
|
|
437
|
+
async sendMessage(options: {
|
|
438
|
+
toNumber: string;
|
|
439
|
+
fromNumber: string;
|
|
440
|
+
context?: string;
|
|
441
|
+
body?: string;
|
|
442
|
+
media?: string[];
|
|
443
|
+
tags?: string[];
|
|
444
|
+
region?: string;
|
|
445
|
+
onCompleted?: (event: any) => void | Promise<void>;
|
|
446
|
+
}): Promise<Message> {
|
|
447
|
+
if (!options.body && (!options.media || options.media.length === 0)) {
|
|
448
|
+
throw new Error('At least one of body or media is required');
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const msgContext = options.context ?? this._relayProtocol ?? 'default';
|
|
452
|
+
const params: Record<string, unknown> = {
|
|
453
|
+
context: msgContext,
|
|
454
|
+
to_number: options.toNumber,
|
|
455
|
+
from_number: options.fromNumber,
|
|
456
|
+
};
|
|
457
|
+
if (options.body) params.body = options.body;
|
|
458
|
+
if (options.media) params.media = options.media;
|
|
459
|
+
if (options.tags) params.tags = options.tags;
|
|
460
|
+
if (options.region) params.region = options.region;
|
|
461
|
+
|
|
462
|
+
const result = await this.execute('messaging.send', params);
|
|
463
|
+
|
|
464
|
+
const messageId = (result.message_id as string) ?? '';
|
|
465
|
+
const message = new Message({
|
|
466
|
+
messageId,
|
|
467
|
+
context: msgContext,
|
|
468
|
+
direction: 'outbound',
|
|
469
|
+
fromNumber: options.fromNumber,
|
|
470
|
+
toNumber: options.toNumber,
|
|
471
|
+
body: options.body ?? '',
|
|
472
|
+
media: options.media ?? [],
|
|
473
|
+
tags: options.tags ?? [],
|
|
474
|
+
state: 'queued',
|
|
475
|
+
});
|
|
476
|
+
if (options.onCompleted) {
|
|
477
|
+
message._onCompleted = options.onCompleted;
|
|
478
|
+
}
|
|
479
|
+
if (messageId) {
|
|
480
|
+
this._messages.set(messageId, message);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return message;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Subscribe to additional contexts. */
|
|
487
|
+
async receive(contexts: string[]): Promise<void> {
|
|
488
|
+
if (!contexts.length) return;
|
|
489
|
+
await this._sendRequest(METHOD_SIGNALWIRE_RECEIVE, { contexts });
|
|
490
|
+
logger.info(`Subscribed to contexts: ${contexts}`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Unsubscribe from contexts. */
|
|
494
|
+
async unreceive(contexts: string[]): Promise<void> {
|
|
495
|
+
if (!contexts.length) return;
|
|
496
|
+
await this._sendRequest(METHOD_SIGNALWIRE_UNRECEIVE, { contexts });
|
|
497
|
+
logger.info(`Unsubscribed from contexts: ${contexts}`);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// ─── Run (auto-reconnect loop) ────────────────────────────────
|
|
501
|
+
|
|
502
|
+
/** Blocking entry point — connects and maintains connection with auto-reconnect. */
|
|
503
|
+
async run(): Promise<void> {
|
|
504
|
+
this._closing = false;
|
|
505
|
+
this._shutdownDeferred = createDeferred<void>();
|
|
506
|
+
|
|
507
|
+
// Handle SIGINT/SIGTERM
|
|
508
|
+
const shutdown = () => {
|
|
509
|
+
logger.info('Shutting down ...');
|
|
510
|
+
this._closing = true;
|
|
511
|
+
if (this._ws) {
|
|
512
|
+
this._ws.close();
|
|
513
|
+
}
|
|
514
|
+
this._shutdownDeferred?.resolve();
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
process.on('SIGINT', shutdown);
|
|
518
|
+
process.on('SIGTERM', shutdown);
|
|
519
|
+
this._signalHandlers = [
|
|
520
|
+
() => process.removeListener('SIGINT', shutdown),
|
|
521
|
+
() => process.removeListener('SIGTERM', shutdown),
|
|
522
|
+
];
|
|
523
|
+
|
|
524
|
+
try {
|
|
525
|
+
while (!this._closing) {
|
|
526
|
+
try {
|
|
527
|
+
await this.connect();
|
|
528
|
+
|
|
529
|
+
// Block until connection closes
|
|
530
|
+
await new Promise<void>((resolve) => {
|
|
531
|
+
if (!this._ws) { resolve(); return; }
|
|
532
|
+
this._ws.on('close', () => resolve());
|
|
533
|
+
});
|
|
534
|
+
} catch (err) {
|
|
535
|
+
if (this._closing) break;
|
|
536
|
+
logger.error(`Connection error: ${err}`);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
if (this._closing) break;
|
|
540
|
+
|
|
541
|
+
this._stopPingLoop();
|
|
542
|
+
this._cancelServerPingTimeout();
|
|
543
|
+
this._clearPendingRequests();
|
|
544
|
+
|
|
545
|
+
// Auto-reconnect with exponential backoff
|
|
546
|
+
logger.info(`Reconnecting in ${this._reconnectDelay.toFixed(1)}s ...`);
|
|
547
|
+
await new Promise<void>((resolve) => {
|
|
548
|
+
const timer = setTimeout(resolve, this._reconnectDelay * 1000);
|
|
549
|
+
// If shutdown requested during wait, resolve immediately
|
|
550
|
+
this._shutdownDeferred?.promise.then(() => {
|
|
551
|
+
clearTimeout(timer);
|
|
552
|
+
resolve();
|
|
553
|
+
});
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
if (this._closing) break;
|
|
557
|
+
|
|
558
|
+
this._reconnectDelay = Math.min(
|
|
559
|
+
this._reconnectDelay * RECONNECT_BACKOFF_FACTOR,
|
|
560
|
+
RECONNECT_MAX_DELAY,
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
} finally {
|
|
564
|
+
await this.disconnect();
|
|
565
|
+
// Cleanup signal handlers
|
|
566
|
+
for (const cleanup of this._signalHandlers) cleanup();
|
|
567
|
+
this._signalHandlers = [];
|
|
568
|
+
logger.info('RELAY client stopped');
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ─── Internal: Send / Receive ──────────────────────────────────
|
|
573
|
+
|
|
574
|
+
private async _sendRequest(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
575
|
+
const reqId = randomUUID();
|
|
576
|
+
const message: Record<string, unknown> = {
|
|
577
|
+
jsonrpc: '2.0',
|
|
578
|
+
id: reqId,
|
|
579
|
+
method,
|
|
580
|
+
params,
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
const deferred = createDeferred<Record<string, unknown>>();
|
|
584
|
+
this._pending.set(reqId, deferred);
|
|
585
|
+
this._pendingMethods.set(reqId, method);
|
|
586
|
+
|
|
587
|
+
try {
|
|
588
|
+
if (!this._ws || !this._connected) {
|
|
589
|
+
if (this._executeQueue.length >= EXECUTE_QUEUE_MAX) {
|
|
590
|
+
throw new RelayError(-1, 'Execute queue full — too many requests while disconnected');
|
|
591
|
+
}
|
|
592
|
+
this._executeQueue.push({ message, deferred });
|
|
593
|
+
logger.debug(`Request queued (not connected): ${method}`);
|
|
594
|
+
} else {
|
|
595
|
+
const raw = JSON.stringify(message);
|
|
596
|
+
logger.debug(`>> ${method} id=${reqId}`);
|
|
597
|
+
this._ws.send(raw);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// Timeout
|
|
601
|
+
return await new Promise<Record<string, unknown>>((resolve, reject) => {
|
|
602
|
+
const timer = setTimeout(() => {
|
|
603
|
+
reject(new RelayError(-1, `Request timeout for ${method}`));
|
|
604
|
+
if (method !== METHOD_SIGNALWIRE_CONNECT) {
|
|
605
|
+
this._forceClose();
|
|
606
|
+
}
|
|
607
|
+
}, REQUEST_TIMEOUT);
|
|
608
|
+
|
|
609
|
+
deferred.promise.then(
|
|
610
|
+
(v) => { clearTimeout(timer); resolve(v); },
|
|
611
|
+
(e) => { clearTimeout(timer); reject(e); },
|
|
612
|
+
);
|
|
613
|
+
});
|
|
614
|
+
} finally {
|
|
615
|
+
this._pending.delete(reqId);
|
|
616
|
+
this._pendingMethods.delete(reqId);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
private _flushExecuteQueue(): void {
|
|
621
|
+
if (!this._executeQueue.length || !this._ws) return;
|
|
622
|
+
const queued = [...this._executeQueue];
|
|
623
|
+
this._executeQueue = [];
|
|
624
|
+
logger.debug(`Flushing ${queued.length} queued requests`);
|
|
625
|
+
for (const { message, deferred } of queued) {
|
|
626
|
+
if (deferred.settled) continue;
|
|
627
|
+
const raw = JSON.stringify(message);
|
|
628
|
+
logger.debug(`>> (queued) ${message.method ?? '?'} id=${message.id ?? '?'}`);
|
|
629
|
+
try {
|
|
630
|
+
this._ws!.send(raw);
|
|
631
|
+
} catch (err) {
|
|
632
|
+
if (!deferred.settled) {
|
|
633
|
+
deferred.reject(new RelayError(-1, `Failed to send queued request: ${err}`));
|
|
634
|
+
deferred.promise.catch(() => {});
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
private _clearPendingRequests(): void {
|
|
641
|
+
for (const deferred of Array.from(this._pending.values())) {
|
|
642
|
+
if (!deferred.settled) {
|
|
643
|
+
deferred.reject(new RelayError(-1, 'Connection closed'));
|
|
644
|
+
deferred.promise.catch(() => {});
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
this._pending.clear();
|
|
648
|
+
this._pendingMethods.clear();
|
|
649
|
+
|
|
650
|
+
for (const deferred of Array.from(this._pendingDials.values())) {
|
|
651
|
+
if (!deferred.settled) {
|
|
652
|
+
deferred.reject(new RelayError(-1, 'Connection closed during dial'));
|
|
653
|
+
deferred.promise.catch(() => {});
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
this._pendingDials.clear();
|
|
657
|
+
this._dialCallsByTag.clear();
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// ─── Message Handling ──────────────────────────────────────────
|
|
661
|
+
|
|
662
|
+
private async _handleMessage(msg: Record<string, any>): Promise<void> {
|
|
663
|
+
if (typeof msg !== 'object' || msg === null) {
|
|
664
|
+
logger.warn('Ignoring non-object message');
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// JSON-RPC error response
|
|
669
|
+
if ('id' in msg && 'error' in msg) {
|
|
670
|
+
const reqId = msg.id as string;
|
|
671
|
+
const deferred = this._pending.get(reqId);
|
|
672
|
+
if (deferred && !deferred.settled) {
|
|
673
|
+
const error = typeof msg.error === 'object' ? msg.error : { code: -1, message: String(msg.error) };
|
|
674
|
+
deferred.reject(new RelayError(
|
|
675
|
+
error.code ?? -1,
|
|
676
|
+
String(error.message ?? 'Unknown error'),
|
|
677
|
+
));
|
|
678
|
+
}
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// JSON-RPC success response
|
|
683
|
+
if ('id' in msg && 'result' in msg) {
|
|
684
|
+
const reqId = msg.id as string;
|
|
685
|
+
const deferred = this._pending.get(reqId);
|
|
686
|
+
if (deferred && !deferred.settled) {
|
|
687
|
+
const result = msg.result;
|
|
688
|
+
if (typeof result !== 'object' || result === null) {
|
|
689
|
+
deferred.resolve({ raw: result });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const requestMethod = this._pendingMethods.get(reqId) ?? '';
|
|
693
|
+
if (requestMethod === METHOD_SIGNALWIRE_CONNECT) {
|
|
694
|
+
deferred.resolve(result);
|
|
695
|
+
} else {
|
|
696
|
+
const code = result.code;
|
|
697
|
+
const codeStr = code != null ? String(code) : null;
|
|
698
|
+
if (codeStr != null && !SUCCESS_CODE_RE.test(codeStr)) {
|
|
699
|
+
let intCode: number;
|
|
700
|
+
try { intCode = parseInt(codeStr, 10); } catch { intCode = -1; }
|
|
701
|
+
if (isNaN(intCode)) intCode = -1;
|
|
702
|
+
deferred.reject(new RelayError(
|
|
703
|
+
intCode,
|
|
704
|
+
String(result.message ?? 'Unknown error'),
|
|
705
|
+
));
|
|
706
|
+
} else {
|
|
707
|
+
deferred.resolve(result);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Server-initiated method call
|
|
715
|
+
const method = (msg.method ?? '') as string;
|
|
716
|
+
const params = (msg.params ?? {}) as Record<string, any>;
|
|
717
|
+
if (typeof params !== 'object') {
|
|
718
|
+
logger.warn('Ignoring message with non-object params');
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
if (method === METHOD_SIGNALWIRE_EVENT) {
|
|
723
|
+
if ('id' in msg) {
|
|
724
|
+
this._sendEventAck(msg.id as string);
|
|
725
|
+
}
|
|
726
|
+
await this._handleEvent(params);
|
|
727
|
+
} else if (method === METHOD_SIGNALWIRE_PING) {
|
|
728
|
+
this._resetServerPingTimeout();
|
|
729
|
+
if ('id' in msg) {
|
|
730
|
+
this._sendPong(msg.id as string);
|
|
731
|
+
}
|
|
732
|
+
} else if (method === METHOD_SIGNALWIRE_DISCONNECT) {
|
|
733
|
+
const restart = params.restart ?? false;
|
|
734
|
+
logger.info(`Received signalwire.disconnect from server (restart=${restart})`);
|
|
735
|
+
if ('id' in msg) {
|
|
736
|
+
this._sendEventAck(msg.id as string);
|
|
737
|
+
}
|
|
738
|
+
if (restart) {
|
|
739
|
+
this._relayProtocol = '';
|
|
740
|
+
this._authorizationState = '';
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// ─── Event Dispatch ────────────────────────────────────────────
|
|
746
|
+
|
|
747
|
+
private async _handleEvent(payload: Record<string, any>): Promise<void> {
|
|
748
|
+
const eventType = (payload.event_type ?? '') as string;
|
|
749
|
+
const eventParams = (payload.params ?? {}) as Record<string, any>;
|
|
750
|
+
const callId = (eventParams.call_id ?? '') as string;
|
|
751
|
+
|
|
752
|
+
if (!eventType) {
|
|
753
|
+
logger.warn(`Received event with empty event_type: ${JSON.stringify(payload)}`);
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
logger.debug(`Event: ${eventType} call_id=${callId}`);
|
|
758
|
+
|
|
759
|
+
// Authorization state update
|
|
760
|
+
if (eventType === EVENT_AUTHORIZATION_STATE) {
|
|
761
|
+
const authState = (eventParams.authorization_state ?? '') as string;
|
|
762
|
+
if (authState) {
|
|
763
|
+
this._authorizationState = authState;
|
|
764
|
+
logger.debug('Updated authorization_state for reconnection');
|
|
765
|
+
}
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// Inbound message
|
|
770
|
+
if (eventType === EVENT_MESSAGING_RECEIVE) {
|
|
771
|
+
this._handleInboundMessage(payload);
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// Outbound message state change
|
|
776
|
+
if (eventType === EVENT_MESSAGING_STATE) {
|
|
777
|
+
this._handleMessageState(payload);
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Inbound call
|
|
782
|
+
if (eventType === EVENT_CALL_RECEIVE) {
|
|
783
|
+
this._handleInboundCall(payload);
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// Outbound dial progress
|
|
788
|
+
if (eventType === EVENT_CALL_DIAL) {
|
|
789
|
+
await this._handleDialEvent(payload);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// State events during pending dial
|
|
794
|
+
if (eventType === EVENT_CALL_STATE) {
|
|
795
|
+
const tag = (eventParams.tag ?? '') as string;
|
|
796
|
+
if (tag && this._pendingDials.has(tag) && callId) {
|
|
797
|
+
if (!this._calls.has(callId)) {
|
|
798
|
+
this._registerDialLeg(tag, eventParams);
|
|
799
|
+
}
|
|
800
|
+
// Fall through to normal routing
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// Route to existing Call by call_id
|
|
805
|
+
if (callId) {
|
|
806
|
+
const call = this._calls.get(callId);
|
|
807
|
+
if (call) {
|
|
808
|
+
await call._dispatchEvent(payload);
|
|
809
|
+
if (call.state === 'ended') {
|
|
810
|
+
this._calls.delete(callId);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
private _handleInboundCall(payload: Record<string, any>): void {
|
|
817
|
+
if (this._calls.size >= this._maxActiveCalls) {
|
|
818
|
+
logger.error(`Max active calls (${this._maxActiveCalls}) reached, dropping inbound call`);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
const params = (payload.params ?? {}) as Record<string, any>;
|
|
822
|
+
const callId = (params.call_id ?? '') as string;
|
|
823
|
+
|
|
824
|
+
const call = new Call(
|
|
825
|
+
this,
|
|
826
|
+
callId,
|
|
827
|
+
params.node_id ?? '',
|
|
828
|
+
params.project_id ?? this.project,
|
|
829
|
+
this._relayProtocol || params.context || params.protocol || '',
|
|
830
|
+
{
|
|
831
|
+
tag: params.tag ?? '',
|
|
832
|
+
direction: params.direction ?? 'inbound',
|
|
833
|
+
device: params.device,
|
|
834
|
+
state: params.call_state ?? 'created',
|
|
835
|
+
segmentId: params.segment_id ?? '',
|
|
836
|
+
},
|
|
837
|
+
);
|
|
838
|
+
this._calls.set(callId, call);
|
|
839
|
+
|
|
840
|
+
if (this._onCallHandler) {
|
|
841
|
+
Promise.resolve(this._onCallHandler(call)).catch((err) => {
|
|
842
|
+
logger.error(`Error in on_call handler for ${callId}: ${err}`);
|
|
843
|
+
});
|
|
844
|
+
} else {
|
|
845
|
+
logger.warn(`Inbound call ${callId} but no on_call handler registered`);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
private _handleInboundMessage(payload: Record<string, any>): void {
|
|
850
|
+
const params = (payload.params ?? {}) as Record<string, any>;
|
|
851
|
+
const message = new Message({
|
|
852
|
+
messageId: params.message_id ?? '',
|
|
853
|
+
context: params.context ?? '',
|
|
854
|
+
direction: params.direction ?? 'inbound',
|
|
855
|
+
fromNumber: params.from_number ?? '',
|
|
856
|
+
toNumber: params.to_number ?? '',
|
|
857
|
+
body: params.body ?? '',
|
|
858
|
+
media: params.media ?? [],
|
|
859
|
+
segments: params.segments ?? 0,
|
|
860
|
+
state: params.message_state ?? 'received',
|
|
861
|
+
tags: params.tags ?? [],
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
if (this._onMessageHandler) {
|
|
865
|
+
Promise.resolve(this._onMessageHandler(message)).catch((err) => {
|
|
866
|
+
logger.error(`Error in on_message handler for ${message.messageId}: ${err}`);
|
|
867
|
+
});
|
|
868
|
+
} else {
|
|
869
|
+
logger.warn(`Inbound message ${message.messageId} but no on_message handler registered`);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
private _handleMessageState(payload: Record<string, any>): void {
|
|
874
|
+
const params = (payload.params ?? {}) as Record<string, any>;
|
|
875
|
+
const messageId = (params.message_id ?? '') as string;
|
|
876
|
+
const message = this._messages.get(messageId);
|
|
877
|
+
if (message) {
|
|
878
|
+
message._dispatchEvent(payload).catch((err) => {
|
|
879
|
+
logger.error(`Error dispatching message state for ${messageId}: ${err}`);
|
|
880
|
+
});
|
|
881
|
+
if (message.isDone) {
|
|
882
|
+
this._messages.delete(messageId);
|
|
883
|
+
}
|
|
884
|
+
} else {
|
|
885
|
+
logger.debug(`State event for unknown message ${messageId}`);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
private _registerDialLeg(tag: string, eventParams: Record<string, any>): Call {
|
|
890
|
+
const callId = (eventParams.call_id ?? '') as string;
|
|
891
|
+
const nodeId = (eventParams.node_id ?? '') as string;
|
|
892
|
+
const call = new Call(
|
|
893
|
+
this,
|
|
894
|
+
callId,
|
|
895
|
+
nodeId,
|
|
896
|
+
eventParams.project_id ?? this.project,
|
|
897
|
+
this._relayProtocol,
|
|
898
|
+
{
|
|
899
|
+
tag,
|
|
900
|
+
direction: 'outbound',
|
|
901
|
+
device: eventParams.device,
|
|
902
|
+
state: eventParams.call_state ?? 'created',
|
|
903
|
+
},
|
|
904
|
+
);
|
|
905
|
+
this._calls.set(callId, call);
|
|
906
|
+
const legs = this._dialCallsByTag.get(tag) ?? [];
|
|
907
|
+
legs.push(call);
|
|
908
|
+
this._dialCallsByTag.set(tag, legs);
|
|
909
|
+
logger.debug(`Registered dial leg: call_id=${callId} tag=${tag}`);
|
|
910
|
+
return call;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
private async _handleDialEvent(payload: Record<string, any>): Promise<void> {
|
|
914
|
+
const eventParams = (payload.params ?? {}) as Record<string, any>;
|
|
915
|
+
const tag = (eventParams.tag ?? '') as string;
|
|
916
|
+
const dialState = (eventParams.dial_state ?? '') as string;
|
|
917
|
+
const callInfo = (eventParams.call ?? {}) as Record<string, any>;
|
|
918
|
+
|
|
919
|
+
logger.debug(`Dial event: tag=${tag} state=${dialState}`);
|
|
920
|
+
|
|
921
|
+
const dialDeferred = this._pendingDials.get(tag);
|
|
922
|
+
if (!dialDeferred || dialDeferred.settled) {
|
|
923
|
+
// Stale or progress event after resolution — dispatch to call if exists
|
|
924
|
+
if (callInfo) {
|
|
925
|
+
const cid = (callInfo.call_id ?? '') as string;
|
|
926
|
+
const call = this._calls.get(cid);
|
|
927
|
+
if (call) {
|
|
928
|
+
await call._dispatchEvent(payload);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
if (dialState === 'answered') {
|
|
935
|
+
const winnerCallId = (callInfo.call_id ?? '') as string;
|
|
936
|
+
const winnerNodeId = (callInfo.node_id ?? '') as string;
|
|
937
|
+
let call = this._calls.get(winnerCallId);
|
|
938
|
+
if (!call) {
|
|
939
|
+
call = new Call(
|
|
940
|
+
this,
|
|
941
|
+
winnerCallId,
|
|
942
|
+
winnerNodeId,
|
|
943
|
+
this.project,
|
|
944
|
+
this._relayProtocol,
|
|
945
|
+
{
|
|
946
|
+
tag,
|
|
947
|
+
direction: 'outbound',
|
|
948
|
+
device: callInfo.device,
|
|
949
|
+
state: 'answered',
|
|
950
|
+
},
|
|
951
|
+
);
|
|
952
|
+
this._calls.set(winnerCallId, call);
|
|
953
|
+
} else {
|
|
954
|
+
if (winnerNodeId && !call.nodeId) {
|
|
955
|
+
call.nodeId = winnerNodeId;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
dialDeferred.resolve(call);
|
|
959
|
+
} else if (dialState === 'failed') {
|
|
960
|
+
dialDeferred.reject(new RelayError(-1, `Dial failed (tag=${tag})`));
|
|
961
|
+
dialDeferred.promise.catch(() => {});
|
|
962
|
+
}
|
|
963
|
+
// "dialing" events are progress — don't resolve
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// ─── Pong / ACK ───────────────────────────────────────────────
|
|
967
|
+
|
|
968
|
+
private _sendPong(reqId: string): void {
|
|
969
|
+
if (!this._ws) return;
|
|
970
|
+
const msg = JSON.stringify({ jsonrpc: '2.0', id: reqId, result: {} });
|
|
971
|
+
this._ws.send(msg);
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
private _sendEventAck(reqId: string): void {
|
|
975
|
+
if (!this._ws) return;
|
|
976
|
+
const msg = JSON.stringify({ jsonrpc: '2.0', id: reqId, result: {} });
|
|
977
|
+
this._ws.send(msg);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// ─── Client Ping Loop ─────────────────────────────────────────
|
|
981
|
+
|
|
982
|
+
private _startPingLoop(): void {
|
|
983
|
+
this._stopPingLoop();
|
|
984
|
+
this._pingInterval = setInterval(async () => {
|
|
985
|
+
if (!this._connected || !this._ws) return;
|
|
986
|
+
try {
|
|
987
|
+
await this._sendRequest(METHOD_SIGNALWIRE_PING, {});
|
|
988
|
+
this._pingFailures = 0;
|
|
989
|
+
} catch {
|
|
990
|
+
this._pingFailures++;
|
|
991
|
+
const backoff = Math.min(
|
|
992
|
+
RECONNECT_MIN_DELAY * (RECONNECT_BACKOFF_FACTOR ** this._pingFailures),
|
|
993
|
+
RECONNECT_MAX_DELAY,
|
|
994
|
+
);
|
|
995
|
+
logger.warn(`Client ping failed (${this._pingFailures}/${CLIENT_PING_MAX_FAILURES}), backoff ${backoff.toFixed(1)}s`);
|
|
996
|
+
if (this._pingFailures >= CLIENT_PING_MAX_FAILURES) {
|
|
997
|
+
logger.error('Max ping failures reached, forcing reconnect');
|
|
998
|
+
this._forceClose();
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}, CLIENT_PING_INTERVAL);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
private _stopPingLoop(): void {
|
|
1005
|
+
if (this._pingInterval) {
|
|
1006
|
+
clearInterval(this._pingInterval);
|
|
1007
|
+
this._pingInterval = null;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// ─── Server Ping Watchdog ─────────────────────────────────────
|
|
1012
|
+
|
|
1013
|
+
private _resetServerPingTimeout(): void {
|
|
1014
|
+
this._pingFailures = 0;
|
|
1015
|
+
this._cancelServerPingTimeout();
|
|
1016
|
+
this._serverPingTimeout = setTimeout(() => {
|
|
1017
|
+
logger.debug(`No server ping received in ${SERVER_PING_TIMEOUT}ms, client pings will probe`);
|
|
1018
|
+
}, SERVER_PING_TIMEOUT);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
private _cancelServerPingTimeout(): void {
|
|
1022
|
+
if (this._serverPingTimeout) {
|
|
1023
|
+
clearTimeout(this._serverPingTimeout);
|
|
1024
|
+
this._serverPingTimeout = null;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
private _forceClose(): void {
|
|
1029
|
+
this._stopPingLoop();
|
|
1030
|
+
this._cancelServerPingTimeout();
|
|
1031
|
+
this._connected = false;
|
|
1032
|
+
if (this._ws) {
|
|
1033
|
+
this._ws.close();
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
}
|