telnyx
Version:
Telnyx API SDK for global Voice, SMS, MMS, WhatsApp, Fax, Wireless IoT, SIP Trunking, and Call Control.
1,072 lines (1,071 loc) • 65.6 kB
JavaScript
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _Telnyx_instances, _a, _Telnyx_encoder, _Telnyx_baseURLOverridden;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "./internal/tslib.mjs";
import { uuid4 } from "./internal/utils/uuid.mjs";
import { validatePositiveInteger, isAbsoluteURL, safeJSON } from "./internal/utils/values.mjs";
import { sleep } from "./internal/utils/sleep.mjs";
import { castToError, isAbortError } from "./internal/errors.mjs";
import { getPlatformHeaders } from "./internal/detect-platform.mjs";
import * as Shims from "./internal/shims.mjs";
import * as Opts from "./internal/request-options.mjs";
import { stringifyQuery } from "./internal/utils/query.mjs";
import { VERSION } from "./version.mjs";
import * as Errors from "./core/error.mjs";
import * as Pagination from "./core/pagination.mjs";
import * as Uploads from "./core/uploads.mjs";
import * as API from "./resources/index.mjs";
import { APIPromise } from "./core/api-promise.mjs";
import { AccessIPAddress, } from "./resources/access-ip-address.mjs";
import { AccessIPRanges, } from "./resources/access-ip-ranges.mjs";
import { AdvancedOrders, } from "./resources/advanced-orders.mjs";
import { AlphanumericSenderIDs, } from "./resources/alphanumeric-sender-ids.mjs";
import { AuditEvents, } from "./resources/audit-events.mjs";
import { AuthenticationProviders, } from "./resources/authentication-providers.mjs";
import { AvailablePhoneNumberBlocks, } from "./resources/available-phone-number-blocks.mjs";
import { AvailablePhoneNumbers, } from "./resources/available-phone-numbers.mjs";
import { Balance } from "./resources/balance.mjs";
import { BillingGroups, } from "./resources/billing-groups.mjs";
import { BulkSimCardActions, } from "./resources/bulk-sim-card-actions.mjs";
import { CallControlApplications, } from "./resources/call-control-applications.mjs";
import { CallEvents, } from "./resources/call-events.mjs";
import { ChannelZones, } from "./resources/channel-zones.mjs";
import { ChargesBreakdown, } from "./resources/charges-breakdown.mjs";
import { ChargesSummary, } from "./resources/charges-summary.mjs";
import { Comments, } from "./resources/comments.mjs";
import { Connections, } from "./resources/connections.mjs";
import { CountryCoverageResource, } from "./resources/country-coverage.mjs";
import { CustomStorageCredentials, } from "./resources/custom-storage-credentials.mjs";
import { CustomerServiceRecords, } from "./resources/customer-service-records.mjs";
import { DetailRecords, } from "./resources/detail-records.mjs";
import { DialogflowConnections, } from "./resources/dialogflow-connections.mjs";
import { DocumentLinks, } from "./resources/document-links.mjs";
import { Documents, } from "./resources/documents.mjs";
import { DynamicEmergencyAddresses, } from "./resources/dynamic-emergency-addresses.mjs";
import { DynamicEmergencyEndpoints, } from "./resources/dynamic-emergency-endpoints.mjs";
import { FaxApplications, } from "./resources/fax-applications.mjs";
import { FqdnConnections, } from "./resources/fqdn-connections.mjs";
import { Fqdns, } from "./resources/fqdns.mjs";
import { GlobalIPAllowedPorts } from "./resources/global-ip-allowed-ports.mjs";
import { GlobalIPAssignmentHealth, } from "./resources/global-ip-assignment-health.mjs";
import { GlobalIPAssignments, } from "./resources/global-ip-assignments.mjs";
import { GlobalIPAssignmentsUsage, } from "./resources/global-ip-assignments-usage.mjs";
import { GlobalIPHealthCheckTypes, } from "./resources/global-ip-health-check-types.mjs";
import { GlobalIPHealthChecks, } from "./resources/global-ip-health-checks.mjs";
import { GlobalIPLatency, } from "./resources/global-ip-latency.mjs";
import { GlobalIPProtocols } from "./resources/global-ip-protocols.mjs";
import { GlobalIPUsage, } from "./resources/global-ip-usage.mjs";
import { GlobalIPs, } from "./resources/global-ips.mjs";
import { InboundChannels, } from "./resources/inbound-channels.mjs";
import { InexplicitNumberOrders, } from "./resources/inexplicit-number-orders.mjs";
import { IntegrationSecrets, } from "./resources/integration-secrets.mjs";
import { InventoryCoverage, } from "./resources/inventory-coverage.mjs";
import { Invoices, } from "./resources/invoices.mjs";
import { IPConnections, } from "./resources/ip-connections.mjs";
import { IPs, } from "./resources/ips.mjs";
import { LedgerBillingGroupReports, } from "./resources/ledger-billing-group-reports.mjs";
import { List } from "./resources/list.mjs";
import { Media, } from "./resources/media.mjs";
import { MessagingHostedNumbers, } from "./resources/messaging-hosted-numbers.mjs";
import { MessagingNumbersBulkUpdates, } from "./resources/messaging-numbers-bulk-updates.mjs";
import { MessagingOptouts, } from "./resources/messaging-optouts.mjs";
import { MessagingProfileMetrics, } from "./resources/messaging-profile-metrics.mjs";
import { MessagingURLDomains, } from "./resources/messaging-url-domains.mjs";
import { MobileNetworkOperators, } from "./resources/mobile-network-operators.mjs";
import { MobilePushCredentials, } from "./resources/mobile-push-credentials.mjs";
import { MobileVoiceConnections, } from "./resources/mobile-voice-connections.mjs";
import { NetworkCoverage, } from "./resources/network-coverage.mjs";
import { NotificationChannels, } from "./resources/notification-channels.mjs";
import { NotificationEventConditions, } from "./resources/notification-event-conditions.mjs";
import { NotificationEvents, } from "./resources/notification-events.mjs";
import { NotificationProfiles, } from "./resources/notification-profiles.mjs";
import { NotificationSettings, } from "./resources/notification-settings.mjs";
import { NumberBlockOrders, } from "./resources/number-block-orders.mjs";
import { NumberLookup, } from "./resources/number-lookup.mjs";
import { NumberOrderPhoneNumbers, } from "./resources/number-order-phone-numbers.mjs";
import { NumberOrders, } from "./resources/number-orders.mjs";
import { NumbersFeatures, } from "./resources/numbers-features.mjs";
import { OAuth, } from "./resources/oauth.mjs";
import { OAuthClients, } from "./resources/oauth-clients.mjs";
import { OAuthGrants, } from "./resources/oauth-grants.mjs";
import { OtaUpdates, } from "./resources/ota-updates.mjs";
import { OutboundVoiceProfiles, } from "./resources/outbound-voice-profiles.mjs";
import { PhoneNumbersRegulatoryRequirements, } from "./resources/phone-numbers-regulatory-requirements.mjs";
import { PortabilityChecks, } from "./resources/portability-checks.mjs";
import { PortingPhoneNumbers, } from "./resources/porting-phone-numbers.mjs";
import { PrivateWirelessGateways, } from "./resources/private-wireless-gateways.mjs";
import { PronunciationDicts, } from "./resources/pronunciation-dicts.mjs";
import { PublicInternetGateways, } from "./resources/public-internet-gateways.mjs";
import { RcsAgents } from "./resources/rcs-agents.mjs";
import { RecordingTranscriptions, } from "./resources/recording-transcriptions.mjs";
import { Regions } from "./resources/regions.mjs";
import { RegulatoryRequirements, } from "./resources/regulatory-requirements.mjs";
import { RequirementGroups, } from "./resources/requirement-groups.mjs";
import { RequirementTypes, } from "./resources/requirement-types.mjs";
import { Requirements, } from "./resources/requirements.mjs";
import { RoomCompositions, } from "./resources/room-compositions.mjs";
import { RoomParticipants, } from "./resources/room-participants.mjs";
import { RoomRecordings, } from "./resources/room-recordings.mjs";
import { Seti, } from "./resources/seti.mjs";
import { ShortCodes, } from "./resources/short-codes.mjs";
import { SimCardDataUsageNotifications, } from "./resources/sim-card-data-usage-notifications.mjs";
import { SimCardOrderPreview, } from "./resources/sim-card-order-preview.mjs";
import { SimCardOrders, } from "./resources/sim-card-orders.mjs";
import { SiprecConnectors, } from "./resources/siprec-connectors.mjs";
import { SubNumberOrders, } from "./resources/sub-number-orders.mjs";
import { SubNumberOrdersReportResource, } from "./resources/sub-number-orders-report.mjs";
import { TelephonyCredentials, } from "./resources/telephony-credentials.mjs";
import { TexmlApplications, } from "./resources/texml-applications.mjs";
import { TrafficPolicyProfiles, } from "./resources/traffic-policy-profiles.mjs";
import { UsageReports, } from "./resources/usage-reports.mjs";
import { UserAddresses, } from "./resources/user-addresses.mjs";
import { UserTags } from "./resources/user-tags.mjs";
import { VerifyProfiles, } from "./resources/verify-profiles.mjs";
import { VirtualCrossConnects, } from "./resources/virtual-cross-connects.mjs";
import { VirtualCrossConnectsCoverage, } from "./resources/virtual-cross-connects-coverage.mjs";
import { VoiceClones, } from "./resources/voice-clones.mjs";
import { VoiceDesigns, } from "./resources/voice-designs.mjs";
import { VoiceSDKCallReports, } from "./resources/voice-sdk-call-reports.mjs";
import { WebhookDeliveries, } from "./resources/webhook-deliveries.mjs";
import { Webhooks, } from "./resources/webhooks.mjs";
import { WellKnown, } from "./resources/well-known.mjs";
import { WhatsappMessageTemplates, } from "./resources/whatsapp-message-templates.mjs";
import { WireguardInterfaces, } from "./resources/wireguard-interfaces.mjs";
import { WireguardPeers, } from "./resources/wireguard-peers.mjs";
import { WirelessBlocklistValues, } from "./resources/wireless-blocklist-values.mjs";
import { WirelessBlocklists, } from "./resources/wireless-blocklists.mjs";
import { Actions } from "./resources/actions/actions.mjs";
import { Addresses, } from "./resources/addresses/addresses.mjs";
import { AI, } from "./resources/ai/ai.mjs";
import { BundlePricing } from "./resources/bundle-pricing/bundle-pricing.mjs";
import { Calls, } from "./resources/calls/calls.mjs";
import { Conferences, } from "./resources/conferences/conferences.mjs";
import { CredentialConnections, } from "./resources/credential-connections/credential-connections.mjs";
import { Enterprises, } from "./resources/enterprises/enterprises.mjs";
import { ExternalConnections, } from "./resources/external-connections/external-connections.mjs";
import { Faxes, } from "./resources/faxes/faxes.mjs";
import { Legacy } from "./resources/legacy/legacy.mjs";
import { ManagedAccounts, } from "./resources/managed-accounts/managed-accounts.mjs";
import { Messages, } from "./resources/messages/messages.mjs";
import { Messaging10dlc } from "./resources/messaging-10dlc/messaging-10dlc.mjs";
import { MessagingHostedNumberOrders, } from "./resources/messaging-hosted-number-orders/messaging-hosted-number-orders.mjs";
import { MessagingProfiles, } from "./resources/messaging-profiles/messaging-profiles.mjs";
import { MessagingTollfree } from "./resources/messaging-tollfree/messaging-tollfree.mjs";
import { Messaging } from "./resources/messaging/messaging.mjs";
import { MobilePhoneNumbers, } from "./resources/mobile-phone-numbers/mobile-phone-numbers.mjs";
import { Networks, } from "./resources/networks/networks.mjs";
import { NumberReservations, } from "./resources/number-reservations/number-reservations.mjs";
import { OperatorConnect } from "./resources/operator-connect/operator-connect.mjs";
import { Organizations } from "./resources/organizations/organizations.mjs";
import { Payment, } from "./resources/payment/payment.mjs";
import { PhoneNumberBlocks } from "./resources/phone-number-blocks/phone-number-blocks.mjs";
import { PhoneNumbers, } from "./resources/phone-numbers/phone-numbers.mjs";
import { PortingOrders, } from "./resources/porting-orders/porting-orders.mjs";
import { Porting } from "./resources/porting/porting.mjs";
import { Portouts, } from "./resources/portouts/portouts.mjs";
import { Queues, } from "./resources/queues/queues.mjs";
import { Recordings, } from "./resources/recordings/recordings.mjs";
import { Reports, } from "./resources/reports/reports.mjs";
import { Reputation } from "./resources/reputation/reputation.mjs";
import { Rooms, } from "./resources/rooms/rooms.mjs";
import { SessionAnalysis, } from "./resources/session-analysis/session-analysis.mjs";
import { SimCardGroups, } from "./resources/sim-card-groups/sim-card-groups.mjs";
import { SimCards, } from "./resources/sim-cards/sim-cards.mjs";
import { SpeechToText, } from "./resources/speech-to-text/speech-to-text.mjs";
import { Storage } from "./resources/storage/storage.mjs";
import { TermsOfService } from "./resources/terms-of-service/terms-of-service.mjs";
import { Texml, } from "./resources/texml/texml.mjs";
import { TextToSpeech, } from "./resources/text-to-speech/text-to-speech.mjs";
import { UacConnections, } from "./resources/uac-connections/uac-connections.mjs";
import { Verifications, } from "./resources/verifications/verifications.mjs";
import { VerifiedNumbers, } from "./resources/verified-numbers/verified-numbers.mjs";
import { Whatsapp } from "./resources/whatsapp/whatsapp.mjs";
import { Wireless, } from "./resources/wireless/wireless.mjs";
import { X402 } from "./resources/x402/x402.mjs";
import { buildHeaders } from "./internal/headers.mjs";
import { toBase64 } from "./internal/utils/base64.mjs";
import { readEnv } from "./internal/utils/env.mjs";
import { formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
import { isEmptyObj } from "./internal/utils/values.mjs";
/**
* API Client for interfacing with the Telnyx API.
*/
export class Telnyx {
/**
* API Client for interfacing with the Telnyx API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['TELNYX_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.publicKey=process.env['TELNYX_PUBLIC_KEY'] ?? null]
* @param {string | null | undefined} [opts.clientID=process.env['TELNYX_CLIENT_ID'] ?? null]
* @param {string | null | undefined} [opts.clientSecret=process.env['TELNYX_CLIENT_SECRET'] ?? null]
* @param {string} [opts.baseURL=process.env['TELNYX_BASE_URL'] ?? https://api.telnyx.com/v2] - Override the default base URL for the API.
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {BuiltinRecord<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({ baseURL = readEnv('TELNYX_BASE_URL'), apiKey = readEnv('TELNYX_API_KEY') ?? null, publicKey = readEnv('TELNYX_PUBLIC_KEY') ?? null, clientID = readEnv('TELNYX_CLIENT_ID') ?? null, clientSecret = readEnv('TELNYX_CLIENT_SECRET') ?? null, ...opts } = {}) {
_Telnyx_instances.add(this);
_Telnyx_encoder.set(this, void 0);
this.legacy = new API.Legacy(this);
this.oauth = new API.OAuth(this);
this.oauthClients = new API.OAuthClients(this);
this.oauthGrants = new API.OAuthGrants(this);
this.webhooks = new API.Webhooks(this);
/**
* IP Address Operations
*/
this.accessIPAddress = new API.AccessIPAddress(this);
/**
* IP Range Operations
*/
this.accessIPRanges = new API.AccessIPRanges(this);
this.actions = new API.Actions(this);
/**
* Operations to work with Address records. Address records are emergency-validated addresses meant to be associated with phone numbers. They are validated for emergency usage purposes at creation time, although you may validate them separately with a custom workflow using the ValidateAddress operation separately. Address records are not usable for physical orders, such as for Telnyx SIM cards, please use UserAddress for that. It is not possible to entirely skip emergency service validation for Address records; if an emergency provider for a phone number rejects the address then it cannot be used on a phone number. To prevent records from getting out of sync, Address records are immutable and cannot be altered once created. If you realize you need to alter an address, a new record must be created with the differing address.
*/
this.addresses = new API.Addresses(this);
this.advancedOrders = new API.AdvancedOrders(this);
/**
* Generate text with LLMs
*/
this.ai = new API.AI(this);
/**
* Audit log operations.
*/
this.auditEvents = new API.AuditEvents(this);
this.authenticationProviders = new API.AuthenticationProviders(this);
/**
* Number search
*/
this.availablePhoneNumberBlocks = new API.AvailablePhoneNumberBlocks(this);
/**
* Number search
*/
this.availablePhoneNumbers = new API.AvailablePhoneNumbers(this);
/**
* Billing operations
*/
this.balance = new API.Balance(this);
/**
* Billing groups operations
*/
this.billingGroups = new API.BillingGroups(this);
/**
* View SIM card actions, their progress and timestamps using the SIM Card Actions API
*/
this.bulkSimCardActions = new API.BulkSimCardActions(this);
this.bundlePricing = new API.BundlePricing(this);
/**
* Call Control applications operations
*/
this.callControlApplications = new API.CallControlApplications(this);
/**
* Call Control debugging
*/
this.callEvents = new API.CallEvents(this);
this.calls = new API.Calls(this);
/**
* Voice Channels
*/
this.channelZones = new API.ChannelZones(this);
this.chargesBreakdown = new API.ChargesBreakdown(this);
this.chargesSummary = new API.ChargesSummary(this);
/**
* Number orders
*/
this.comments = new API.Comments(this);
/**
* Conference command operations
*/
this.conferences = new API.Conferences(this);
this.connections = new API.Connections(this);
/**
* Country Coverage
*/
this.countryCoverage = new API.CountryCoverageResource(this);
/**
* Credential connection operations
*/
this.credentialConnections = new API.CredentialConnections(this);
/**
* Call Recordings operations.
*/
this.customStorageCredentials = new API.CustomStorageCredentials(this);
/**
* Customer Service Record operations
*/
this.customerServiceRecords = new API.CustomerServiceRecords(this);
/**
* Detail Records operations
*/
this.detailRecords = new API.DetailRecords(this);
/**
* Dialogflow Connection Operations.
*/
this.dialogflowConnections = new API.DialogflowConnections(this);
/**
* Documents
*/
this.documentLinks = new API.DocumentLinks(this);
/**
* Documents
*/
this.documents = new API.Documents(this);
/**
* Dynamic emergency address operations
*/
this.dynamicEmergencyAddresses = new API.DynamicEmergencyAddresses(this);
/**
* Dynamic Emergency Endpoints
*/
this.dynamicEmergencyEndpoints = new API.DynamicEmergencyEndpoints(this);
/**
* External Connections operations
*/
this.externalConnections = new API.ExternalConnections(this);
/**
* Fax Applications operations
*/
this.faxApplications = new API.FaxApplications(this);
/**
* Programmable fax command operations
*/
this.faxes = new API.Faxes(this);
/**
* FQDN connection operations
*/
this.fqdnConnections = new API.FqdnConnections(this);
/**
* FQDN operations
*/
this.fqdns = new API.Fqdns(this);
/**
* Global IPs
*/
this.globalIPAllowedPorts = new API.GlobalIPAllowedPorts(this);
/**
* Global IPs
*/
this.globalIPAssignmentHealth = new API.GlobalIPAssignmentHealth(this);
/**
* Global IPs
*/
this.globalIPAssignments = new API.GlobalIPAssignments(this);
/**
* Global IPs
*/
this.globalIPAssignmentsUsage = new API.GlobalIPAssignmentsUsage(this);
/**
* Global IPs
*/
this.globalIPHealthCheckTypes = new API.GlobalIPHealthCheckTypes(this);
/**
* Global IPs
*/
this.globalIPHealthChecks = new API.GlobalIPHealthChecks(this);
/**
* Global IPs
*/
this.globalIPLatency = new API.GlobalIPLatency(this);
/**
* Global IPs
*/
this.globalIPProtocols = new API.GlobalIPProtocols(this);
/**
* Global IPs
*/
this.globalIPUsage = new API.GlobalIPUsage(this);
/**
* Global IPs
*/
this.globalIPs = new API.GlobalIPs(this);
/**
* Voice Channels
*/
this.inboundChannels = new API.InboundChannels(this);
/**
* Store and retrieve integration secrets
*/
this.integrationSecrets = new API.IntegrationSecrets(this);
/**
* Inventory Level
*/
this.inventoryCoverage = new API.InventoryCoverage(this);
this.invoices = new API.Invoices(this);
/**
* IP connection operations
*/
this.ipConnections = new API.IPConnections(this);
/**
* IP operations
*/
this.ips = new API.IPs(this);
/**
* Ledger billing reports
*/
this.ledgerBillingGroupReports = new API.LedgerBillingGroupReports(this);
/**
* Voice Channels
*/
this.list = new API.List(this);
/**
* Managed Accounts operations
*/
this.managedAccounts = new API.ManagedAccounts(this);
/**
* Media Storage operations
*/
this.media = new API.Media(this);
this.messages = new API.Messages(this);
this.messaging = new API.Messaging(this);
/**
* Manage your messaging hosted numbers
*/
this.messagingHostedNumberOrders = new API.MessagingHostedNumberOrders(this);
this.messagingHostedNumbers = new API.MessagingHostedNumbers(this);
/**
* Configure your phone numbers
*/
this.messagingNumbersBulkUpdates = new API.MessagingNumbersBulkUpdates(this);
/**
* Opt-Out Management
*/
this.messagingOptouts = new API.MessagingOptouts(this);
this.messagingProfiles = new API.MessagingProfiles(this);
this.messagingTollfree = new API.MessagingTollfree(this);
/**
* Messaging URL Domains
*/
this.messagingURLDomains = new API.MessagingURLDomains(this);
/**
* Mobile network operators operations
*/
this.mobileNetworkOperators = new API.MobileNetworkOperators(this);
/**
* Mobile push credential management
*/
this.mobilePushCredentials = new API.MobilePushCredentials(this);
this.networkCoverage = new API.NetworkCoverage(this);
/**
* Network operations
*/
this.networks = new API.Networks(this);
/**
* Notification settings operations
*/
this.notificationChannels = new API.NotificationChannels(this);
/**
* Notification settings operations
*/
this.notificationEventConditions = new API.NotificationEventConditions(this);
/**
* Notification settings operations
*/
this.notificationEvents = new API.NotificationEvents(this);
/**
* Notification settings operations
*/
this.notificationProfiles = new API.NotificationProfiles(this);
/**
* Notification settings operations
*/
this.notificationSettings = new API.NotificationSettings(this);
this.numberBlockOrders = new API.NumberBlockOrders(this);
/**
* Look up phone number data
*/
this.numberLookup = new API.NumberLookup(this);
this.numberOrderPhoneNumbers = new API.NumberOrderPhoneNumbers(this);
/**
* Number orders
*/
this.numberOrders = new API.NumberOrders(this);
/**
* Number reservations
*/
this.numberReservations = new API.NumberReservations(this);
this.numbersFeatures = new API.NumbersFeatures(this);
this.operatorConnect = new API.OperatorConnect(this);
/**
* OTA updates operations
*/
this.otaUpdates = new API.OtaUpdates(this);
/**
* Outbound voice profiles operations
*/
this.outboundVoiceProfiles = new API.OutboundVoiceProfiles(this);
/**
* Operations for managing stored payment transactions.
*/
this.payment = new API.Payment(this);
this.phoneNumberBlocks = new API.PhoneNumberBlocks(this);
/**
* Configure your phone numbers
*/
this.phoneNumbers = new API.PhoneNumbers(this);
/**
* Regulatory Requirements
*/
this.phoneNumbersRegulatoryRequirements = new API.PhoneNumbersRegulatoryRequirements(this);
/**
* Determining portability of phone numbers
*/
this.portabilityChecks = new API.PortabilityChecks(this);
/**
* Endpoints related to porting orders management.
*/
this.porting = new API.Porting(this);
/**
* Endpoints related to porting orders management.
*/
this.portingOrders = new API.PortingOrders(this);
/**
* Endpoints related to porting orders management.
*/
this.portingPhoneNumbers = new API.PortingPhoneNumbers(this);
/**
* Number portout operations
*/
this.portouts = new API.Portouts(this);
/**
* Private Wireless Gateways operations
*/
this.privateWirelessGateways = new API.PrivateWirelessGateways(this);
/**
* Public Internet Gateway operations
*/
this.publicInternetGateways = new API.PublicInternetGateways(this);
/**
* Queue commands operations
*/
this.queues = new API.Queues(this);
this.rcsAgents = new API.RcsAgents(this);
/**
* Call Recordings operations.
*/
this.recordingTranscriptions = new API.RecordingTranscriptions(this);
/**
* Call Recordings operations.
*/
this.recordings = new API.Recordings(this);
/**
* Regions
*/
this.regions = new API.Regions(this);
/**
* Regulatory Requirements
*/
this.regulatoryRequirements = new API.RegulatoryRequirements(this);
this.reports = new API.Reports(this);
/**
* Discover available speech-to-text providers, models, and supported languages.
*/
this.speechToText = new API.SpeechToText(this);
/**
* Requirement Groups
*/
this.requirementGroups = new API.RequirementGroups(this);
/**
* Types of requirements for international numbers and porting orders
*/
this.requirementTypes = new API.RequirementTypes(this);
/**
* Requirements for international numbers and porting orders
*/
this.requirements = new API.Requirements(this);
/**
* Rooms Compositions operations.
*/
this.roomCompositions = new API.RoomCompositions(this);
/**
* Rooms Participants operations.
*/
this.roomParticipants = new API.RoomParticipants(this);
/**
* Rooms Recordings operations.
*/
this.roomRecordings = new API.RoomRecordings(this);
/**
* Rooms operations.
*/
this.rooms = new API.Rooms(this);
/**
* Observability into Telnyx platform stability and performance.
*/
this.seti = new API.Seti(this);
/**
* Short codes
*/
this.shortCodes = new API.ShortCodes(this);
/**
* SIM Cards operations
*/
this.simCardDataUsageNotifications = new API.SimCardDataUsageNotifications(this);
/**
* SIM Card Groups operations
*/
this.simCardGroups = new API.SimCardGroups(this);
/**
* SIM Card Orders operations
*/
this.simCardOrderPreview = new API.SimCardOrderPreview(this);
/**
* SIM Card Orders operations
*/
this.simCardOrders = new API.SimCardOrders(this);
/**
* SIM Cards operations
*/
this.simCards = new API.SimCards(this);
/**
* SIPREC connectors configuration.
*/
this.siprecConnectors = new API.SiprecConnectors(this);
/**
* Migrate data from an external provider into Telnyx Cloud Storage
*/
this.storage = new API.Storage(this);
this.subNumberOrders = new API.SubNumberOrders(this);
/**
* Number orders
*/
this.subNumberOrdersReport = new API.SubNumberOrdersReportResource(this);
this.telephonyCredentials = new API.TelephonyCredentials(this);
/**
* TeXML REST Commands
*/
this.texml = new API.Texml(this);
/**
* TeXML Applications operations
*/
this.texmlApplications = new API.TexmlApplications(this);
/**
* Text to speech streaming command operations
*/
this.textToSpeech = new API.TextToSpeech(this);
/**
* Usage data reporting across Telnyx products
*/
this.usageReports = new API.UsageReports(this);
/**
* Operations for working with UserAddress records. UserAddress records are stored addresses that users can use for non-emergency-calling purposes, such as for shipping addresses for orders of wireless SIMs (or other physical items). They cannot be used for emergency calling and are distinct from Address records, which are used on phone numbers.
*/
this.userAddresses = new API.UserAddresses(this);
/**
* User-defined tags for Telnyx resources
*/
this.userTags = new API.UserTags(this);
/**
* Two factor authentication API
*/
this.verifications = new API.Verifications(this);
/**
* Verified Numbers operations
*/
this.verifiedNumbers = new API.VerifiedNumbers(this);
/**
* Two factor authentication API
*/
this.verifyProfiles = new API.VerifyProfiles(this);
/**
* Virtual Cross Connect operations
*/
this.virtualCrossConnects = new API.VirtualCrossConnects(this);
/**
* Virtual Cross Connect operations
*/
this.virtualCrossConnectsCoverage = new API.VirtualCrossConnectsCoverage(this);
/**
* Webhooks operations
*/
this.webhookDeliveries = new API.WebhookDeliveries(this);
/**
* WireGuard Interface operations
*/
this.wireguardInterfaces = new API.WireguardInterfaces(this);
/**
* WireGuard Interface operations
*/
this.wireguardPeers = new API.WireguardPeers(this);
/**
* Regions for wireless services
*/
this.wireless = new API.Wireless(this);
/**
* Wireless Blocklists operations
*/
this.wirelessBlocklistValues = new API.WirelessBlocklistValues(this);
/**
* Wireless Blocklists operations
*/
this.wirelessBlocklists = new API.WirelessBlocklists(this);
this.wellKnown = new API.WellKnown(this);
/**
* Inexplicit number orders for bulk purchasing without specifying exact numbers
*/
this.inexplicitNumberOrders = new API.InexplicitNumberOrders(this);
/**
* Mobile phone number operations
*/
this.mobilePhoneNumbers = new API.MobilePhoneNumbers(this);
/**
* Mobile voice connection operations
*/
this.mobileVoiceConnections = new API.MobileVoiceConnections(this);
this.messaging10dlc = new API.Messaging10dlc(this);
this.organizations = new API.Organizations(this);
this.alphanumericSenderIDs = new API.AlphanumericSenderIDs(this);
this.messagingProfileMetrics = new API.MessagingProfileMetrics(this);
/**
* Analyze voice AI sessions, costs, and event hierarchies across Telnyx products.
*/
this.sessionAnalysis = new API.SessionAnalysis(this);
this.whatsapp = new API.Whatsapp(this);
/**
* Manage Whatsapp message templates
*/
this.whatsappMessageTemplates = new API.WhatsappMessageTemplates(this);
this.x402 = new API.X402(this);
/**
* Capture and manage voice identities as clones for use in text-to-speech synthesis.
*/
this.voiceClones = new API.VoiceClones(this);
/**
* Create and manage AI-generated voice designs using natural language prompts.
*/
this.voiceDesigns = new API.VoiceDesigns(this);
/**
* Traffic Policy Profiles operations
*/
this.trafficPolicyProfiles = new API.TrafficPolicyProfiles(this);
/**
* Enterprise management for Branded Calling and Number Reputation services
*/
this.enterprises = new API.Enterprises(this);
this.reputation = new API.Reputation(this);
this.termsOfService = new API.TermsOfService(this);
/**
* Manage pronunciation dictionaries for text-to-speech synthesis. Dictionaries contain alias items (text replacement) and phoneme items (IPA pronunciation notation) that control how specific words are spoken.
*/
this.pronunciationDicts = new API.PronunciationDicts(this);
/**
* UAC connection operations
*/
this.uacConnections = new API.UacConnections(this);
/**
* Retrieve raw Voice SDK call report stats payloads for WebRTC call troubleshooting.
*/
this.voiceSDKCallReports = new API.VoiceSDKCallReports(this);
const options = {
apiKey,
publicKey,
clientID,
clientSecret,
...opts,
baseURL: baseURL || `https://api.telnyx.com/v2`,
};
this.baseURL = options.baseURL;
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
this.logger = options.logger ?? console;
const defaultLogLevel = 'warn';
// Set default logLevel early so that we can log a warning in parseLogLevel.
this.logLevel = defaultLogLevel;
this.logLevel =
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
parseLogLevel(readEnv('TELNYX_LOG'), "process.env['TELNYX_LOG']", this) ??
defaultLogLevel;
this.fetchOptions = options.fetchOptions;
this.maxRetries = options.maxRetries ?? 2;
this.fetch = options.fetch ?? Shims.getDefaultFetch();
__classPrivateFieldSet(this, _Telnyx_encoder, Opts.FallbackEncoder, "f");
const customHeadersEnv = readEnv('TELNYX_CUSTOM_HEADERS');
if (customHeadersEnv) {
const parsed = {};
for (const line of customHeadersEnv.split('\n')) {
const colon = line.indexOf(':');
if (colon >= 0) {
parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
}
}
options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
}
this._options = options;
this.apiKey = apiKey;
this.publicKey = publicKey;
this.clientID = clientID;
this.clientSecret = clientSecret;
}
/**
* Create a new client instance re-using the same options given to the current client with optional overriding.
*/
withOptions(options) {
const client = new this.constructor({
...this._options,
baseURL: this.baseURL,
maxRetries: this.maxRetries,
timeout: this.timeout,
logger: this.logger,
logLevel: this.logLevel,
fetch: this.fetch,
fetchOptions: this.fetchOptions,
apiKey: this.apiKey,
publicKey: this.publicKey,
clientID: this.clientID,
clientSecret: this.clientSecret,
...options,
});
client.oauthClientAuthState = this.oauthClientAuthState;
return client;
}
defaultQuery() {
return this._options.defaultQuery;
}
validateHeaders({ values, nulls }) {
return;
}
async authHeaders(opts) {
return buildHeaders([await this.bearerAuth(opts), await this.oauthClientAuth(opts)]);
}
async bearerAuth(opts) {
if (this.apiKey == null) {
return undefined;
}
return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
}
async oauthClientAuth(opts) {
if (!this.clientID || !this.clientSecret) {
return undefined;
}
// Invalidate the cache if the token is expired
if (this.oauthClientAuthState && +(await this.oauthClientAuthState.promise).expires_at < Date.now()) {
this.oauthClientAuthState = undefined;
}
// Invalidate the cache if the relevant state has been changed
if (this.oauthClientAuthState &&
this.oauthClientAuthState.clientID !== this.clientID &&
this.oauthClientAuthState.clientSecret !== this.clientSecret) {
this.oauthClientAuthState = undefined;
}
if (!this.oauthClientAuthState) {
this.oauthClientAuthState = {
promise: this.fetch(this.buildURL('https://api.telnyx.com/v2/oauth/token', {}), {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${toBase64(`${this.clientID}:${this.clientSecret}`)}`,
},
body: 'grant_type=client_credentials',
}).then(async (res) => {
if (!res.ok) {
const errText = await res.text().catch(() => '');
const errJSON = errText ? safeJSON(errText) : undefined;
const errMessage = errJSON ? undefined : errText;
throw this.makeStatusError(res.status, errJSON, errMessage, res.headers);
}
const json = (await res.json());
const now = new Date();
now.setSeconds(now.getSeconds() + json.expires_in);
return { ...json, expires_at: now };
}),
clientID: this.clientID,
clientSecret: this.clientSecret,
};
}
const token = await this.oauthClientAuthState.promise;
return buildHeaders([{ Authorization: `Bearer ${token.access_token}` }]);
}
stringifyQuery(query) {
return stringifyQuery(query);
}
getUserAgent() {
return `${this.constructor.name}/JS ${VERSION}`;
}
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
makeStatusError(status, error, message, headers) {
return Errors.APIError.generate(status, error, message, headers);
}
buildURL(path, query, defaultBaseURL) {
const baseURL = (!__classPrivateFieldGet(this, _Telnyx_instances, "m", _Telnyx_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
const pathQuery = Object.fromEntries(url.searchParams);
if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
query = { ...pathQuery, ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
async prepareOptions(options) { }
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) { }
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => {
return { method, path, ...opts };
}));
}
request(options, remainingRetries = null) {
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
}
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = maxRetries;
}
await this.prepareOptions(options);
const { req, url, timeout } = await this.buildRequest(options, {
retryCount: maxRetries - retriesRemaining,
});
await this.prepareRequest(req, { url, options });
/** Not an API request ID, just for correlating local log entries. */
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
const startTime = Date.now();
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
retryOfRequestLogID,
method: options.method,
url,
options,
headers: req.headers,
}));
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
const headersTime = Date.now();
if (response instanceof globalThis.Error) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
// detect native connection timeout errors
// deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
// others do not provide enough information to distinguish timeouts from other connection errors
const isTimeout = isAbortError(response) ||
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
if (retriesRemaining) {
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
}
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
if (isTimeout) {
throw new Errors.APIConnectionTimeoutError();
}
throw new Errors.APIConnectionError({ cause: response });
}
const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
if (!response.ok) {
const shouldRetry = await this.shouldRetry(response);
if (retriesRemaining && shouldRetry) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
// We don't need the body of this response.
await Shims.CancelReadableStream(response.body);
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
}
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
const errText = await response.text().catch((err) => castToError(err).message);
const errJSON = safeJSON(errText);
const errMessage = errJSON ? undefined : errText;
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
message: errMessage,
durationMs: Date.now() - startTime,
}));
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
throw err;
}
loggerFor(this).info(responseInfo);
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, opts && 'then' in opts ?
opts.then((opts) => ({ method: 'get', path, ...opts }))
: { method: 'get', path, ...opts });
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null, undefined);
return new Pagination.PagePromise(this, request, Page);
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, method, ...options } = init || {};
const abort = this._makeAbort(controller);
if (signal)
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, ms);
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
const fetchOptions = {
signal: controller.signal,
...(isReadableBody ? { duplex: 'half' } : {}),
method: 'GET',
...options,
};
if (method) {
// Custom methods like 'patch' need to be uppercased
// See https://github.com/nodejs/undici/issues/2294
fetchOptions.method = method.toUpperCase();
}