Auto-commit 2026-04-29 16:31

This commit is contained in:
2026-04-29 16:31:27 -04:00
parent e8687bb6b2
commit 0495ee5bd2
19691 changed files with 3272886 additions and 138 deletions

View File

@@ -0,0 +1,7 @@
export default abstract class AuthStrategy {
private authType;
protected constructor(authType: string);
getAuthType(): string;
abstract getAuthString(): Promise<string>;
abstract requiresAuthentication(): boolean;
}

11
node_modules/twilio/lib/auth_strategy/AuthStrategy.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class AuthStrategy {
constructor(authType) {
this.authType = authType;
}
getAuthType() {
return this.authType;
}
}
exports.default = AuthStrategy;

View File

@@ -0,0 +1,8 @@
import AuthStrategy from "./AuthStrategy";
export default class BasicAuthStrategy extends AuthStrategy {
private username;
private password;
constructor(username: string, password: string);
getAuthString(): Promise<string>;
requiresAuthentication(): boolean;
}

View File

@@ -0,0 +1,21 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const AuthStrategy_1 = __importDefault(require("./AuthStrategy"));
class BasicAuthStrategy extends AuthStrategy_1.default {
constructor(username, password) {
super("basic");
this.username = username;
this.password = password;
}
getAuthString() {
const auth = Buffer.from(this.username + ":" + this.password).toString("base64");
return Promise.resolve(`Basic ${auth}`);
}
requiresAuthentication() {
return true;
}
}
exports.default = BasicAuthStrategy;

View File

@@ -0,0 +1,6 @@
import AuthStrategy from "./AuthStrategy";
export default class NoAuthStrategy extends AuthStrategy {
constructor();
getAuthString(): Promise<string>;
requiresAuthentication(): boolean;
}

View File

@@ -0,0 +1,18 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const AuthStrategy_1 = __importDefault(require("./AuthStrategy"));
class NoAuthStrategy extends AuthStrategy_1.default {
constructor() {
super("noauth");
}
getAuthString() {
return Promise.resolve("");
}
requiresAuthentication() {
return false;
}
}
exports.default = NoAuthStrategy;

View File

@@ -0,0 +1,16 @@
import AuthStrategy from "./AuthStrategy";
import TokenManager from "../http/bearer_token/TokenManager";
export default class TokenAuthStrategy extends AuthStrategy {
private token;
private tokenManager;
constructor(tokenManager: TokenManager);
getAuthString(): Promise<string>;
requiresAuthentication(): boolean;
fetchToken(): Promise<string>;
/**
* Function to check if the token is expired with a buffer of 30 seconds.
* @param token - The JWT token as a string.
* @returns Boolean indicating if the token is expired.
*/
isTokenExpired(token: string): boolean;
}

View File

@@ -0,0 +1,60 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const AuthStrategy_1 = __importDefault(require("./AuthStrategy"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
class TokenAuthStrategy extends AuthStrategy_1.default {
constructor(tokenManager) {
super("token");
this.token = "";
this.tokenManager = tokenManager;
}
async getAuthString() {
return this.fetchToken()
.then((token) => {
this.token = token;
return `Bearer ${this.token}`;
})
.catch((error) => {
throw new Error(`Failed to fetch access token: ${error.message}`);
});
}
requiresAuthentication() {
return true;
}
async fetchToken() {
if (this.token == null ||
this.token.length === 0 ||
this.isTokenExpired(this.token)) {
return this.tokenManager.fetchToken();
}
return Promise.resolve(this.token);
}
/**
* Function to check if the token is expired with a buffer of 30 seconds.
* @param token - The JWT token as a string.
* @returns Boolean indicating if the token is expired.
*/
isTokenExpired(token) {
try {
// Decode the token without verifying the signature, as we only want to read the expiration for this check
const decoded = jsonwebtoken_1.default.decode(token);
if (!decoded || !decoded.exp) {
// If the token doesn't have an expiration, consider it expired
return true;
}
const expiresAt = decoded.exp * 1000;
const bufferMilliseconds = 30 * 1000;
const bufferExpiresAt = expiresAt - bufferMilliseconds;
// Return true if the current time is after the expiration time with buffer
return Date.now() > bufferExpiresAt;
}
catch (error) {
// If there's an error decoding the token, consider it expired
return true;
}
}
}
exports.default = TokenAuthStrategy;

34
node_modules/twilio/lib/base/ApiResponse.d.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
/**
* API Response wrapper containing HTTP metadata
*
* This interface is returned by *WithHttpInfo methods and provides access to:
* - The response data (resource instance, page, or boolean)
* - HTTP status code
* - Response headers
*/
export interface ApiResponse<T> {
/**
* The response data
* - For create/fetch/update: Resource instance
* - For delete/remove: boolean indicating success
* - For page: Page object
*/
body: T;
/**
* HTTP status code from the response
* - 200: Success (fetch, update)
* - 201: Created (create)
* - 204: No Content (delete)
* - 4xx/5xx: Error responses
*/
statusCode: number;
/**
* Response headers as key-value pairs
* Common headers include:
* - Content-Type
* - X-RateLimit-Remaining
* - X-RateLimit-Limit
* - X-Request-ID
*/
headers: Record<string, string>;
}

2
node_modules/twilio/lib/base/ApiResponse.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

121
node_modules/twilio/lib/base/BaseTwilio.d.ts generated vendored Normal file
View File

@@ -0,0 +1,121 @@
import RequestClient from "./RequestClient";
import { ValidationClientOptions } from "./ValidationClient";
import { HttpMethod } from "../interfaces";
import { Headers } from "../http/request";
import AuthStrategy from "../auth_strategy/AuthStrategy";
import CredentialProvider from "../credential_provider/CredentialProvider";
declare namespace Twilio {
interface ClientOpts {
httpClient?: RequestClient;
accountSid?: string;
env?: NodeJS.ProcessEnv;
edge?: string;
region?: string;
lazyLoading?: boolean;
logLevel?: string;
userAgentExtensions?: string[];
autoRetry?: boolean;
maxRetryDelay?: number;
maxRetries?: number;
validationClient?: ValidationClientOptions;
/**
https.Agent options
*/
timeout?: number;
keepAlive?: boolean;
keepAliveMsecs?: number;
maxSockets?: number;
maxTotalSockets?: number;
maxFreeSockets?: number;
scheduling?: "fifo" | "lifo" | undefined;
ca?: string | Buffer;
}
interface RequestOpts {
method?: HttpMethod;
uri?: string;
username?: string;
password?: string;
authStrategy?: AuthStrategy;
headers?: Headers;
params?: object;
data?: object;
timeout?: number;
allowRedirects?: boolean;
logLevel?: string;
}
/**
* Parent class for Twilio Client that implements request & validation logic
*/
class Client {
username?: string;
password?: string;
accountSid: string;
credentialProvider?: CredentialProvider;
opts?: ClientOpts;
env?: NodeJS.ProcessEnv;
edge?: string;
region?: string;
logLevel?: string;
autoRetry?: boolean;
maxRetryDelay?: number;
maxRetries?: number;
validationClient?: ValidationClientOptions;
/**
https.Agent options
*/
timeout?: number;
keepAlive?: boolean;
keepAliveMsecs?: number;
maxSockets?: number;
maxTotalSockets?: number;
maxFreeSockets?: number;
scheduling?: "fifo" | "lifo" | undefined;
ca?: string | Buffer;
userAgentExtensions?: string[];
_httpClient?: RequestClient;
/**
* Create a BaseTwilio instance
*
* @param username -
* The username used for authentication. This is normally account sid, but if using key/secret auth will be
* the api key sid.
* @param password -
* The password used for authentication. This is normally auth token, but if using key/secret auth will be
* the secret.
* @param opts - The options argument
*
* @returns A new instance of BaseTwilio
*/
constructor(username?: string, password?: string, opts?: ClientOpts);
setOpts(opts?: ClientOpts): void;
setAccountSid(accountSid?: string): void;
setCredentialProvider(credentialProvider: CredentialProvider): void;
invalidateBasicAuth(): void;
invalidateOAuth(): void;
get httpClient(): RequestClient;
/**
* Makes a request to the Twilio API using the configured http client.
* Authentication information is automatically added if none is provided.
*
* @param opts - The options argument
*/
request(opts: RequestOpts): Promise<any>;
/**
* Adds a region and/or edge to a given hostname
*
* @param hostname - A URI hostname (e.g. api.twilio.com)
* @param targetEdge - The targeted edge location (e.g. sydney)
* @param targetRegion - The targeted region location (e.g. au1)
*/
getHostname(hostname: string, targetEdge: string | undefined, targetRegion: string | undefined): string;
/**
* Test if your environment is impacted by a TLS or certificate
* change is by sending an HTTP request to the test endpoint
*
* @throws RestException if the request fails
*
*/
validateSslCert(): Promise<any>;
}
}
export = Twilio;

232
node_modules/twilio/lib/base/BaseTwilio.js generated vendored Normal file
View File

@@ -0,0 +1,232 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const RequestClient_1 = __importDefault(require("./RequestClient")); /* jshint ignore:line */
const os = require("os"); /* jshint ignore:line */
const url = require("url"); /* jshint ignore:line */
const moduleInfo = require("../../package.json"); /* jshint ignore:line */
const util = require("util"); /* jshint ignore:line */
const RestException = require("../base/RestException"); /* jshint ignore:line */
var Twilio;
(function (Twilio) {
/* jshint ignore:start */
/**
* Parent class for Twilio Client that implements request & validation logic
*/
/* jshint ignore:end */
class Client {
/* jshint ignore:start */
/**
* Create a BaseTwilio instance
*
* @param username -
* The username used for authentication. This is normally account sid, but if using key/secret auth will be
* the api key sid.
* @param password -
* The password used for authentication. This is normally auth token, but if using key/secret auth will be
* the secret.
* @param opts - The options argument
*
* @returns A new instance of BaseTwilio
*/
/* jshint ignore:end */
constructor(username, password, opts) {
this.setOpts(opts);
this.username =
username ??
this.env?.TWILIO_ACCOUNT_SID ??
process.env.TWILIO_ACCOUNT_SID;
this.password =
password ??
this.env?.TWILIO_AUTH_TOKEN ??
process.env.TWILIO_AUTH_TOKEN;
this.accountSid = "";
this.setAccountSid(this.opts?.accountSid || this.username);
this.invalidateOAuth();
}
setOpts(opts) {
this.opts = opts || {};
this.env = this.opts.env || {};
this.edge =
this.opts.edge ?? this.env.TWILIO_EDGE ?? process.env.TWILIO_EDGE;
this.region =
this.opts.region ?? this.env.TWILIO_REGION ?? process.env.TWILIO_REGION;
this.logLevel =
this.opts.logLevel ??
this.env.TWILIO_LOG_LEVEL ??
process.env.TWILIO_LOG_LEVEL;
this.timeout = this.opts.timeout;
this.keepAlive = this.opts.keepAlive;
this.keepAliveMsecs = this.opts.keepAliveMsecs;
this.maxSockets = this.opts.maxSockets;
this.maxTotalSockets = this.opts.maxTotalSockets;
this.maxFreeSockets = this.opts.maxFreeSockets;
this.scheduling = this.opts.scheduling;
this.ca = this.opts.ca;
this.autoRetry = this.opts.autoRetry || false;
this.maxRetryDelay = this.opts.maxRetryDelay;
this.maxRetries = this.opts.maxRetries;
this.validationClient = this.opts.validationClient;
this.userAgentExtensions = this.opts.userAgentExtensions || [];
this._httpClient = this.opts.httpClient;
if (this.opts.lazyLoading === false) {
this._httpClient = this.httpClient;
}
}
setAccountSid(accountSid) {
this.accountSid = accountSid || "";
if (this.accountSid && !this.accountSid?.startsWith("AC")) {
const apiKeyMsg = this.accountSid?.startsWith("SK")
? ". The given SID indicates an API Key which requires the accountSid to be passed as an additional option"
: "";
throw new Error("accountSid must start with AC" + apiKeyMsg);
}
}
setCredentialProvider(credentialProvider) {
this.credentialProvider = credentialProvider;
this.accountSid = "";
this.invalidateBasicAuth();
}
invalidateBasicAuth() {
this.username = undefined;
this.password = undefined;
}
invalidateOAuth() {
this.credentialProvider = undefined;
}
get httpClient() {
if (!this._httpClient) {
this._httpClient = new RequestClient_1.default({
timeout: this.timeout,
keepAlive: this.keepAlive,
keepAliveMsecs: this.keepAliveMsecs,
maxSockets: this.maxSockets,
maxTotalSockets: this.maxTotalSockets,
maxFreeSockets: this.maxFreeSockets,
scheduling: this.scheduling,
ca: this.ca,
autoRetry: this.autoRetry,
maxRetryDelay: this.maxRetryDelay,
maxRetries: this.maxRetries,
validationClient: this.validationClient,
});
}
return this._httpClient;
}
/* jshint ignore:start */
/**
* Makes a request to the Twilio API using the configured http client.
* Authentication information is automatically added if none is provided.
*
* @param opts - The options argument
*/
/* jshint ignore:end */
request(opts) {
opts = opts || {};
if (!opts.method) {
throw new Error("method is required");
}
if (!opts.uri) {
throw new Error("uri is required");
}
const username = opts.username || this.username;
const password = opts.password || this.password;
const authStrategy = opts.authStrategy || this.credentialProvider?.toAuthStrategy();
if (!authStrategy) {
if (!username) {
(() => {
throw new Error("username is required");
})();
}
if (!password) {
(() => {
throw new Error("password is required");
})();
}
}
const headers = opts.headers || {};
const pkgVersion = moduleInfo.version;
const osName = os.platform();
const osArch = os.arch();
const nodeVersion = process.version;
headers["User-Agent"] = util.format("twilio-node/%s (%s %s) node/%s", pkgVersion, osName, osArch, nodeVersion);
this.userAgentExtensions?.forEach((extension) => {
headers["User-Agent"] += ` ${extension}`;
});
headers["Accept-Charset"] = "utf-8";
if ((opts.method === "post" || opts.method === "put") &&
!headers["Content-Type"]) {
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
if (opts.method !== "delete" && !headers["Accept"]) {
headers["Accept"] = "application/json";
}
var uri = new url.URL(opts.uri);
uri.hostname = this.getHostname(uri.hostname, this.edge, this.region);
return this.httpClient?.request({
method: opts.method,
uri: uri.href,
username: username,
password: password,
authStrategy: authStrategy,
headers: headers,
params: opts.params,
data: opts.data,
timeout: opts.timeout,
allowRedirects: opts.allowRedirects,
// use the Twilio client's log-level if the httpClient's log-level is unspecified
logLevel: opts.logLevel || this.opts?.logLevel,
});
}
/* jshint ignore:start */
/**
* Adds a region and/or edge to a given hostname
*
* @param hostname - A URI hostname (e.g. api.twilio.com)
* @param targetEdge - The targeted edge location (e.g. sydney)
* @param targetRegion - The targeted region location (e.g. au1)
*/
/* jshint ignore:end */
getHostname(hostname, targetEdge, targetRegion) {
const defaultRegion = "us1";
const domain = hostname.split(".").slice(-2).join(".");
const prefix = hostname.split("." + domain)[0];
let [product, edge, region] = prefix.split(".");
if (edge && !region) {
region = edge;
edge = undefined;
}
region = targetRegion || region || (targetEdge && defaultRegion);
if (!region) {
return hostname;
}
edge = targetEdge || edge;
return [product, edge, region, domain].filter((part) => part).join(".");
}
/* jshint ignore:start */
/**
* Test if your environment is impacted by a TLS or certificate
* change is by sending an HTTP request to the test endpoint
*
* @throws RestException if the request fails
*
*/
/* jshint ignore:end */
validateSslCert() {
return this.httpClient
?.request({
method: "get",
uri: "https://tls-test.twilio.com:443",
})
.then((response) => {
if (response["statusCode"] < 200 || response["statusCode"] >= 300) {
throw new RestException(response);
}
return response;
});
}
}
Twilio.Client = Client;
})(Twilio || (Twilio = {}));
module.exports = Twilio;

29
node_modules/twilio/lib/base/Domain.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import { Client as BaseTwilio, RequestOpts } from "./BaseTwilio";
/**
* Base domain object
*/
export default class Domain {
twilio: BaseTwilio;
baseUrl: string;
/**
* Creates a Domain instance
*
* @param twilio - A Twilio Client
* @param baseUrl - Base url for this domain
*/
constructor(twilio: BaseTwilio, baseUrl: string);
/**
* Turn a uri into an absolute url
*
* @param uri - uri to transform
* @returns absolute url
*/
absoluteUrl(uri?: string): string;
/**
* Make request to this domain
*
* @param opts - request options
* @returns request promise
*/
request(opts: RequestOpts): Promise<any>;
}

53
node_modules/twilio/lib/base/Domain.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utility_1 = require("./utility");
/**
* Base domain object
*/
class Domain {
/**
* Creates a Domain instance
*
* @param twilio - A Twilio Client
* @param baseUrl - Base url for this domain
*/
constructor(twilio, baseUrl) {
this.twilio = twilio;
this.baseUrl = baseUrl;
}
/**
* Turn a uri into an absolute url
*
* @param uri - uri to transform
* @returns absolute url
*/
absoluteUrl(uri) {
var result = "";
if (typeof this.baseUrl === "string") {
const cleanBaseUrl = (0, utility_1.trim)(this.baseUrl, "/");
result += cleanBaseUrl;
result += "/";
}
if (typeof uri === "string") {
uri = (0, utility_1.trim)(uri, "/");
if (result === "") {
result += "/";
}
result += uri;
}
return result;
}
/**
* Make request to this domain
*
* @param opts - request options
* @returns request promise
*/
request(opts) {
return this.twilio.request({
...opts,
uri: this.absoluteUrl(opts.uri),
});
}
}
exports.default = Domain;

104
node_modules/twilio/lib/base/Page.d.ts generated vendored Normal file
View File

@@ -0,0 +1,104 @@
import Version from "./Version";
import Response from "../http/response";
export interface TwilioResponsePayload {
[key: string]: any;
first_page_uri: string;
next_page_uri: string;
page: number;
page_size: number;
previous_page_uri: string;
uri: string;
meta?: {
key?: string;
next_page_url?: string;
previous_page_url?: string;
};
}
interface Solution {
[name: string]: any;
}
export default class Page<TVersion extends Version, TPayload extends TwilioResponsePayload, TResource, TInstance> {
nextPageUrl?: string;
previousPageUrl?: string;
instances: TInstance[];
_version: TVersion;
_payload: TPayload;
_solution: Solution;
/**
*
* Base page object to maintain request state.
*
* @param version - A twilio version instance
* @param response - The http response
* @param solution - path solution
*/
constructor(version: TVersion, response: Response<string | TPayload>, solution: Solution);
/**
* Meta keys returned in a list request
*
* @constant META_KEYS
*/
static META_KEYS: string[];
/**
* Get the url of the previous page of records
*
* @returns url of the previous page, or undefined if the
* previous page URI/URL is not defined.
*/
getPreviousPageUrl(): string | undefined;
/**
* Get the url of the next page of records
*
* @returns url of the next page, or undefined if the
* next page URI/URL is not defined.
*/
getNextPageUrl(): string | undefined;
/**
* Build a new instance given a json payload
*
* @param payload - Payload response from the API
* @returns instance of a resource
*/
getInstance(payload: any): TInstance;
/**
* Load a list of records
*
* @param resources - json payload of records
* @returns list of resources
*/
loadInstances(resources: TResource[]): TInstance[];
/**
* Fetch the next page of records
*
* @returns promise that resolves to next page of results,
* or undefined if there isn't a nextPageUrl undefined.
*/
nextPage(): Promise<Page<TVersion, TPayload, TResource, TInstance>> | undefined;
/**
* Fetch the previous page of records
*
* @returns promise that resolves to previous page of
* results, or undefined if there isn't a previousPageUrl undefined.
*/
previousPage(): Promise<Page<TVersion, TPayload, TResource, TInstance>> | undefined;
/**
* Parse json response from API
*
* @param response - API response
*
* @throws Error If non 200 status code is returned
*
* @returns json parsed response
*/
processResponse(response: Response<string | TPayload>): TPayload;
/**
* Load a page of records
*
* @param {object} payload json payload
* @return {array} the page of records
*/
loadPage(payload: TPayload): TResource[];
forOwn(obj: object, iteratee: (val: any, key: string, object: object) => void): void;
toJSON(): object;
}
export {};

195
node_modules/twilio/lib/base/Page.js generated vendored Normal file
View File

@@ -0,0 +1,195 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RestException_1 = __importDefault(require("./RestException"));
class Page {
/**
*
* Base page object to maintain request state.
*
* @param version - A twilio version instance
* @param response - The http response
* @param solution - path solution
*/
constructor(version, response, solution) {
let payload = this.processResponse(response);
this._version = version;
this._payload = payload;
this._solution = solution;
this.nextPageUrl = this.getNextPageUrl();
this.previousPageUrl = this.getPreviousPageUrl();
this.instances = this.loadInstances(this.loadPage(payload));
}
/**
* Get the url of the previous page of records
*
* @returns url of the previous page, or undefined if the
* previous page URI/URL is not defined.
*/
getPreviousPageUrl() {
if (this._payload.meta &&
"previous_page_url" in this._payload.meta &&
this._payload.meta.previous_page_url) {
// jshint ignore:line
return this._payload.meta.previous_page_url; // jshint ignore:line
}
if ("previous_page_uri" in this._payload &&
this._payload.previous_page_uri) {
// jshint ignore:line
return this._version._domain.absoluteUrl(this._payload.previous_page_uri); // jshint ignore:line
}
return undefined;
}
/**
* Get the url of the next page of records
*
* @returns url of the next page, or undefined if the
* next page URI/URL is not defined.
*/
getNextPageUrl() {
if (this._payload.meta &&
"next_page_url" in this._payload.meta &&
this._payload.meta.next_page_url) {
// jshint ignore:line
return this._payload.meta.next_page_url; // jshint ignore:line
}
if ("next_page_uri" in this._payload && this._payload.next_page_uri) {
// jshint ignore:line
return this._version._domain.absoluteUrl(this._payload.next_page_uri); // jshint ignore:line
}
return undefined;
}
/**
* Build a new instance given a json payload
*
* @param payload - Payload response from the API
* @returns instance of a resource
*/
getInstance(payload) {
throw new Error("Page.get_instance() must be implemented in the derived class");
}
/**
* Load a list of records
*
* @param resources - json payload of records
* @returns list of resources
*/
loadInstances(resources) {
let instances = [];
resources.forEach((resource) => {
instances.push(this.getInstance(resource));
});
return instances;
}
/**
* Fetch the next page of records
*
* @returns promise that resolves to next page of results,
* or undefined if there isn't a nextPageUrl undefined.
*/
nextPage() {
if (!this.nextPageUrl) {
return undefined;
}
var reqPromise = this._version._domain.twilio.request({
method: "get",
uri: this.nextPageUrl,
});
var nextPagePromise = reqPromise.then(function (response) {
return new this.constructor(this._version, response, this._solution);
}.bind(this));
return nextPagePromise;
}
/**
* Fetch the previous page of records
*
* @returns promise that resolves to previous page of
* results, or undefined if there isn't a previousPageUrl undefined.
*/
previousPage() {
if (!this.previousPageUrl) {
return undefined;
}
var reqPromise = this._version._domain.twilio.request({
method: "get",
uri: this.previousPageUrl,
});
var prevPagePromise = reqPromise.then(function (response) {
return new this.constructor(this._version, response, this._solution);
}.bind(this));
return prevPagePromise;
}
/**
* Parse json response from API
*
* @param response - API response
*
* @throws Error If non 200 status code is returned
*
* @returns json parsed response
*/
processResponse(response) {
if (response.statusCode !== 200) {
throw new RestException_1.default(response);
}
if (typeof response.body === "string") {
return JSON.parse(response.body);
}
return response.body;
}
/**
* Load a page of records
*
* @param {object} payload json payload
* @return {array} the page of records
*/
loadPage(payload) {
if (payload.meta?.key) {
return payload[payload.meta.key];
}
const keys = Object.keys(payload).filter((key) => !Page.META_KEYS.includes(key));
if (keys.length === 1) {
return payload[keys[0]];
}
for (const key of keys)
if (Array.isArray(payload[key]))
return payload[key];
throw new Error("Page Records cannot be deserialized");
}
forOwn(obj, iteratee) {
obj = Object(obj);
for (const [key, val] of Object.entries(obj)) {
iteratee(val, key, obj);
}
}
toJSON() {
const clone = {};
this.forOwn(this, (value, key) => {
if (!key.startsWith("_") && typeof value !== "function") {
clone[key] = value;
}
});
return clone;
}
}
/**
* Meta keys returned in a list request
*
* @constant META_KEYS
*/
Page.META_KEYS = [
"end",
"first_page_uri",
"last_page_uri",
"next_page_uri",
"num_pages",
"page",
"page_size",
"previous_page_uri",
"start",
"total",
"uri",
];
exports.default = Page;

186
node_modules/twilio/lib/base/RequestClient.d.ts generated vendored Normal file
View File

@@ -0,0 +1,186 @@
import { HttpMethod } from "../interfaces";
import { AxiosInstance, InternalAxiosRequestConfig } from "axios";
import Response from "../http/response";
import Request, { Headers } from "../http/request";
import AuthStrategy from "../auth_strategy/AuthStrategy";
import { ValidationClientOptions } from "./ValidationClient";
declare class RequestClient {
defaultTimeout: number;
axios: AxiosInstance;
lastResponse?: Response<any>;
lastRequest?: Request<any>;
autoRetry: boolean;
maxRetryDelay: number;
maxRetries: number;
keepAlive: boolean;
/**
* Make http request
* @param opts - The options passed to https.Agent
* @param opts.timeout - https.Agent timeout option. Used as the socket timeout, AND as the default request timeout.
* @param opts.keepAlive - https.Agent keepAlive option
* @param opts.keepAliveMsecs - https.Agent keepAliveMsecs option
* @param opts.maxSockets - https.Agent maxSockets option
* @param opts.maxTotalSockets - https.Agent maxTotalSockets option
* @param opts.maxFreeSockets - https.Agent maxFreeSockets option
* @param opts.scheduling - https.Agent scheduling option
* @param opts.autoRetry - Enable auto-retry requests with exponential backoff on 429 responses. Defaults to false.
* @param opts.maxRetryDelay - Max retry delay in milliseconds for 429 Too Many Request response retries. Defaults to 3000.
* @param opts.maxRetries - Max number of request retries for 429 Too Many Request responses. Defaults to 3.
* @param opts.validationClient - Validation client for PKCV
*/
constructor(opts?: RequestClient.RequestClientOptions);
/**
* Make http request
* @param opts - The options argument
* @param opts.method - The http method
* @param opts.uri - The request uri
* @param opts.username - The username used for auth
* @param opts.password - The password used for auth
* @param opts.authStrategy - The authStrategy for API call
* @param opts.headers - The request headers
* @param opts.params - The request params
* @param opts.data - The request data
* @param opts.timeout - The request timeout in milliseconds (default 30000)
* @param opts.allowRedirects - Should the client follow redirects
* @param opts.forever - Set to true to use the forever-agent
* @param opts.logLevel - Show debug logs
*/
request<TData>(opts: RequestClient.RequestOptions<TData>): Promise<Response<TData>>;
filterLoggingHeaders(headers: Headers): string[];
/**
* ValidationInterceptor adds the Twilio-Client-Validation header to the request
* @param validationClient - The validation client for PKCV
* <p>Usage Example:</p>
* ```javascript
* import axios from "axios";
* // Initialize validation client with credentials
* const validationClient = {
* accountSid: "ACXXXXXXXXXXXXXXXX",
* credentialSid: "CRXXXXXXXXXXXXXXXX",
* signingKey: "SKXXXXXXXXXXXXXXXX",
* privateKey: "private key",
* algorithm: "PS256",
* }
* // construct an axios instance
* const instance = axios.create();
* instance.interceptors.request.use(
* ValidationInterceptor(opts.validationClient)
* );
* ```
*/
validationInterceptor(validationClient: ValidationClientOptions): (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig<any>;
private logRequest;
}
declare namespace RequestClient {
interface RequestOptions<TData = any, TParams = object> {
/**
* The HTTP method
*/
method: HttpMethod;
/**
* The request URI
*/
uri: string;
/**
* The username used for auth
*/
username?: string;
/**
* The password used for auth
*/
password?: string;
/**
* The AuthStrategy for API Call
*/
authStrategy?: AuthStrategy;
/**
* The request headers
*/
headers?: Headers;
/**
* The object of params added as query string to the request
*/
params?: TParams;
/**
* The form data that should be submitted
*/
data?: TData;
/**
* The request timeout in milliseconds
*/
timeout?: number;
/**
* Should the client follow redirects
*/
allowRedirects?: boolean;
/**
* Set to true to use the forever-agent
*/
forever?: boolean;
/**
* Set to 'debug' to enable debug logging
*/
logLevel?: string;
}
interface RequestClientOptions {
/**
* A timeout in milliseconds. This will be used as the HTTPS agent's socket
* timeout, AND as the default request timeout.
*/
timeout?: number;
/**
* https.Agent keepAlive option
*/
keepAlive?: boolean;
/**
* https.Agent keepAliveMSecs option
*/
keepAliveMsecs?: number;
/**
* https.Agent maxSockets option
*/
maxSockets?: number;
/**
* https.Agent maxTotalSockets option
*/
maxTotalSockets?: number;
/**
* https.Agent maxFreeSockets option
*/
maxFreeSockets?: number;
/**
* https.Agent scheduling option
*/
scheduling?: "fifo" | "lifo" | undefined;
/**
* The private CA certificate bundle (if private SSL certificate)
*/
ca?: string | Buffer;
/**
* Enable auto-retry with exponential backoff when receiving 429 Errors from
* the API. Disabled by default.
*/
autoRetry?: boolean;
/**
* Maximum retry delay in milliseconds for 429 Error response retries.
* Defaults to 3000.
*/
maxRetryDelay?: number;
/**
* Maximum number of request retries for 429 Error responses. Defaults to 3.
*/
maxRetries?: number;
/**
* Validation client for Public Key Client Validation
* On setting this with your credentials, Twilio validates:
<ul>
<li>The request comes from a sender who is in control of the private key.</li>
<li>The message has not been modified in transit.</li>
</ul>
* That the message has not been modified in transit.
* Refer our doc for details - https://www.twilio.com/docs/iam/pkcv
*/
validationClient?: ValidationClientOptions;
}
}
export = RequestClient;

281
node_modules/twilio/lib/base/RequestClient.js generated vendored Normal file
View File

@@ -0,0 +1,281 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const axios_1 = __importStar(require("axios"));
const fs = __importStar(require("fs"));
const https_proxy_agent_1 = __importDefault(require("https-proxy-agent"));
const qs_1 = __importDefault(require("qs"));
const https = __importStar(require("https"));
const response_1 = __importDefault(require("../http/response"));
const request_1 = __importDefault(require("../http/request"));
const ValidationToken_1 = __importDefault(require("../jwt/validation/ValidationToken"));
const DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
const DEFAULT_TIMEOUT = 30000;
const DEFAULT_INITIAL_RETRY_INTERVAL_MILLIS = 100;
const DEFAULT_MAX_RETRY_DELAY = 3000;
const DEFAULT_MAX_RETRIES = 3;
const DEFAULT_MAX_SOCKETS = 20;
const DEFAULT_MAX_FREE_SOCKETS = 5;
const DEFAULT_MAX_TOTAL_SOCKETS = 100;
function getExponentialBackoffResponseHandler(axios, opts) {
const maxIntervalMillis = opts.maxIntervalMillis;
const maxRetries = opts.maxRetries;
return function (res) {
const config = res.config;
if (res.status !== 429) {
return res;
}
const retryCount = (config.retryCount || 0) + 1;
if (retryCount <= maxRetries) {
config.retryCount = retryCount;
const baseDelay = Math.min(maxIntervalMillis, DEFAULT_INITIAL_RETRY_INTERVAL_MILLIS * Math.pow(2, retryCount));
const delay = Math.floor(baseDelay * Math.random()); // Full jitter backoff
return new Promise((resolve) => {
setTimeout(() => resolve(axios(config)), delay);
});
}
return res;
};
}
class RequestClient {
/**
* Make http request
* @param opts - The options passed to https.Agent
* @param opts.timeout - https.Agent timeout option. Used as the socket timeout, AND as the default request timeout.
* @param opts.keepAlive - https.Agent keepAlive option
* @param opts.keepAliveMsecs - https.Agent keepAliveMsecs option
* @param opts.maxSockets - https.Agent maxSockets option
* @param opts.maxTotalSockets - https.Agent maxTotalSockets option
* @param opts.maxFreeSockets - https.Agent maxFreeSockets option
* @param opts.scheduling - https.Agent scheduling option
* @param opts.autoRetry - Enable auto-retry requests with exponential backoff on 429 responses. Defaults to false.
* @param opts.maxRetryDelay - Max retry delay in milliseconds for 429 Too Many Request response retries. Defaults to 3000.
* @param opts.maxRetries - Max number of request retries for 429 Too Many Request responses. Defaults to 3.
* @param opts.validationClient - Validation client for PKCV
*/
constructor(opts) {
opts = opts || {};
this.defaultTimeout = opts.timeout || DEFAULT_TIMEOUT;
this.autoRetry = opts.autoRetry || false;
this.maxRetryDelay = opts.maxRetryDelay || DEFAULT_MAX_RETRY_DELAY;
this.maxRetries = opts.maxRetries || DEFAULT_MAX_RETRIES;
this.keepAlive = opts.keepAlive !== false;
// construct an https agent
let agentOpts = {
timeout: this.defaultTimeout,
keepAlive: this.keepAlive,
keepAliveMsecs: opts.keepAliveMsecs,
maxSockets: opts.maxSockets || DEFAULT_MAX_SOCKETS, // no of sockets open per host
maxTotalSockets: opts.maxTotalSockets || DEFAULT_MAX_TOTAL_SOCKETS, // no of sockets open in total
maxFreeSockets: opts.maxFreeSockets || DEFAULT_MAX_FREE_SOCKETS, // no of free sockets open per host
scheduling: opts.scheduling,
ca: opts.ca,
};
// sets https agent CA bundle if defined in CA bundle filepath env variable
if (process.env.TWILIO_CA_BUNDLE !== undefined) {
if (agentOpts.ca === undefined) {
agentOpts.ca = fs.readFileSync(process.env.TWILIO_CA_BUNDLE);
}
}
let agent;
if (process.env.HTTP_PROXY) {
// Note: if process.env.HTTP_PROXY is set, we're not able to apply the given
// socket timeout. See: https://github.com/TooTallNate/node-https-proxy-agent/pull/96
agent = (0, https_proxy_agent_1.default)(process.env.HTTP_PROXY);
}
else {
agent = new https.Agent(agentOpts);
}
// construct an axios instance
this.axios = axios_1.default.create();
this.axios.defaults.headers.post["Content-Type"] = DEFAULT_CONTENT_TYPE;
this.axios.defaults.httpsAgent = agent;
if (opts.autoRetry) {
this.axios.interceptors.response.use(getExponentialBackoffResponseHandler(this.axios, {
maxIntervalMillis: this.maxRetryDelay,
maxRetries: this.maxRetries,
}));
}
// if validation client is set, intercept the request using ValidationInterceptor
if (opts.validationClient) {
this.axios.interceptors.request.use(this.validationInterceptor(opts.validationClient));
}
}
/**
* Make http request
* @param opts - The options argument
* @param opts.method - The http method
* @param opts.uri - The request uri
* @param opts.username - The username used for auth
* @param opts.password - The password used for auth
* @param opts.authStrategy - The authStrategy for API call
* @param opts.headers - The request headers
* @param opts.params - The request params
* @param opts.data - The request data
* @param opts.timeout - The request timeout in milliseconds (default 30000)
* @param opts.allowRedirects - Should the client follow redirects
* @param opts.forever - Set to true to use the forever-agent
* @param opts.logLevel - Show debug logs
*/
async request(opts) {
if (!opts.method) {
throw new Error("http method is required");
}
if (!opts.uri) {
throw new Error("uri is required");
}
var headers = opts.headers || {};
if (!headers.Connection && !headers.connection)
headers.Connection = this.keepAlive ? "keep-alive" : "close";
let auth = undefined;
if (opts.username && opts.password) {
auth = Buffer.from(opts.username + ":" + opts.password).toString("base64");
headers.Authorization = "Basic " + auth;
}
else if (opts.authStrategy) {
headers.Authorization = await opts.authStrategy.getAuthString();
}
const options = {
timeout: opts.timeout || this.defaultTimeout,
maxRedirects: opts.allowRedirects ? 10 : 0,
url: opts.uri,
method: opts.method,
headers: opts.headers,
proxy: false,
validateStatus: (status) => status >= 100 && status < 600,
};
if (opts.data && options.headers) {
if (options.headers["Content-Type"] === "application/x-www-form-urlencoded") {
options.data = qs_1.default.stringify(opts.data, { arrayFormat: "repeat" });
}
else if (options.headers["Content-Type"] === "application/json") {
options.data = opts.data;
}
}
if (opts.params) {
options.params = opts.params;
options.paramsSerializer = (params) => {
return qs_1.default.stringify(params, { arrayFormat: "repeat" });
};
}
const requestOptions = {
method: opts.method,
url: opts.uri,
auth: auth,
params: options.params,
data: opts.data,
headers: opts.headers,
};
if (opts.logLevel === "debug") {
this.logRequest(requestOptions);
}
const _this = this;
this.lastResponse = undefined;
this.lastRequest = new request_1.default(requestOptions);
return this.axios(options)
.then((response) => {
if (opts.logLevel === "debug") {
console.log(`response.statusCode: ${response.status}`);
console.log(`response.headers: ${JSON.stringify(response.headers)}`);
}
_this.lastResponse = new response_1.default(response.status, response.data, response.headers);
return {
statusCode: response.status,
body: response.data,
headers: response.headers,
};
})
.catch((error) => {
_this.lastResponse = undefined;
throw error;
});
}
filterLoggingHeaders(headers) {
return Object.keys(headers).filter((header) => {
return !"authorization".includes(header.toLowerCase());
});
}
/**
* ValidationInterceptor adds the Twilio-Client-Validation header to the request
* @param validationClient - The validation client for PKCV
* <p>Usage Example:</p>
* ```javascript
* import axios from "axios";
* // Initialize validation client with credentials
* const validationClient = {
* accountSid: "ACXXXXXXXXXXXXXXXX",
* credentialSid: "CRXXXXXXXXXXXXXXXX",
* signingKey: "SKXXXXXXXXXXXXXXXX",
* privateKey: "private key",
* algorithm: "PS256",
* }
* // construct an axios instance
* const instance = axios.create();
* instance.interceptors.request.use(
* ValidationInterceptor(opts.validationClient)
* );
* ```
*/
validationInterceptor(validationClient) {
return function (config) {
config.headers = config.headers || new axios_1.AxiosHeaders();
try {
config.headers["Twilio-Client-Validation"] = new ValidationToken_1.default(validationClient).fromHttpRequest(config);
}
catch (err) {
console.log("Error creating Twilio-Client-Validation header:", err);
throw err;
}
return config;
};
}
logRequest(options) {
console.log("-- BEGIN Twilio API Request --");
console.log(`${options.method} ${options.url}`);
if (options.params) {
console.log("Querystring:");
console.log(options.params);
}
if (options.headers) {
console.log("Headers:");
const filteredHeaderKeys = this.filterLoggingHeaders(options.headers);
filteredHeaderKeys.forEach((header) => console.log(`${header}: ${options.headers?.header}`));
}
console.log("-- END Twilio API Request --");
}
}
module.exports = RequestClient;

16
node_modules/twilio/lib/base/RestException.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
interface RestExceptionError {
status: number;
message?: string;
code?: number;
moreInfo?: string;
details?: object;
}
export default class RestException extends Error implements RestExceptionError {
status: number;
message: string;
code?: number;
moreInfo?: string;
details?: object;
constructor(response: any);
}
export {};

33
node_modules/twilio/lib/base/RestException.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class RestException extends Error {
constructor(response) {
super("[HTTP " + response.statusCode + "] Failed to execute request");
const isResponseBodyString = typeof response.body == "string";
const body = isResponseBodyString
? parseResponseBody(response.body)
: response.body;
this.status = response.statusCode;
if (body !== null) {
this.message = body.message;
this.code = body.code;
this.moreInfo = body.more_info; /* jshint ignore:line */
this.details = body.details;
}
else {
this.message =
"[HTTP " + response.statusCode + "] Failed to execute request";
}
}
}
exports.default = RestException;
function parseResponseBody(response_body) {
let body = null;
try {
body = JSON.parse(response_body);
}
catch (catchError) {
body = null;
}
return body;
}

134
node_modules/twilio/lib/base/TokenPage.d.ts generated vendored Normal file
View File

@@ -0,0 +1,134 @@
import Version from "./Version";
import Response from "../http/response";
/**
* Token-based pagination metadata structure
* Used for APIs that return pagination tokens instead of URLs
*/
export interface TokenPaginationPayload {
[key: string]: any;
meta: {
key: string;
pageSize?: number;
nextToken?: string | null;
previousToken?: string | null;
};
}
interface Solution {
[name: string]: any;
}
/**
* TokenPage handles token-based pagination where the API returns
* nextToken/previousToken strings instead of full URLs.
*
* Example response format:
* {
* "meta": {
* "key": "items",
* "pageSize": 50,
* "nextToken": "abc123",
* "previousToken": "xyz789"
* },
* "items": [
* { "id": 1, "name": "Item 1" },
* { "id": 2, "name": "Item 2" }
* ]
* }
*/
export default class TokenPage<TVersion extends Version, TPayload extends TokenPaginationPayload, TResource, TInstance> {
instances: TInstance[];
protected _version: TVersion;
protected _payload: TPayload;
protected _solution: Solution;
private readonly _uri;
private readonly _params;
/**
* Base page object to maintain request state for token-based pagination.
*
* @param version - A twilio version instance
* @param response - The http response
* @param uri - The URI for making pagination requests
* @param data - The request parameters
* @param solution - path solution
*/
constructor(version: TVersion, response: Response<string | TPayload>, uri: string, data?: Record<string, any>, solution?: Solution);
/**
* Parse json response from API
*
* @param response - API response
*
* @throws Error If non 200 status code is returned
*
* @returns json parsed response
*/
processResponse(response: Response<string | TPayload>): TPayload;
/**
* Load a page of records from the payload
*
* @param payload - json payload
* @returns the page of records
*/
loadPage(payload: TPayload): TResource[];
/**
* Build a new instance given a json payload
*
* @param payload - Payload response from the API
* @returns instance of a resource
*/
getInstance(payload: TResource): TInstance;
/**
* Load a list of records
*
* @param resources - json payload of records
* @returns list of resources
*/
loadInstances(resources: TResource[]): TInstance[];
toJSON(): object;
/**
* Returns the key that identifies the collection in the response.
*
* @returns the key or undefined if doesn't exist
*/
get key(): string | undefined;
/**
* Returns the page size or undefined if doesn't exist.
*
* @returns the page size or undefined
*/
get pageSize(): number | undefined;
/**
* Returns the next_token for pagination or undefined if doesn't exist.
*
* @returns the next token or undefined
*/
get nextToken(): string | undefined;
/**
* Returns the previous_token for pagination or undefined if doesn't exist.
*
* @returns the previous token or undefined
*/
get previousToken(): string | undefined;
/**
* Internal helper to fetch a page using a given token.
*
* @param token - The pagination token to use
* @returns promise that resolves to the page or undefined if no token exists
*/
private _getPage;
/**
* Fetch the next page of records using token-based pagination.
* Makes a request to the same URI with pageToken set to nextToken.
*
* @returns promise that resolves to next page of results,
* or undefined if there isn't a nextToken.
*/
nextPage(): Promise<TokenPage<TVersion, TPayload, TResource, TInstance>> | undefined;
/**
* Fetch the previous page of records using token-based pagination.
* Makes a request to the same URI with pageToken set to previousToken.
*
* @returns promise that resolves to previous page of results,
* or undefined if there isn't a previousToken.
*/
previousPage(): Promise<TokenPage<TVersion, TPayload, TResource, TInstance>> | undefined;
}
export {};

197
node_modules/twilio/lib/base/TokenPage.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RestException_1 = __importDefault(require("./RestException"));
/**
* TokenPage handles token-based pagination where the API returns
* nextToken/previousToken strings instead of full URLs.
*
* Example response format:
* {
* "meta": {
* "key": "items",
* "pageSize": 50,
* "nextToken": "abc123",
* "previousToken": "xyz789"
* },
* "items": [
* { "id": 1, "name": "Item 1" },
* { "id": 2, "name": "Item 2" }
* ]
* }
*/
class TokenPage {
/**
* Base page object to maintain request state for token-based pagination.
*
* @param version - A twilio version instance
* @param response - The http response
* @param uri - The URI for making pagination requests
* @param data - The request parameters
* @param solution - path solution
*/
constructor(version, response, uri, data = {}, solution = {}) {
const payload = this.processResponse(response);
this._version = version;
this._payload = payload;
this._solution = solution;
this._uri = uri;
this._params = data;
this.instances = this.loadInstances(this.loadPage(payload));
}
/**
* Parse json response from API
*
* @param response - API response
*
* @throws Error If non 200 status code is returned
*
* @returns json parsed response
*/
processResponse(response) {
if (response.statusCode !== 200) {
throw new RestException_1.default(response);
}
if (typeof response.body === "string") {
return JSON.parse(response.body);
}
return response.body;
}
/**
* Load a page of records from the payload
*
* @param payload - json payload
* @returns the page of records
*/
loadPage(payload) {
if (payload.meta?.key) {
return payload[payload.meta.key];
}
throw new Error("Token pagination requires meta.key to be present in response");
}
/**
* Build a new instance given a json payload
*
* @param payload - Payload response from the API
* @returns instance of a resource
*/
getInstance(payload) {
throw new Error("TokenPage.getInstance() must be implemented in the derived class");
}
/**
* Load a list of records
*
* @param resources - json payload of records
* @returns list of resources
*/
loadInstances(resources) {
const instances = [];
resources.forEach((resource) => {
instances.push(this.getInstance(resource));
});
return instances;
}
toJSON() {
const clone = {};
Object.entries(this).forEach(([key, value]) => {
if (!key.startsWith("_") && typeof value !== "function") {
clone[key] = value;
}
});
return clone;
}
/**
* Returns the key that identifies the collection in the response.
*
* @returns the key or undefined if doesn't exist
*/
get key() {
if (this._payload.meta && this._payload.meta.key) {
return this._payload.meta.key;
}
return undefined;
}
/**
* Returns the page size or undefined if doesn't exist.
*
* @returns the page size or undefined
*/
get pageSize() {
if (this._payload.meta && this._payload.meta.pageSize) {
return this._payload.meta.pageSize;
}
return undefined;
}
/**
* Returns the next_token for pagination or undefined if doesn't exist.
*
* @returns the next token or undefined
*/
get nextToken() {
if (this._payload.meta &&
this._payload.meta.nextToken !== undefined &&
this._payload.meta.nextToken !== null) {
return this._payload.meta.nextToken;
}
return undefined;
}
/**
* Returns the previous_token for pagination or undefined if doesn't exist.
*
* @returns the previous token or undefined
*/
get previousToken() {
if (this._payload.meta &&
this._payload.meta.previousToken !== undefined &&
this._payload.meta.previousToken !== null) {
return this._payload.meta.previousToken;
}
return undefined;
}
/**
* Internal helper to fetch a page using a given token.
*
* @param token - The pagination token to use
* @returns promise that resolves to the page or undefined if no token exists
*/
_getPage(token) {
if (!token) {
return undefined;
}
if (!this._uri) {
throw new Error("URI must be provided for token pagination");
}
const params = { ...this._params, pageToken: token };
const responsePromise = this._version.page({
method: "get",
uri: this._uri,
params: params,
});
return responsePromise.then((response) => {
return new this.constructor(this._version, response, this._uri, this._params, this._solution);
});
}
/**
* Fetch the next page of records using token-based pagination.
* Makes a request to the same URI with pageToken set to nextToken.
*
* @returns promise that resolves to next page of results,
* or undefined if there isn't a nextToken.
*/
nextPage() {
return this._getPage(this.nextToken);
}
/**
* Fetch the previous page of records using token-based pagination.
* Makes a request to the same URI with pageToken set to previousToken.
*
* @returns promise that resolves to previous page of results,
* or undefined if there isn't a previousToken.
*/
previousPage() {
return this._getPage(this.previousToken);
}
}
exports.default = TokenPage;

View File

@@ -0,0 +1,30 @@
interface ValidationError {
detail: string;
pointer: string;
}
interface TwilioServiceErrorResponse {
type: string;
title: string;
status: number;
detail?: string;
instance?: string;
code: number;
errors?: ValidationError[];
}
export default class TwilioServiceException extends Error implements TwilioServiceErrorResponse {
type: string;
title: string;
status: number;
detail?: string;
instance?: string;
code: number;
errors?: ValidationError[];
constructor(response: any);
/**
* Check if a response body matches the RFC-9457 structure
* @param body - The response body to check
* @returns true if the body has the required RFC-9457 fields
*/
static isRFC9457Response(body: any): boolean;
}
export {};

54
node_modules/twilio/lib/base/TwilioServiceException.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TwilioServiceException extends Error {
constructor(response) {
const isResponseBodyString = typeof response.body == "string";
const body = isResponseBodyString
? parseResponseBody(response.body)
: response.body;
// Initialize status first for the error message
const status = body?.status || response.statusCode;
super(`[HTTP ${status}] ${body?.title || "Failed to execute request"}`);
// Set all required properties
this.type = body?.type || "";
this.title = body?.title || "Failed to execute request";
this.status = status;
this.code = body?.code || 0;
// Set optional properties
if (body?.detail) {
this.detail = body.detail;
}
if (body?.instance) {
this.instance = body.instance;
}
if (body?.errors) {
this.errors = body.errors;
}
}
/**
* Check if a response body matches the RFC-9457 structure
* @param body - The response body to check
* @returns true if the body has the required RFC-9457 fields
*/
static isRFC9457Response(body) {
if (!body || typeof body !== "object") {
return false;
}
// Check for required fields according to the spec
return (typeof body.type === "string" &&
typeof body.title === "string" &&
typeof body.status === "number" &&
typeof body.code === "number");
}
}
exports.default = TwilioServiceException;
function parseResponseBody(response_body) {
let body = null;
try {
body = JSON.parse(response_body);
}
catch (catchError) {
body = null;
}
return body;
}

10
node_modules/twilio/lib/base/ValidationClient.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
declare namespace ValidationClient {
interface ValidationClientOptions {
accountSid: string;
credentialSid: string;
signingKey: string;
privateKey: string;
algorithm?: string;
}
}
export = ValidationClient;

2
node_modules/twilio/lib/base/ValidationClient.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

241
node_modules/twilio/lib/base/Version.d.ts generated vendored Normal file
View File

@@ -0,0 +1,241 @@
import Domain from "./Domain";
import { RequestOpts } from "./BaseTwilio";
import { ApiResponse } from "./ApiResponse";
export interface PageLimitOptions {
/**
* The maximum number of items to fetch
*/
limit: number;
/**
* The maximum number of items to return with every request
*/
pageSize: number;
}
export interface PageLimit {
limit: number;
pageSize: number;
}
export default class Version {
_domain: Domain;
_version: Version | string;
/**
*
* Base version object
*
* @param domain - twilio domain
* @param version - api version
*/
constructor(domain: Domain, version: string | Version);
get domain(): Domain;
/**
* Throws the appropriate exception based on the response format
*
* @param response - the response object
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
*/
private throwException;
/**
* Generate absolute url from a uri
*
* @param uri - uri to transform
* @returns transformed url
*/
absoluteUrl(uri: string): string;
/**
* Generate relative url from a uri
*
* @param uri - uri to transform
* @returns transformed url
*/
relativeUrl(uri: string): string;
/**
* Make a request against the domain
*
* @param opts - request options
* @returns promise that resolves to request response
*/
request(opts: RequestOpts): Promise<any>;
/**
* Create a new record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx or 201 status code
*
* @returns promise that resolves to created record
*/
create(opts: RequestOpts): Promise<any>;
/**
* Fetch an instance of a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx or 3xx status code
*
* @returns promise that resolves to fetched result
*/
fetch(opts: RequestOpts): Promise<any>;
/**
* Fetch a page of records
*
* @param opts - request options
* @returns promise that resolves to page of records
*/
page(opts: RequestOpts): Promise<any>;
/**
* Update a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to updated result
*/
update(opts: RequestOpts): Promise<any>;
/**
* Patch a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to patched result
*/
patch(opts: RequestOpts): Promise<any>;
/**
* Delete a record
*
* @param opts - request options
*
* @throws Error If response returns a 5xx status
*
* @returns promise that resolves to true if record was deleted
*/
remove(opts: RequestOpts): Promise<boolean>;
/**
* Create a new record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx or 201 status code
*
* @returns promise that resolves to ApiResponse with created record and metadata
*/
createWithResponseInfo<T>(opts: RequestOpts): Promise<ApiResponse<T>>;
/**
* Fetch an instance of a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx or 3xx status code
*
* @returns promise that resolves to ApiResponse with fetched record and metadata
*/
fetchWithResponseInfo<T>(opts: RequestOpts): Promise<ApiResponse<T>>;
/**
* Update a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to ApiResponse with updated record and metadata
*/
updateWithResponseInfo<T>(opts: RequestOpts): Promise<ApiResponse<T>>;
/**
* Patch a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to ApiResponse with patched record and metadata
*/
patchWithResponseInfo<T>(opts: RequestOpts): Promise<ApiResponse<T>>;
/**
* Delete a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns a 5xx status
*
* @returns promise that resolves to ApiResponse with boolean and metadata
*/
removeWithResponseInfo(opts: RequestOpts): Promise<ApiResponse<boolean>>;
/**
* Process limits for list requests
*
* @param opts.limit - The maximum number of items to fetch
* @param opts.pageSize - The maximum number of items to return with every request
*
*/
readLimits(opts: PageLimitOptions): PageLimit;
setPromiseCallback(operationPromise: any, callback: any): Promise<any>;
/**
* For each record instance, executes a provided callback function with that
* instance
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to
* fetch
* @param params.pageSize - Optional maximum number of records to return
* with every request
* @param params.callback - Callback function to call with each
* record instance
* @param params.done - Optional done function to call when all
* records are processed, the limit is reached, or an error occurs.
* Receives an error argument if an error occurs.
* @param callback - Callback function to call with each record.
* Receives a done function argument that will short-circuit the for-each
* loop that may accept an error argument.
* @returns Returns a promise that resolves when all records
* processed or if the limit is reached, and rejects with an error if an
* error occurs and is not handled in the user provided done function.
*/
each<T>(params?: any, callback?: (item: T, done: (err?: Error) => void) => void): Promise<void>;
list<T>(params?: any, callback?: (error: Error | null, items: T) => any): Promise<any>;
/**
* For each record instance, executes a provided callback function with that
* instance and captures HTTP response metadata from the first page
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to
* fetch
* @param params.pageSize - Optional maximum number of records to return
* with every request
* @param params.callback - Callback function to call with each
* record instance
* @param params.done - Optional done function to call when all
* records are processed, the limit is reached, or an error occurs.
* Receives an error argument if an error occurs, and ApiResponse metadata.
* @param callback - Callback function to call with each record.
* Receives a done function argument that will short-circuit the for-each
* loop that may accept an error argument.
* @returns Returns a promise that resolves with first page metadata when all records
* processed or if the limit is reached, and rejects with an error if an
* error occurs and is not handled in the user provided done function.
*/
eachWithHttpInfo<T>(params?: any, callback?: (item: T, done: (err?: Error) => void) => void): Promise<ApiResponse<void>>;
/**
* Fetches all records and returns them as an array with HTTP response metadata
* from the first page
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to fetch
* @param params.pageSize - Optional maximum number of records to return with every request
* @param callback - Optional callback function
* @returns Promise that resolves to ApiResponse with array of all records and first page metadata
*/
listWithHttpInfo<T>(params?: any, callback?: (error: Error | null, items: ApiResponse<T[]>) => any): Promise<ApiResponse<T[]>>;
}

747
node_modules/twilio/lib/base/Version.js generated vendored Normal file
View File

@@ -0,0 +1,747 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RestException_1 = __importDefault(require("./RestException"));
const TwilioServiceException_1 = __importDefault(require("./TwilioServiceException"));
const utility_1 = require("./utility");
class Version {
/**
*
* Base version object
*
* @param domain - twilio domain
* @param version - api version
*/
constructor(domain, version) {
this._domain = domain;
this._version = version;
}
get domain() {
return this._domain;
}
/**
* Throws the appropriate exception based on the response format
*
* @param response - the response object
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
*/
throwException(response) {
const isResponseBodyString = typeof response.body === "string";
let body = null;
if (isResponseBodyString) {
try {
body = JSON.parse(response.body);
}
catch (e) {
// If parsing fails, body remains null
}
}
else {
body = response.body;
}
// Check if response matches RFC-9457 format
if (TwilioServiceException_1.default.isRFC9457Response(body)) {
throw new TwilioServiceException_1.default(response);
}
// Fall back to legacy RestException
throw new RestException_1.default(response);
}
/**
* Generate absolute url from a uri
*
* @param uri - uri to transform
* @returns transformed url
*/
absoluteUrl(uri) {
return this._domain.absoluteUrl(this.relativeUrl(uri));
}
/**
* Generate relative url from a uri
*
* @param uri - uri to transform
* @returns transformed url
*/
relativeUrl(uri) {
var result = "";
if (typeof this._version === "string") {
const version = (0, utility_1.trim)(this._version, "/");
result += version;
result += "/";
}
if (typeof uri === "string") {
uri = (0, utility_1.trim)(uri, "/");
if (result === "") {
result += "/";
}
result += uri;
}
return result;
}
/**
* Make a request against the domain
*
* @param opts - request options
* @returns promise that resolves to request response
*/
request(opts) {
return this._domain.request({
...opts,
uri: this.relativeUrl(opts.uri || ""),
});
}
/**
* Create a new record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx or 201 status code
*
* @returns promise that resolves to created record
*/
create(opts) {
var qResponse = this.request(opts);
qResponse = qResponse.then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
if (typeof response.body === "string") {
return JSON.parse(response.body);
}
return response.body;
});
return qResponse;
}
/**
* Fetch an instance of a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx or 3xx status code
*
* @returns promise that resolves to fetched result
*/
fetch(opts) {
var qResponse = this.request(opts);
qResponse = qResponse.then((response) => {
if (response.statusCode < 200 || response.statusCode >= 400) {
this.throwException(response);
}
if (typeof response.body === "string") {
return JSON.parse(response.body);
}
return response.body;
});
return qResponse;
}
/**
* Fetch a page of records
*
* @param opts - request options
* @returns promise that resolves to page of records
*/
page(opts) {
return this.request(opts);
}
/**
* Update a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to updated result
*/
update(opts) {
var qResponse = this.request(opts);
qResponse = qResponse.then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
if (typeof response.body === "string") {
return JSON.parse(response.body);
}
return response.body;
});
return qResponse;
}
/**
* Patch a record
*
* @param opts - request options
*
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to patched result
*/
async patch(opts) {
const response = await this.request(opts);
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
return typeof response.body === "string"
? JSON.parse(response.body)
: response.body;
}
/**
* Delete a record
*
* @param opts - request options
*
* @throws Error If response returns a 5xx status
*
* @returns promise that resolves to true if record was deleted
*/
remove(opts) {
let qResponse = this.request(opts);
qResponse = qResponse.then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
return true; // if response code is 2XX, deletion was successful
});
return qResponse;
}
/**
* Create a new record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx or 201 status code
*
* @returns promise that resolves to ApiResponse with created record and metadata
*/
createWithResponseInfo(opts) {
return this.request(opts).then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
let body;
if (typeof response.body === "string") {
body = JSON.parse(response.body);
}
else {
body = response.body;
}
return {
body: body,
statusCode: response.statusCode,
headers: response.headers,
};
});
}
/**
* Fetch an instance of a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx or 3xx status code
*
* @returns promise that resolves to ApiResponse with fetched record and metadata
*/
fetchWithResponseInfo(opts) {
return this.request(opts).then((response) => {
if (response.statusCode < 200 || response.statusCode >= 400) {
this.throwException(response);
}
let body;
if (typeof response.body === "string") {
body = JSON.parse(response.body);
}
else {
body = response.body;
}
return {
body: body,
statusCode: response.statusCode,
headers: response.headers,
};
});
}
/**
* Update a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to ApiResponse with updated record and metadata
*/
updateWithResponseInfo(opts) {
return this.request(opts).then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
let body;
if (typeof response.body === "string") {
body = JSON.parse(response.body);
}
else {
body = response.body;
}
return {
body: body,
statusCode: response.statusCode,
headers: response.headers,
};
});
}
/**
* Patch a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns non 2xx status code
*
* @returns promise that resolves to ApiResponse with patched record and metadata
*/
async patchWithResponseInfo(opts) {
const response = await this.request(opts);
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
let body;
if (typeof response.body === "string") {
body = JSON.parse(response.body);
}
else {
body = response.body;
}
return {
body: body,
statusCode: response.statusCode,
headers: response.headers,
};
}
/**
* Delete a record and return response metadata
*
* @param opts - request options
*
* @throws TwilioServiceException if response matches RFC-9457 format
* @throws RestException for legacy format
* @throws Error If response returns a 5xx status
*
* @returns promise that resolves to ApiResponse with boolean and metadata
*/
removeWithResponseInfo(opts) {
return this.request(opts).then((response) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throwException(response);
}
return {
body: true, // if response code is 2XX, deletion was successful
statusCode: response.statusCode,
headers: response.headers,
};
});
}
/**
* Process limits for list requests
*
* @param opts.limit - The maximum number of items to fetch
* @param opts.pageSize - The maximum number of items to return with every request
*
*/
readLimits(opts) {
var limit = opts.limit;
var pageSize = opts.pageSize;
if ((limit && !Number.isFinite(limit)) || limit <= 0) {
throw new TypeError("Parameter limit must be a positive integer");
}
if (pageSize && (!Number.isFinite(pageSize) || pageSize <= 0)) {
throw new TypeError("Parameter pageSize must be a positive integer");
}
if (limit && !pageSize) {
pageSize = limit;
}
return {
limit: limit,
pageSize: pageSize,
};
}
setPromiseCallback(operationPromise, callback) {
if (typeof callback === "function") {
operationPromise = operationPromise
.then((value) => callback(null, value))
.catch((error) => callback(error));
}
return operationPromise;
}
/**
* For each record instance, executes a provided callback function with that
* instance
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to
* fetch
* @param params.pageSize - Optional maximum number of records to return
* with every request
* @param params.callback - Callback function to call with each
* record instance
* @param params.done - Optional done function to call when all
* records are processed, the limit is reached, or an error occurs.
* Receives an error argument if an error occurs.
* @param callback - Callback function to call with each record.
* Receives a done function argument that will short-circuit the for-each
* loop that may accept an error argument.
* @returns Returns a promise that resolves when all records
* processed or if the limit is reached, and rejects with an error if an
* error occurs and is not handled in the user provided done function.
*/
each(params, callback) {
if (typeof params === "function") {
callback = params;
params = {};
}
else {
params = params || {};
}
if (params.callback) {
callback = params.callback;
}
if (typeof callback === "undefined") {
throw new Error("Callback function must be provided");
}
let done = false;
let doneCalled = false;
let currentPage = 1;
let currentResource = 0;
let limits = {};
let pPending = true;
let pResolve;
let pReject;
if (this._version instanceof Version) {
limits = this._version.readLimits({
limit: params.limit,
pageSize: params.pageSize,
});
}
function onComplete(error) {
let unhandledError = error;
done = true;
if (typeof params.done === "function" && !doneCalled) {
try {
params.done(unhandledError);
unhandledError = null;
}
catch (e) {
unhandledError = e;
}
}
doneCalled = true;
if (pPending) {
if (unhandledError) {
pReject(unhandledError);
}
else {
pResolve();
}
pPending = false;
}
}
function fetchNextPage(fn) {
let promise = fn();
if (typeof promise === "undefined") {
onComplete();
return;
}
promise
.then((page) => {
try {
page.instances.forEach(function (instance) {
if (done ||
(typeof params.limit !== "undefined" &&
currentResource >= params.limit)) {
done = true;
return false;
}
currentResource++;
callback?.(instance, onComplete);
});
}
catch (e) {
return onComplete(e);
}
if (!done) {
currentPage++;
fetchNextPage(page.nextPage.bind(page));
}
else {
onComplete();
}
})
.catch(onComplete);
}
return new Promise((resolve, reject) => {
pResolve = resolve;
pReject = reject;
fetchNextPage(this.page.bind(this, Object.assign(params, limits)));
});
}
list(params, callback) {
if (typeof params === "function") {
callback = params;
params = {};
}
else {
params = params || {};
}
let allResources = [];
params.callback = function (resource, done) {
allResources.push(resource);
if (typeof params.limit !== "undefined" &&
allResources.length === params.limit) {
done();
}
};
let operationPromise = new Promise((resolve, reject) => {
params.done = function (error) {
if (typeof error === "undefined") {
resolve(allResources);
}
else {
reject(error);
}
};
});
if (this._version instanceof Version) {
operationPromise = this._version.setPromiseCallback(operationPromise, callback);
}
this.each(params);
return operationPromise;
}
/**
* For each record instance, executes a provided callback function with that
* instance and captures HTTP response metadata from the first page
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to
* fetch
* @param params.pageSize - Optional maximum number of records to return
* with every request
* @param params.callback - Callback function to call with each
* record instance
* @param params.done - Optional done function to call when all
* records are processed, the limit is reached, or an error occurs.
* Receives an error argument if an error occurs, and ApiResponse metadata.
* @param callback - Callback function to call with each record.
* Receives a done function argument that will short-circuit the for-each
* loop that may accept an error argument.
* @returns Returns a promise that resolves with first page metadata when all records
* processed or if the limit is reached, and rejects with an error if an
* error occurs and is not handled in the user provided done function.
*/
eachWithHttpInfo(params, callback) {
if (typeof params === "function") {
callback = params;
params = {};
}
else {
params = params || {};
}
if (params.callback) {
callback = params.callback;
}
if (typeof callback === "undefined") {
throw new Error("Callback function must be provided");
}
let done = false;
let doneCalled = false;
let currentPage = 1;
let currentResource = 0;
let limits = {};
let pPending = true;
let pResolve;
let pReject;
let firstPageMetadata = null;
if (this._version instanceof Version) {
limits = this._version.readLimits({
limit: params.limit,
pageSize: params.pageSize,
});
}
function onComplete(error) {
let unhandledError = error;
done = true;
if (typeof params.done === "function" && !doneCalled) {
try {
params.done(unhandledError, firstPageMetadata);
unhandledError = null;
}
catch (e) {
unhandledError = e;
}
}
doneCalled = true;
if (pPending) {
if (unhandledError) {
pReject(unhandledError);
}
else {
// firstPageMetadata is guaranteed to be set here because:
// 1. If no page was fetched, we already rejected with error
// 2. If page was fetched, firstPageMetadata was set in the .then() handler
pResolve({
body: undefined,
statusCode: firstPageMetadata.statusCode,
headers: firstPageMetadata.headers,
});
}
pPending = false;
}
}
function fetchNextPageWithInfo(fn) {
let promise = fn();
if (typeof promise === "undefined" || promise === null) {
// If this is the first page and we got null/undefined, that's an error
// If this is a subsequent page, null means "no more pages" (success)
if (currentPage === 1) {
pReject(new Error("Page method did not return a Promise"));
pPending = false;
}
else {
onComplete();
}
return;
}
promise
.then((response) => {
// Handle both cases:
// 1. Version.page() returns { statusCode, body, headers }
// 2. Resource.page() returns Page object directly
let pageData = response.body !== undefined ? response.body : response;
// Capture first page metadata on first page
if (currentPage === 1 && !firstPageMetadata) {
if (response.statusCode !== undefined) {
// Case 1: Response structure with metadata
firstPageMetadata = {
statusCode: response.statusCode,
headers: response.headers || {},
};
}
else {
// Case 2: Direct Page object (no metadata available)
firstPageMetadata = {
statusCode: 200,
headers: {},
};
}
}
// Parse body if it's a string
if (typeof pageData === "string") {
pageData = JSON.parse(pageData);
}
try {
pageData.instances.forEach(function (instance) {
if (done ||
(typeof params.limit !== "undefined" &&
currentResource >= params.limit)) {
done = true;
return false;
}
currentResource++;
callback?.(instance, onComplete);
});
}
catch (e) {
return onComplete(e);
}
if (!done) {
currentPage++;
// Page's nextPage method should already return response structure
const nextPageFn = pageData.nextPage?.bind(pageData);
if (nextPageFn) {
fetchNextPageWithInfo(nextPageFn);
}
else {
onComplete();
}
}
else {
onComplete();
}
})
.catch(onComplete);
}
return new Promise((resolve, reject) => {
pResolve = resolve;
pReject = reject;
const pageParams = Object.assign({}, params, limits);
fetchNextPageWithInfo(() => {
// Use pageWithHttpInfo() if available to capture HTTP metadata, otherwise use page()
// When called from resources, this.pageWithHttpInfo exists and returns { statusCode, body, headers }
// When called from Version directly, this.page returns { statusCode, body, headers }
if (typeof this.pageWithHttpInfo === "function") {
return this.pageWithHttpInfo(pageParams);
}
return this.page(pageParams);
});
});
}
/**
* Fetches all records and returns them as an array with HTTP response metadata
* from the first page
*
* @param params - Parameters (Optional)
* @param params.limit - Optional maximum number of record instances to fetch
* @param params.pageSize - Optional maximum number of records to return with every request
* @param callback - Optional callback function
* @returns Promise that resolves to ApiResponse with array of all records and first page metadata
*/
listWithHttpInfo(params, callback) {
if (typeof params === "function") {
callback = params;
params = {};
}
else {
params = params || {};
}
let allResources = [];
let firstPageMetadata = null;
params.callback = function (resource, done) {
allResources.push(resource);
if (typeof params.limit !== "undefined" &&
allResources.length === params.limit) {
done();
}
};
let operationPromise = new Promise((resolve, reject) => {
params.done = function (error, metadata) {
if (metadata) {
firstPageMetadata = metadata;
}
if (typeof error === "undefined") {
// firstPageMetadata is guaranteed to be set here because:
// eachWithHttpInfo either:
// 1. Rejects with error (no page fetched)
// 2. Passes metadata to done callback (page was fetched)
resolve({
body: allResources,
statusCode: firstPageMetadata.statusCode,
headers: firstPageMetadata.headers,
});
}
else {
reject(error);
}
};
});
if (this._version instanceof Version) {
operationPromise = this._version.setPromiseCallback(operationPromise, callback);
}
this.eachWithHttpInfo(params);
return operationPromise;
}
}
exports.default = Version;

41
node_modules/twilio/lib/base/deserialize.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
export interface NumberParser {
(n: string): number;
}
/**
* @namespace deserialize
*/
/**
* Parse a string into a Date object
*
* @param s - Date string in YYYY-MM-DD format
* @returns Date object, or the original date string if the argument is not a valid date
*/
export declare function iso8601Date(s: string): string | Date;
/**
* Parse a string into a Date object
*
* @param s - Date string in YYYY-MM-DD[T]HH:mm:ss[Z] format
* @returns Date object, or the original date string if the argument is not a valid date
*/
export declare function iso8601DateTime(s: string): string | Date;
/**
* Parse a string into a Date object
*
* @param s - Date string in ddd, DD MMM YYYY HH:mm:ss [+0000] format
* @returns Date object, or the original date string if the argument is not a valid date
*/
export declare function rfc2822DateTime(s: string): string | Date;
/**
* Parse a string into a decimal
*
* @param d - Decimal value as string
* @returns Number, or the original string if the argument is NaN
*/
export declare function decimal(d: string): string | number;
/**
* Parse a string into a integer
*
* @param i - Integer value as string
* @returns Number, or the original string if the argument is NaN
*/
export declare function integer(i: string): string | number;

75
node_modules/twilio/lib/base/deserialize.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.iso8601Date = iso8601Date;
exports.iso8601DateTime = iso8601DateTime;
exports.rfc2822DateTime = rfc2822DateTime;
exports.decimal = decimal;
exports.integer = integer;
const dayjs_1 = __importDefault(require("dayjs"));
const utc_1 = __importDefault(require("dayjs/plugin/utc"));
dayjs_1.default.extend(utc_1.default);
/**
* @namespace deserialize
*/
/**
* Parse a string into a Date object
*
* @param s - Date string in YYYY-MM-DD format
* @returns Date object, or the original date string if the argument is not a valid date
*/
function iso8601Date(s) {
return parseDate(s, "YYYY-MM-DD");
}
/**
* Parse a string into a Date object
*
* @param s - Date string in YYYY-MM-DD[T]HH:mm:ss[Z] format
* @returns Date object, or the original date string if the argument is not a valid date
*/
function iso8601DateTime(s) {
return parseDate(s, "YYYY-MM-DD[T]HH:mm:ss[Z]");
}
/**
* Parse a string into a Date object
*
* @param s - Date string in ddd, DD MMM YYYY HH:mm:ss [+0000] format
* @returns Date object, or the original date string if the argument is not a valid date
*/
function rfc2822DateTime(s) {
return parseDate(s, "ddd, DD MMM YYYY HH:mm:ss [+0000]");
}
/**
* Parse a string into a decimal
*
* @param d - Decimal value as string
* @returns Number, or the original string if the argument is NaN
*/
function decimal(d) {
return parseNumber(d, parseFloat);
}
/**
* Parse a string into a integer
*
* @param i - Integer value as string
* @returns Number, or the original string if the argument is NaN
*/
function integer(i) {
return parseNumber(i, parseInt);
}
function parseDate(s, format) {
var m = dayjs_1.default.utc(s, format);
if (m.isValid()) {
return m.toDate();
}
return s;
}
function parseNumber(n, parser) {
var parsed = parser(n);
if (typeof parsed === "number" && isNaN(parsed)) {
return n;
}
return parsed;
}

53
node_modules/twilio/lib/base/serialize.d.ts generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import TwiML from "../twiml/TwiML";
/**
* @namespace serialize
*/
/**
* Turns a Date object into a string if parameter is a Date otherwise returns the parameter
*
* @param d - date object to format
* @returns date formatted in YYYY-MM-DD form, otherwise the
* provided parameter.
*/
export declare function iso8601Date<T>(date: T | Date): T | string;
/**
* Turns a Date object into a string if parameter is a Date otherwise returns the parameter
*
* @param d - date object to format
* @returns date formatted in YYYY-MM-DD[T]HH:mm:ss[Z] form, otherwise the
* provided parameter.
*/
export declare function iso8601DateTime<T>(date: T | Date): T | string;
/**
* Turns a map of params int oa flattened map separated by dots if the parameter is an object, otherwise returns an empty map
*
* @param m - map to transform
* @param prefix - to append to each flattened value
* @returns flattened map
*/
export declare function prefixedCollapsibleMap<T extends {}>(m: T, prefix?: string): T;
/**
* Turns an object into a JSON string if the parameter is an object, otherwise returns the passed in object
*
* @param o - json object or array
* @returns stringified object
*/
export declare function object<T>(o: T): T;
/**
* Coerces a boolean literal into a string
*
* @param input - boolean or string to be coerced
* @returns a string 'true' or 'false' if passed a boolean, else the value
*/
export declare function bool(input: string | boolean): string | "true" | "false";
export declare function twiml(input: TwiML | string): string;
type MapFunction<TInput, TOutput> = (input: TInput) => TOutput;
/**
* Maps transform over each element in input if input is an array
*
* @param input - array to map transform over, if not an array then it is
* returned as is.
* @returns new array with transform applied to each element.
*/
export declare function map<TInput, TOutput>(input: Array<TInput>, transform: MapFunction<TInput, TOutput>): Array<TOutput>;
export {};

121
node_modules/twilio/lib/base/serialize.js generated vendored Normal file
View File

@@ -0,0 +1,121 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.iso8601Date = iso8601Date;
exports.iso8601DateTime = iso8601DateTime;
exports.prefixedCollapsibleMap = prefixedCollapsibleMap;
exports.object = object;
exports.bool = bool;
exports.twiml = twiml;
exports.map = map;
const dayjs_1 = __importDefault(require("dayjs"));
const utc_1 = __importDefault(require("dayjs/plugin/utc"));
dayjs_1.default.extend(utc_1.default);
/**
* @namespace serialize
*/
/**
* Turns a Date object into a string if parameter is a Date otherwise returns the parameter
*
* @param d - date object to format
* @returns date formatted in YYYY-MM-DD form, otherwise the
* provided parameter.
*/
function iso8601Date(date) {
if (!date || !(date instanceof Date)) {
return date;
}
else {
return dayjs_1.default.utc(date).format("YYYY-MM-DD");
}
}
/**
* Turns a Date object into a string if parameter is a Date otherwise returns the parameter
*
* @param d - date object to format
* @returns date formatted in YYYY-MM-DD[T]HH:mm:ss[Z] form, otherwise the
* provided parameter.
*/
function iso8601DateTime(date) {
if (!date || !(date instanceof Date)) {
return date;
}
else {
return dayjs_1.default.utc(date).format("YYYY-MM-DD[T]HH:mm:ss[Z]");
}
}
function prefixedCollapsibleMap(m, prefix) {
if (!m ||
typeof m !== "object" ||
Object.prototype.toString.call(m) !== "[object Object]") {
return {};
}
function flatten(m, result, previous) {
result = result || {};
previous = previous || [];
Object.keys(m).forEach((key) => {
const unionKeys = [...previous];
if (!unionKeys.includes(key)) {
unionKeys.push(key);
}
if (typeof m[key] === "object" &&
Object.prototype.toString.call(m[key]) === "[object Object]") {
flatten(m[key], result, unionKeys);
}
else {
result[unionKeys.join(".")] = m[key];
}
});
return result;
}
var flattened = flatten(m);
var result = flattened;
if (prefix) {
result = {};
Object.keys(flattened).forEach((key) => {
result[prefix + "." + key] = flattened[key];
});
}
return result;
}
function object(o) {
if (typeof o === "object") {
return JSON.stringify(o);
}
return o;
}
/**
* Coerces a boolean literal into a string
*
* @param input - boolean or string to be coerced
* @returns a string 'true' or 'false' if passed a boolean, else the value
*/
function bool(input) {
if (typeof input === "string") {
return input;
}
if (typeof input === "boolean" ||
(typeof input === "object" &&
Object.prototype.toString.call(input) === "[object Boolean]")) {
return input.toString();
}
return input;
}
function twiml(input) {
return input.toString();
}
/**
* Maps transform over each element in input if input is an array
*
* @param input - array to map transform over, if not an array then it is
* returned as is.
* @returns new array with transform applied to each element.
*/
function map(input, transform) {
if (typeof input === "object" && Array.isArray(input)) {
return input.map((element) => transform(element));
}
return input;
}

2
node_modules/twilio/lib/base/utility.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export declare const trim: (str: string, c?: string) => string;
export declare function isValidPathParam(param: any): boolean;

13
node_modules/twilio/lib/base/utility.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.trim = void 0;
exports.isValidPathParam = isValidPathParam;
const INVALID_PATH_PARAM_CHARS = ["/", "?"];
const trim = (str, c = "\\s") => str.replace(new RegExp(`^([${c}]*)(.*?)([${c}]*)$`), "$2");
exports.trim = trim;
function isValidPathParam(param) {
if (param === null || param === undefined)
return false;
const paramString = param.toString();
return INVALID_PATH_PARAM_CHARS.every((invalidChar) => !paramString.includes(invalidChar));
}

10
node_modules/twilio/lib/base/values.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/**
* @namespace values
*/
/**
* Removes all undefined values of an object
*
* @param obj - object to filter
* @returns object with no undefined values
*/
export declare function of(obj: Object): Object;

15
node_modules/twilio/lib/base/values.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
"use strict";
/**
* @namespace values
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.of = of;
/**
* Removes all undefined values of an object
*
* @param obj - object to filter
* @returns object with no undefined values
*/
function of(obj) {
return Object.fromEntries(Object.entries(obj).filter((entry) => entry[1] !== undefined));
}

View File

@@ -0,0 +1,22 @@
import CredentialProvider from "./CredentialProvider";
import TokenManager from "../http/bearer_token/TokenManager";
import AuthStrategy from "../auth_strategy/AuthStrategy";
declare class ClientCredentialProvider extends CredentialProvider {
grantType: string;
clientId: string;
clientSecret: string;
tokenManager: TokenManager | null;
constructor();
toAuthStrategy(): AuthStrategy;
}
declare namespace ClientCredentialProvider {
class ClientCredentialProviderBuilder {
private readonly instance;
constructor();
setClientId(clientId: string): ClientCredentialProviderBuilder;
setClientSecret(clientSecret: string): ClientCredentialProviderBuilder;
setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder;
build(): ClientCredentialProvider;
}
}
export = ClientCredentialProvider;

View File

@@ -0,0 +1,50 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const CredentialProvider_1 = __importDefault(require("./CredentialProvider"));
const ApiTokenManager_1 = __importDefault(require("../http/bearer_token/ApiTokenManager"));
const TokenAuthStrategy_1 = __importDefault(require("../auth_strategy/TokenAuthStrategy"));
class ClientCredentialProvider extends CredentialProvider_1.default {
constructor() {
super("client-credentials");
this.grantType = "client_credentials";
this.clientId = "";
this.clientSecret = "";
this.tokenManager = null;
}
toAuthStrategy() {
if (this.tokenManager == null) {
this.tokenManager = new ApiTokenManager_1.default({
grantType: this.grantType,
clientId: this.clientId,
clientSecret: this.clientSecret,
});
}
return new TokenAuthStrategy_1.default(this.tokenManager);
}
}
(function (ClientCredentialProvider) {
class ClientCredentialProviderBuilder {
constructor() {
this.instance = new ClientCredentialProvider();
}
setClientId(clientId) {
this.instance.clientId = clientId;
return this;
}
setClientSecret(clientSecret) {
this.instance.clientSecret = clientSecret;
return this;
}
setTokenManager(tokenManager) {
this.instance.tokenManager = tokenManager;
return this;
}
build() {
return this.instance;
}
}
ClientCredentialProvider.ClientCredentialProviderBuilder = ClientCredentialProviderBuilder;
})(ClientCredentialProvider || (ClientCredentialProvider = {}));
module.exports = ClientCredentialProvider;

View File

@@ -0,0 +1,7 @@
import AuthStrategy from "../auth_strategy/AuthStrategy";
export default abstract class CredentialProvider {
private authType;
protected constructor(authType: string);
getAuthType(): string;
abstract toAuthStrategy(): AuthStrategy;
}

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class CredentialProvider {
constructor(authType) {
this.authType = authType;
}
getAuthType() {
return this.authType;
}
}
exports.default = CredentialProvider;

View File

@@ -0,0 +1,9 @@
import CredentialProvider from "./CredentialProvider";
import AuthStrategy from "../auth_strategy/AuthStrategy";
declare namespace NoAuthCredentialProvider {
class NoAuthCredentialProvider extends CredentialProvider {
constructor();
toAuthStrategy(): AuthStrategy;
}
}
export = NoAuthCredentialProvider;

View File

@@ -0,0 +1,19 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const CredentialProvider_1 = __importDefault(require("./CredentialProvider"));
const NoAuthStrategy_1 = __importDefault(require("../auth_strategy/NoAuthStrategy"));
var NoAuthCredentialProvider;
(function (NoAuthCredentialProvider_1) {
class NoAuthCredentialProvider extends CredentialProvider_1.default {
constructor() {
super("noauth");
}
toAuthStrategy() {
return new NoAuthStrategy_1.default();
}
}
NoAuthCredentialProvider_1.NoAuthCredentialProvider = NoAuthCredentialProvider;
})(NoAuthCredentialProvider || (NoAuthCredentialProvider = {}));
module.exports = NoAuthCredentialProvider;

View File

@@ -0,0 +1,22 @@
import CredentialProvider from "./CredentialProvider";
import TokenManager from "../http/bearer_token/TokenManager";
import AuthStrategy from "../auth_strategy/AuthStrategy";
declare class OrgsCredentialProvider extends CredentialProvider {
grantType: string;
clientId: string;
clientSecret: string;
tokenManager: TokenManager | null;
constructor();
toAuthStrategy(): AuthStrategy;
}
declare namespace OrgsCredentialProvider {
class OrgsCredentialProviderBuilder {
private readonly instance;
constructor();
setClientId(clientId: string): OrgsCredentialProviderBuilder;
setClientSecret(clientSecret: string): OrgsCredentialProviderBuilder;
setTokenManager(tokenManager: TokenManager): OrgsCredentialProviderBuilder;
build(): OrgsCredentialProvider;
}
}
export = OrgsCredentialProvider;

View File

@@ -0,0 +1,50 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const CredentialProvider_1 = __importDefault(require("./CredentialProvider"));
const OrgsTokenManager_1 = __importDefault(require("../http/bearer_token/OrgsTokenManager"));
const TokenAuthStrategy_1 = __importDefault(require("../auth_strategy/TokenAuthStrategy"));
class OrgsCredentialProvider extends CredentialProvider_1.default {
constructor() {
super("client-credentials");
this.grantType = "client_credentials";
this.clientId = "";
this.clientSecret = "";
this.tokenManager = null;
}
toAuthStrategy() {
if (this.tokenManager == null) {
this.tokenManager = new OrgsTokenManager_1.default({
grantType: this.grantType,
clientId: this.clientId,
clientSecret: this.clientSecret,
});
}
return new TokenAuthStrategy_1.default(this.tokenManager);
}
}
(function (OrgsCredentialProvider) {
class OrgsCredentialProviderBuilder {
constructor() {
this.instance = new OrgsCredentialProvider();
}
setClientId(clientId) {
this.instance.clientId = clientId;
return this;
}
setClientSecret(clientSecret) {
this.instance.clientSecret = clientSecret;
return this;
}
setTokenManager(tokenManager) {
this.instance.tokenManager = tokenManager;
return this;
}
build() {
return this.instance;
}
}
OrgsCredentialProvider.OrgsCredentialProviderBuilder = OrgsCredentialProviderBuilder;
})(OrgsCredentialProvider || (OrgsCredentialProvider = {}));
module.exports = OrgsCredentialProvider;

View File

@@ -0,0 +1,8 @@
import TokenManager from "./TokenManager";
import { TokenListInstanceCreateOptions } from "../../rest/oauth/v2/token";
export default class ApiTokenManager implements TokenManager {
private params;
constructor(params: TokenListInstanceCreateOptions);
getParams(): TokenListInstanceCreateOptions;
fetchToken(): Promise<string>;
}

View File

@@ -0,0 +1,33 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const token_1 = require("../../rest/oauth/v2/token");
const OauthBase_1 = __importDefault(require("../../rest/OauthBase"));
const V2_1 = __importDefault(require("../../rest/oauth/V2"));
const NoAuthCredentialProvider_1 = __importDefault(require("../../credential_provider/NoAuthCredentialProvider"));
const BaseTwilio_1 = require("../../base/BaseTwilio");
class ApiTokenManager {
constructor(params) {
this.params = params;
}
getParams() {
return this.params;
}
async fetchToken() {
const noAuthCredentialProvider = new NoAuthCredentialProvider_1.default.NoAuthCredentialProvider();
const client = new BaseTwilio_1.Client();
client.setCredentialProvider(noAuthCredentialProvider);
const tokenListInstance = (0, token_1.TokenListInstance)(new V2_1.default(new OauthBase_1.default(client)));
return tokenListInstance
.create(this.params)
.then((token) => {
return token.accessToken;
})
.catch((error) => {
throw new Error(`Error Status Code: ${error.status}\nFailed to fetch access token: ${error.message}`);
});
}
}
exports.default = ApiTokenManager;

View File

@@ -0,0 +1,8 @@
import TokenManager from "./TokenManager";
import { TokenListInstanceCreateOptions } from "../../rest/oauth/v2/token";
export default class OrgsTokenManager implements TokenManager {
private readonly params;
constructor(params: TokenListInstanceCreateOptions);
getParams(): TokenListInstanceCreateOptions;
fetchToken(): Promise<string>;
}

View File

@@ -0,0 +1,33 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const token_1 = require("../../rest/oauth/v2/token");
const OauthBase_1 = __importDefault(require("../../rest/OauthBase"));
const V2_1 = __importDefault(require("../../rest/oauth/V2"));
const NoAuthCredentialProvider_1 = __importDefault(require("../../credential_provider/NoAuthCredentialProvider"));
const BaseTwilio_1 = require("../../base/BaseTwilio");
class OrgsTokenManager {
constructor(params) {
this.params = params;
}
getParams() {
return this.params;
}
async fetchToken() {
const noAuthCredentialProvider = new NoAuthCredentialProvider_1.default.NoAuthCredentialProvider();
const client = new BaseTwilio_1.Client();
client.setCredentialProvider(noAuthCredentialProvider);
const tokenListInstance = (0, token_1.TokenListInstance)(new V2_1.default(new OauthBase_1.default(client)));
return tokenListInstance
.create(this.params)
.then((token) => {
return token.accessToken;
})
.catch((error) => {
throw new Error(`Error Status Code: ${error.status}\nFailed to fetch access token: ${error.message}`);
});
}
}
exports.default = OrgsTokenManager;

View File

@@ -0,0 +1,3 @@
export default abstract class TokenManager {
abstract fetchToken(): Promise<string>;
}

View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TokenManager {
}
exports.default = TokenManager;

25
node_modules/twilio/lib/http/request.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import { HttpMethod } from "../interfaces";
export interface RequestOptions<TData> {
method?: HttpMethod | "*";
url?: string;
auth?: string;
params?: object | "*";
data?: TData | "*";
headers?: Headers;
}
export interface Headers {
[header: string]: string;
}
export default class Request<TData> {
method: HttpMethod | "*";
url: string;
auth: string;
params: object | "*";
data: TData | "*";
headers: Headers | "*";
constructor(opts?: RequestOptions<TData>);
get ANY(): "*";
attributeEqual(lhs: any, rhs: any): boolean;
isEqual(other: Request<any>): boolean;
toString(): string;
}

85
node_modules/twilio/lib/http/request.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Request {
constructor(opts) {
opts = opts || {};
this.method = opts.method || this.ANY;
this.url = opts.url || this.ANY;
this.auth = opts.auth || this.ANY;
this.params = opts.params || this.ANY;
this.data = opts.data || this.ANY;
this.headers = opts.headers || this.ANY;
}
get ANY() {
return "*";
}
attributeEqual(lhs, rhs) {
if (lhs === this.ANY || rhs === this.ANY) {
return true;
}
lhs = lhs || undefined;
rhs = rhs || undefined;
if (typeof lhs !== typeof rhs) {
return false;
}
if (typeof lhs !== "object") {
return lhs === rhs;
}
return (Object.entries(lhs)
.sort((a, b) => a[0].localeCompare(b[0]))
.toString() ===
Object.entries(rhs)
.sort((a, b) => a[0].localeCompare(b[0]))
.toString());
}
isEqual(other) {
return (this.attributeEqual(this.method, other.method) &&
this.attributeEqual(this.url, other.url) &&
this.attributeEqual(this.auth, other.auth) &&
this.attributeEqual(this.params, other.params) &&
this.attributeEqual(this.data, other.data) &&
this.attributeEqual(this.headers, other.headers));
}
toString() {
var auth = "";
if (this.auth && this.auth !== this.ANY) {
auth = this.auth + " ";
}
var params = "";
if (this.params && this.params !== this.ANY) {
params =
"?" +
Object.keys(this.params)
.map((key) => function () {
return key + "=" + this.params[key];
}.bind(this)())
.join("&");
}
var data = "";
if (this.data && this.data !== this.ANY) {
if (this.method === "get") {
data = "\n -G";
}
data =
data +
"\n" +
Object.entries(this.data)
.map((d) => {
return " -d " + d[0] + "=" + d[1];
})
.join("\n");
}
var headers = "";
if (this.headers && this.headers !== this.ANY) {
headers =
"\n" +
Object.entries(this.headers)
.map((header) => {
return " -H " + header[0] + "=" + header[1];
})
.join("\n");
}
return auth + this.method + " " + this.url + params + data + headers;
}
}
exports.default = Request;

7
node_modules/twilio/lib/http/response.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export default class Response<TPayload> {
statusCode: number;
body: TPayload;
headers: any;
constructor(statusCode: number, body: TPayload, headers: any);
toString(): string;
}

13
node_modules/twilio/lib/http/response.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Response {
constructor(statusCode, body, headers) {
this.statusCode = statusCode;
this.body = body;
this.headers = headers;
}
toString() {
return "HTTP " + this.statusCode + " " + this.body;
}
}
exports.default = Response;

72
node_modules/twilio/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,72 @@
import ITwilio from "./rest/Twilio";
import * as webhooks from "./webhooks/webhooks";
import IRequestClient from "./base/RequestClient";
import type { ClientOpts as IClientOpts } from "./base/BaseTwilio";
import IRestException from "./base/RestException";
import type { ApiResponse as IApiResponse } from "./base/ApiResponse";
import IAccessToken from "./jwt/AccessToken";
import IValidationToken from "./jwt/validation/ValidationToken";
import IClientCapability from "./jwt/ClientCapability";
import ITaskRouterCapability from "./jwt/taskrouter/TaskRouterCapability";
import * as taskRouterUtil from "./jwt/taskrouter/util";
import IVoiceResponse from "./twiml/VoiceResponse";
import IMessagingResponse from "./twiml/MessagingResponse";
import IFaxResponse from "./twiml/FaxResponse";
import IClientCredentialProvider from "./credential_provider/ClientCredentialProvider";
import INoAuthCredentialProvider from "./credential_provider/NoAuthCredentialProvider";
import IOrgsCredentialProvider from "./credential_provider/OrgsCredentialProvider";
declare function TwilioSDK(accountSid?: string, authToken?: string, opts?: IClientOpts): TwilioSDK.Twilio;
declare namespace TwilioSDK {
type Twilio = ITwilio;
const Twilio: typeof ITwilio;
namespace jwt {
type AccessToken = IAccessToken;
const AccessToken: typeof IAccessToken;
type ValidationToken = IValidationToken;
const ValidationToken: typeof IValidationToken;
type ClientCapability = IClientCapability;
const ClientCapability: typeof IClientCapability;
namespace taskrouter {
type TaskRouterCapability = ITaskRouterCapability;
const TaskRouterCapability: typeof ITaskRouterCapability;
const util: typeof taskRouterUtil;
}
}
namespace twiml {
type VoiceResponse = IVoiceResponse;
const VoiceResponse: typeof IVoiceResponse;
type MessagingResponse = IMessagingResponse;
const MessagingResponse: typeof IMessagingResponse;
type FaxResponse = IFaxResponse;
const FaxResponse: typeof IFaxResponse;
}
type RequestClient = IRequestClient;
const RequestClient: typeof IRequestClient;
type RestException = IRestException;
const RestException: typeof IRestException;
type ApiResponse<T> = IApiResponse<T>;
type ClientCredentialProviderBuilder = IClientCredentialProvider.ClientCredentialProviderBuilder;
const ClientCredentialProviderBuilder: typeof IClientCredentialProvider.ClientCredentialProviderBuilder;
type OrgsCredentialProviderBuilder = IOrgsCredentialProvider.OrgsCredentialProviderBuilder;
const OrgsCredentialProviderBuilder: typeof IOrgsCredentialProvider.OrgsCredentialProviderBuilder;
type NoAuthCredentialProvider = INoAuthCredentialProvider.NoAuthCredentialProvider;
const NoAuthCredentialProvider: typeof INoAuthCredentialProvider.NoAuthCredentialProvider;
type validateBody = typeof webhooks.validateBody;
const validateBody: typeof webhooks.validateBody;
type validateRequest = typeof webhooks.validateRequest;
const validateRequest: typeof webhooks.validateRequest;
type validateRequestWithBody = typeof webhooks.validateRequestWithBody;
const validateRequestWithBody: typeof webhooks.validateRequestWithBody;
type validateExpressRequest = typeof webhooks.validateExpressRequest;
const validateExpressRequest: typeof webhooks.validateExpressRequest;
type validateIncomingRequest = typeof webhooks.validateIncomingRequest;
const validateIncomingRequest: typeof webhooks.validateIncomingRequest;
type getExpectedBodyHash = typeof webhooks.getExpectedBodyHash;
const getExpectedBodyHash: typeof webhooks.getExpectedBodyHash;
type getExpectedTwilioSignature = typeof webhooks.getExpectedTwilioSignature;
const getExpectedTwilioSignature: typeof webhooks.getExpectedTwilioSignature;
type webhook = typeof webhooks.webhook;
const webhook: typeof webhooks.webhook;
type ClientOpts = IClientOpts;
}
export = TwilioSDK;

90
node_modules/twilio/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,90 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Twilio_1 = __importDefault(require("./rest/Twilio"));
const webhooks = __importStar(require("./webhooks/webhooks"));
const RequestClient_1 = __importDefault(require("./base/RequestClient"));
const RestException_1 = __importDefault(require("./base/RestException"));
const AccessToken_1 = __importDefault(require("./jwt/AccessToken"));
const ValidationToken_1 = __importDefault(require("./jwt/validation/ValidationToken"));
const ClientCapability_1 = __importDefault(require("./jwt/ClientCapability"));
const TaskRouterCapability_1 = __importDefault(require("./jwt/taskrouter/TaskRouterCapability"));
const taskRouterUtil = __importStar(require("./jwt/taskrouter/util"));
const VoiceResponse_1 = __importDefault(require("./twiml/VoiceResponse"));
const MessagingResponse_1 = __importDefault(require("./twiml/MessagingResponse"));
const FaxResponse_1 = __importDefault(require("./twiml/FaxResponse"));
const ClientCredentialProvider_1 = __importDefault(require("./credential_provider/ClientCredentialProvider"));
const NoAuthCredentialProvider_1 = __importDefault(require("./credential_provider/NoAuthCredentialProvider"));
const OrgsCredentialProvider_1 = __importDefault(require("./credential_provider/OrgsCredentialProvider"));
// Shorthand to automatically create a RestClient
function TwilioSDK(accountSid, authToken, opts) {
return new TwilioSDK.Twilio(accountSid, authToken, opts);
}
(function (TwilioSDK) {
TwilioSDK.Twilio = Twilio_1.default;
let jwt;
(function (jwt) {
jwt.AccessToken = AccessToken_1.default;
jwt.ValidationToken = ValidationToken_1.default;
jwt.ClientCapability = ClientCapability_1.default;
let taskrouter;
(function (taskrouter) {
taskrouter.TaskRouterCapability = TaskRouterCapability_1.default;
taskrouter.util = taskRouterUtil;
})(taskrouter = jwt.taskrouter || (jwt.taskrouter = {}));
})(jwt = TwilioSDK.jwt || (TwilioSDK.jwt = {}));
let twiml;
(function (twiml) {
twiml.VoiceResponse = VoiceResponse_1.default;
twiml.MessagingResponse = MessagingResponse_1.default;
twiml.FaxResponse = FaxResponse_1.default;
})(twiml = TwilioSDK.twiml || (TwilioSDK.twiml = {}));
TwilioSDK.RequestClient = RequestClient_1.default;
TwilioSDK.RestException = RestException_1.default;
TwilioSDK.ClientCredentialProviderBuilder = ClientCredentialProvider_1.default.ClientCredentialProviderBuilder;
TwilioSDK.OrgsCredentialProviderBuilder = OrgsCredentialProvider_1.default.OrgsCredentialProviderBuilder;
TwilioSDK.NoAuthCredentialProvider = NoAuthCredentialProvider_1.default.NoAuthCredentialProvider;
TwilioSDK.validateBody = webhooks.validateBody;
TwilioSDK.validateRequest = webhooks.validateRequest;
TwilioSDK.validateRequestWithBody = webhooks.validateRequestWithBody;
TwilioSDK.validateExpressRequest = webhooks.validateExpressRequest;
TwilioSDK.validateIncomingRequest = webhooks.validateIncomingRequest;
TwilioSDK.getExpectedBodyHash = webhooks.getExpectedBodyHash;
TwilioSDK.getExpectedTwilioSignature = webhooks.getExpectedTwilioSignature;
TwilioSDK.webhook = webhooks.webhook;
})(TwilioSDK || (TwilioSDK = {}));
module.exports = TwilioSDK;

94
node_modules/twilio/lib/interfaces.d.ts generated vendored Normal file
View File

@@ -0,0 +1,94 @@
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
export type Url = string;
export type PhoneNumber = string;
export type PhoneNumberCapabilities = {
mms: boolean;
sms: boolean;
voice: boolean;
fax: boolean;
};
export type Sid = string;
export interface ListEachOptions<TInstance> {
/**
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
*/
limit?: number;
/**
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
*/
pageSize?: number;
/**
* Function to process each record. If this and a positional
* callback are passed, this one will be used
*/
callback?: (item: TInstance, done: (err?: Error) => void) => void;
/**
* Function to be called upon completion of streaming
*/
done?: (err?: Error) => void;
}
export interface ListOptions<TInstance> {
/**
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
*/
limit?: number;
/**
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
*/
pageSize?: number;
/**
* Callback to handle list of records
*/
callback?: (items: TInstance[]) => void;
}
export interface PageOptions<TPage> {
/**
* PageToken provided by the API
*/
pageToken?: string;
/**
* Page Number, this value is simply for client state
*/
pageNumber?: number;
/**
* Number of records to return, defaults to 50
*/
pageSize?: number;
/**
* Callback to handle list of records
*/
callback?: (page: TPage) => void;
}
/**
* A generic type that returns all property names of a class whose type is not "function"
*/
export type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];
/**
* A generic type that returns only properties of a class that are not functions
*/
export type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
/**
* A type alias for better readibility
*/
export type Json<T> = NonFunctionProperties<T>;
export declare class SerializableClass {
/**
* Converts the current instance in a regular JSON.
* It will be automatically called by JSON.stringify()
*/
toJSON(): Json<this>;
}

2
node_modules/twilio/lib/interfaces.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

186
node_modules/twilio/lib/jwt/AccessToken.d.ts generated vendored Normal file
View File

@@ -0,0 +1,186 @@
declare class AccessToken implements AccessToken.AccessTokenOptions {
static DEFAULT_ALGORITHM: "HS256";
static ALGORITHMS: string[];
accountSid: string;
keySid: string;
secret: string;
ttl: number;
identity: string;
nbf?: number;
region?: string;
grants: AccessToken.Grant<any, any, any>[];
/**
* @param accountSid - The account's unique ID to which access is scoped
* @param keySid - The signing key's unique ID
* @param secret - The secret to sign the token with
* @param options - ...
* @param options.ttl - Time to live in seconds (default 3600)
* @param options.identity - The identity of the first person. Required.
* @param options.nbf - Time from epoch in seconds for not before value
* @param options.region - The region value associated with this account
*/
constructor(accountSid: string, keySid: string, secret: string, options: AccessToken.AccessTokenOptions);
addGrant<T extends AccessToken.Grant<any, any, any>>(grant: T): void;
toJwt(algorithm?: "HS256" | "HS384" | "HS512"): string;
}
declare namespace AccessToken {
abstract class Grant<TOptions, TPayload, TKey> {
key: TKey;
protected constructor(key: TKey);
abstract toPayload(): TPayload;
}
interface TaskRouterGrantOptions {
workspaceSid?: string;
workerSid?: string;
role?: string;
}
interface TaskRouterGrantPayload {
workspace_sid?: string;
worker_sid?: string;
role?: string;
}
interface ChatGrantOptions {
serviceSid?: string;
endpointId?: string;
deploymentRoleSid?: string;
pushCredentialSid?: string;
}
interface ChatGrantPayload {
service_sid?: string;
endpoint_id?: string;
deployment_role_sid?: string;
push_credential_sid?: string;
}
interface VideoGrantOptions {
room?: string;
}
interface VideoGrantPayload {
room?: string;
}
interface SyncGrantOptions {
serviceSid?: string;
endpointId?: string;
}
interface SyncGrantPayload {
service_sid?: string;
endpoint_id?: string;
}
interface VoiceGrantOptions {
incomingAllow?: boolean;
outgoingApplicationSid?: string;
outgoingApplicationParams?: object;
pushCredentialSid?: string;
endpointId?: string;
}
interface VoiceGrantPayload {
incoming?: {
allow: boolean;
};
outgoing?: {
application_sid: string;
params?: object;
};
push_credential_sid?: string;
endpoint_id?: string;
}
interface PlaybackGrantOptions {
grant?: object;
}
interface PlaybackGrantPayload {
grant?: object;
}
interface AccessTokenOptions {
/**
* Time to live in seconds
*/
ttl?: number;
/**
* The identity of the first person. Required.
*/
identity: string;
/**
* Time from epoch in seconds for not before value
*/
nbf?: number;
/**
* The region value associated with this account
*/
region?: string;
}
class TaskRouterGrant extends Grant<TaskRouterGrantOptions, TaskRouterGrantPayload, "task_router"> implements TaskRouterGrantOptions {
workspaceSid?: string;
workerSid?: string;
role?: string;
/**
* @param options - ...
* @param options.workspaceSid - The workspace unique ID
* @param options.workerSid - The worker unique ID
* @param options.role - The role of the grant
*/
constructor(options?: TaskRouterGrantOptions);
toPayload(): TaskRouterGrantPayload;
}
class ChatGrant extends Grant<ChatGrantOptions, ChatGrantPayload, "chat"> implements ChatGrantOptions {
serviceSid?: string;
endpointId?: string;
deploymentRoleSid?: string;
pushCredentialSid?: string;
/**
* @param options - ...
* @param options.serviceSid - The service unique ID
* @param options.endpointId - The endpoint ID
* @param options.deploymentRoleSid - SID of the deployment role to be
* assigned to the user
* @param options.pushCredentialSid - The Push Credentials SID
*/
constructor(options?: ChatGrantOptions);
toPayload(): ChatGrantPayload;
}
class VideoGrant extends Grant<VideoGrantOptions, VideoGrantPayload, "video"> implements VideoGrantOptions {
room?: string;
/**
* @param options - ...
* @param options.room - The Room name or Room sid.
*/
constructor(options?: VideoGrantOptions);
toPayload(): VideoGrantPayload;
}
class SyncGrant extends Grant<SyncGrantOptions, SyncGrantPayload, "data_sync"> implements SyncGrantOptions {
serviceSid?: string;
endpointId?: string;
/**
* @param options.serviceSid - The service unique ID
* @param options.endpointId - The endpoint ID
*/
constructor(options?: SyncGrantOptions);
toPayload(): SyncGrantPayload;
}
class VoiceGrant extends Grant<VoiceGrantOptions, VoiceGrantPayload, "voice"> implements VoiceGrantOptions {
incomingAllow?: boolean;
outgoingApplicationSid?: string;
outgoingApplicationParams?: object;
pushCredentialSid?: string;
endpointId?: string;
/**
* @param options - ...
* @param options.incomingAllow - Whether or not this endpoint is allowed to receive incoming calls as grants.identity
* @param options.outgoingApplicationSid - application sid to call when placing outgoing call
* @param options.outgoingApplicationParams - request params to pass to the application
* @param options.pushCredentialSid - Push Credential Sid to use when registering to receive incoming call notifications
* @param options.endpointId - Specify an endpoint identifier for this device, which will allow the developer
* to direct calls to a specific endpoint when multiple devices are associated with a single identity
*/
constructor(options?: VoiceGrantOptions);
toPayload(): VoiceGrantPayload;
}
class PlaybackGrant extends Grant<PlaybackGrantOptions, PlaybackGrantPayload, "player"> implements PlaybackGrantOptions {
grant?: object;
/**
* @param options - ...
* @param options.grant - The PlaybackGrant retrieved from Twilio's API
*/
constructor(options?: PlaybackGrantOptions);
toPayload(): PlaybackGrantPayload;
}
}
export = AccessToken;

256
node_modules/twilio/lib/jwt/AccessToken.js generated vendored Normal file
View File

@@ -0,0 +1,256 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
class AccessToken {
/**
* @param accountSid - The account's unique ID to which access is scoped
* @param keySid - The signing key's unique ID
* @param secret - The secret to sign the token with
* @param options - ...
* @param options.ttl - Time to live in seconds (default 3600)
* @param options.identity - The identity of the first person. Required.
* @param options.nbf - Time from epoch in seconds for not before value
* @param options.region - The region value associated with this account
*/
constructor(accountSid, keySid, secret, options) {
if (!accountSid) {
throw new Error("accountSid is required");
}
if (!keySid) {
throw new Error("keySid is required");
}
if (!secret) {
throw new Error("secret is required");
}
if (!options || !options.identity) {
throw new Error("identity is required to be specified in options");
}
this.accountSid = accountSid;
this.keySid = keySid;
this.secret = secret;
this.ttl = options.ttl || 3600;
this.identity = options.identity;
this.nbf = options.nbf;
this.region = options.region;
this.grants = [];
}
addGrant(grant) {
this.grants.push(grant);
}
toJwt(algorithm) {
algorithm = algorithm || AccessToken.DEFAULT_ALGORITHM;
if (!AccessToken.ALGORITHMS.includes(algorithm)) {
throw new Error("Algorithm not supported. Allowed values are " +
AccessToken.ALGORITHMS.join(", "));
}
let grants = {};
if (Number.isInteger(this.identity) || typeof this.identity === "string") {
grants.identity = String(this.identity);
}
for (const grant of this.grants) {
grants[grant.key] = grant.toPayload();
}
const now = Math.floor(Date.now() / 1000);
let payload = {
jti: this.keySid + "-" + now,
grants: grants,
};
if (typeof this.nbf === "number") {
payload.nbf = this.nbf;
}
let header = {
cty: "twilio-fpa;v=1",
typ: "JWT",
};
if (this.region && typeof this.region === "string") {
header.twr = this.region;
}
return jsonwebtoken_1.default.sign(payload, this.secret, {
header: header,
algorithm: algorithm,
issuer: this.keySid,
subject: this.accountSid,
expiresIn: this.ttl,
});
}
}
AccessToken.DEFAULT_ALGORITHM = "HS256";
AccessToken.ALGORITHMS = ["HS256", "HS384", "HS512"];
(function (AccessToken) {
class Grant {
constructor(key) {
this.key = key;
}
}
AccessToken.Grant = Grant;
class TaskRouterGrant extends Grant {
/**
* @param options - ...
* @param options.workspaceSid - The workspace unique ID
* @param options.workerSid - The worker unique ID
* @param options.role - The role of the grant
*/
constructor(options) {
options = options || {};
super("task_router");
this.workspaceSid = options.workspaceSid;
this.workerSid = options.workerSid;
this.role = options.role;
}
toPayload() {
let grant = {};
if (this.workspaceSid) {
grant.workspace_sid = this.workspaceSid;
}
if (this.workerSid) {
grant.worker_sid = this.workerSid;
}
if (this.role) {
grant.role = this.role;
}
return grant;
}
}
AccessToken.TaskRouterGrant = TaskRouterGrant;
class ChatGrant extends Grant {
/**
* @param options - ...
* @param options.serviceSid - The service unique ID
* @param options.endpointId - The endpoint ID
* @param options.deploymentRoleSid - SID of the deployment role to be
* assigned to the user
* @param options.pushCredentialSid - The Push Credentials SID
*/
constructor(options) {
options = options || {};
super("chat");
this.serviceSid = options.serviceSid;
this.endpointId = options.endpointId;
this.deploymentRoleSid = options.deploymentRoleSid;
this.pushCredentialSid = options.pushCredentialSid;
}
toPayload() {
let grant = {};
if (this.serviceSid) {
grant.service_sid = this.serviceSid;
}
if (this.endpointId) {
grant.endpoint_id = this.endpointId;
}
if (this.deploymentRoleSid) {
grant.deployment_role_sid = this.deploymentRoleSid;
}
if (this.pushCredentialSid) {
grant.push_credential_sid = this.pushCredentialSid;
}
return grant;
}
}
AccessToken.ChatGrant = ChatGrant;
class VideoGrant extends Grant {
/**
* @param options - ...
* @param options.room - The Room name or Room sid.
*/
constructor(options) {
options = options || {};
super("video");
this.room = options.room;
}
toPayload() {
let grant = {};
if (this.room) {
grant.room = this.room;
}
return grant;
}
}
AccessToken.VideoGrant = VideoGrant;
class SyncGrant extends Grant {
/**
* @param options.serviceSid - The service unique ID
* @param options.endpointId - The endpoint ID
*/
constructor(options) {
options = options || {};
super("data_sync");
this.serviceSid = options.serviceSid;
this.endpointId = options.endpointId;
}
toPayload() {
let grant = {};
if (this.serviceSid) {
grant.service_sid = this.serviceSid;
}
if (this.endpointId) {
grant.endpoint_id = this.endpointId;
}
return grant;
}
}
AccessToken.SyncGrant = SyncGrant;
class VoiceGrant extends Grant {
/**
* @param options - ...
* @param options.incomingAllow - Whether or not this endpoint is allowed to receive incoming calls as grants.identity
* @param options.outgoingApplicationSid - application sid to call when placing outgoing call
* @param options.outgoingApplicationParams - request params to pass to the application
* @param options.pushCredentialSid - Push Credential Sid to use when registering to receive incoming call notifications
* @param options.endpointId - Specify an endpoint identifier for this device, which will allow the developer
* to direct calls to a specific endpoint when multiple devices are associated with a single identity
*/
constructor(options) {
options = options || {};
super("voice");
this.incomingAllow = options.incomingAllow;
this.outgoingApplicationSid = options.outgoingApplicationSid;
this.outgoingApplicationParams = options.outgoingApplicationParams;
this.pushCredentialSid = options.pushCredentialSid;
this.endpointId = options.endpointId;
}
toPayload() {
let grant = {};
if (this.incomingAllow === true) {
grant.incoming = { allow: true };
}
if (this.outgoingApplicationSid) {
grant.outgoing = {
application_sid: this.outgoingApplicationSid,
};
if (this.outgoingApplicationParams) {
grant.outgoing.params = this.outgoingApplicationParams;
}
}
if (this.pushCredentialSid) {
grant.push_credential_sid = this.pushCredentialSid;
}
if (this.endpointId) {
grant.endpoint_id = this.endpointId;
}
return grant;
}
}
AccessToken.VoiceGrant = VoiceGrant;
class PlaybackGrant extends Grant {
/**
* @param options - ...
* @param options.grant - The PlaybackGrant retrieved from Twilio's API
*/
constructor(options) {
options = options || {};
super("player");
this.grant = options.grant;
}
toPayload() {
let grant = {};
if (this.grant) {
grant = this.grant;
}
return grant;
}
}
AccessToken.PlaybackGrant = PlaybackGrant;
})(AccessToken || (AccessToken = {}));
module.exports = AccessToken;

61
node_modules/twilio/lib/jwt/ClientCapability.d.ts generated vendored Normal file
View File

@@ -0,0 +1,61 @@
export interface Scope {
scope: string;
payload(): string;
}
export interface OutgoingClientScopeOptions {
applicationSid: string;
clientName?: string;
params?: object;
}
export interface ClientCapabilityOptions {
accountSid: string;
authToken: string;
ttl?: number;
}
/**
* @param filters
*/
export declare class EventStreamScope implements Scope {
scope: string;
filters: object;
constructor(filters?: object);
payload(): string;
}
/**
* @param clientName
*/
export declare class IncomingClientScope implements Scope {
scope: string;
clientName: string;
constructor(clientName: string);
payload(): string;
}
export declare class OutgoingClientScope implements Scope {
scope: string;
applicationSid: string;
clientName?: string;
params?: object;
/**
* @param options - ...
* @param options.applicationSid - the application sid
* @param options.clientName - the client name
* @param options.params - parameters
*/
constructor(options: OutgoingClientScopeOptions);
payload(): string;
}
/**
* @param options
*/
export default class ClientCapability {
static EventStreamScope: typeof EventStreamScope;
static IncomingClientScope: typeof IncomingClientScope;
static OutgoingClientScope: typeof OutgoingClientScope;
accountSid: string;
authToken: string;
ttl: number;
scopes: Scope[];
constructor(options: ClientCapabilityOptions);
addScope(scope: Scope): void;
toJwt(): string;
}

122
node_modules/twilio/lib/jwt/ClientCapability.js generated vendored Normal file
View File

@@ -0,0 +1,122 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutgoingClientScope = exports.IncomingClientScope = exports.EventStreamScope = void 0;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const querystring_1 = __importDefault(require("querystring"));
/**
* @param filters
*/
class EventStreamScope {
constructor(filters) {
this.scope = "scope:stream:subscribe";
this.filters = filters || {};
}
payload() {
var queryArgs = ["path=/2010-04-01/Events"];
if (Object.keys(this.filters).length > 0) {
var queryParams = Object.entries(this.filters).map((filter) => {
return [querystring_1.default.escape(filter[0]), querystring_1.default.escape(filter[1])].join("=");
});
var filterParams = queryParams.join("&");
queryArgs.push(["appParams", querystring_1.default.escape(filterParams)].join("="));
}
var queryString = queryArgs.join("&");
return [this.scope, queryString].join("?");
}
}
exports.EventStreamScope = EventStreamScope;
/**
* @param clientName
*/
class IncomingClientScope {
constructor(clientName) {
this.scope = "scope:client:incoming";
this.clientName = clientName;
}
payload() {
var query = ["clientName", querystring_1.default.escape(this.clientName)].join("=");
return [this.scope, query].join("?");
}
}
exports.IncomingClientScope = IncomingClientScope;
class OutgoingClientScope {
/**
* @param options - ...
* @param options.applicationSid - the application sid
* @param options.clientName - the client name
* @param options.params - parameters
*/
constructor(options) {
this.scope = "scope:client:outgoing";
if (!options) {
throw new Error('Required parameter "options" missing.');
}
if (typeof options !== "object") {
throw new TypeError('Parameter "options" must be a type Object');
}
if (!options.applicationSid) {
throw new Error('Required parameter "options.applicationSid" missing.');
}
this.applicationSid = options.applicationSid;
this.clientName = options.clientName;
this.params = options.params;
}
payload() {
var queryArgs = [["appSid", querystring_1.default.escape(this.applicationSid)].join("=")];
if (typeof this.clientName === "string") {
queryArgs.push(["clientName", querystring_1.default.escape(this.clientName)].join("="));
}
if (typeof this.params === "object") {
var queryParams = Object.entries(this.params).map((param) => {
return [querystring_1.default.escape(param[0]), querystring_1.default.escape(param[1])].join("=");
});
var filterParams = queryParams.join("&");
queryArgs.push(["appParams", querystring_1.default.escape(filterParams)].join("="));
}
var queryString = queryArgs.join("&");
return [this.scope, queryString].join("?");
}
}
exports.OutgoingClientScope = OutgoingClientScope;
/**
* @param options
*/
class ClientCapability {
constructor(options) {
if (!options) {
throw new Error('Required parameter "options" missing.');
}
if (typeof options !== "object") {
throw new TypeError('Parameter "options" must be a type Object');
}
if (!options.accountSid) {
throw new Error('Required parameter "options.accountSid" missing.');
}
if (!options.authToken) {
throw new Error('Required parameter "options.authToken" missing.');
}
this.accountSid = options.accountSid;
this.authToken = options.authToken;
this.ttl = options.ttl || 3600;
this.scopes = [];
}
addScope(scope) {
this.scopes.push(scope);
}
toJwt() {
const scope = this.scopes.map((scope) => scope.payload()).join(" ");
var payload = {
scope: scope,
iss: this.accountSid,
exp: Math.floor(new Date().valueOf() / 1000) + this.ttl,
};
return jsonwebtoken_1.default.sign(payload, this.authToken);
}
}
ClientCapability.EventStreamScope = EventStreamScope;
ClientCapability.IncomingClientScope = IncomingClientScope;
ClientCapability.OutgoingClientScope = OutgoingClientScope;
exports.default = ClientCapability;

View File

@@ -0,0 +1,74 @@
export interface TaskRouterCapabilityOptions {
accountSid: string;
authToken: string;
workspaceSid: string;
channelId: string;
friendlyName?: string;
ttl?: number;
version?: string;
}
export interface PolicyOptions {
/** Policy URL */
url?: string;
/** HTTP Method */
method?: string;
/** Request query filter allowances */
queryFilter?: object;
/** Request post filter allowances */
postFilter?: object;
/** Allow the policy */
allow?: boolean;
}
export interface PolicyPayload {
url: string;
method: string;
query_filter: object;
post_filter: object;
allow: boolean;
}
/**
* Create a new Policy
*/
export declare class Policy {
url: string;
method: string;
queryFilter: object;
postFilter: object;
allow: boolean;
/**
* Create a new Policy instance
*
* @param options - ...
* @param options.url - Policy URL
* @param options.method - HTTP Method
* @param options.queryFilter - Request query filter allowances
* @param options.postFilter - Request post filter allowances
* @param options.allowed - Allow the policy
*/
constructor(options?: PolicyOptions);
payload(): PolicyPayload;
}
export default class TaskRouterCapability {
accountSid: string;
authToken: string;
workspaceSid: string;
channelId: string;
ttl: number;
version: string;
policies: Policy[];
friendlyName?: string;
/**
* @param options - ...
* @param options.accountSid - account sid
* @param options.authToken - auth token
* @param options.workspaceSid - workspace sid
* @param options.channelId - taskrouter channel id
* @param options.friendlyName - friendly name for the jwt
* @param options.ttl - time to live
* @param options.version - taskrouter version
*/
constructor(options: TaskRouterCapabilityOptions);
static Policy: typeof Policy;
addPolicy(policy: Policy): void;
toJwt(): string;
}

View File

@@ -0,0 +1,101 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Policy = void 0;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
/**
* Create a new Policy
*/
class Policy {
/**
* Create a new Policy instance
*
* @param options - ...
* @param options.url - Policy URL
* @param options.method - HTTP Method
* @param options.queryFilter - Request query filter allowances
* @param options.postFilter - Request post filter allowances
* @param options.allowed - Allow the policy
*/
constructor(options) {
options = options || {};
this.url = options.url || "";
this.method = options.method || "GET";
this.queryFilter = options.queryFilter || {};
this.postFilter = options.postFilter || {};
this.allow = options.allow || true;
}
payload() {
return {
url: this.url,
method: this.method,
query_filter: this.queryFilter,
post_filter: this.postFilter,
allow: this.allow,
};
}
}
exports.Policy = Policy;
class TaskRouterCapability {
/**
* @param options - ...
* @param options.accountSid - account sid
* @param options.authToken - auth token
* @param options.workspaceSid - workspace sid
* @param options.channelId - taskrouter channel id
* @param options.friendlyName - friendly name for the jwt
* @param options.ttl - time to live
* @param options.version - taskrouter version
*/
constructor(options) {
if (!options) {
throw new Error('Required parameter "options" missing.');
}
if (!options.accountSid) {
throw new Error('Required parameter "options.accountSid" missing.');
}
if (!options.authToken) {
throw new Error('Required parameter "options.authToken" missing.');
}
if (!options.workspaceSid) {
throw new Error('Required parameter "options.workspaceSid" missing.');
}
if (!options.channelId) {
throw new Error('Required parameter "options.channelId" missing.');
}
this.accountSid = options.accountSid;
this.authToken = options.authToken;
this.workspaceSid = options.workspaceSid;
this.channelId = options.channelId;
this.friendlyName = options.friendlyName;
this.ttl = options.ttl || 3600;
this.version = options.version || "v1";
this.policies = [];
}
addPolicy(policy) {
this.policies.push(policy);
}
toJwt() {
var payload = {
iss: this.accountSid,
exp: Math.floor(new Date().valueOf() / 1000) + this.ttl,
version: this.version,
friendly_name: this.friendlyName,
account_sid: this.accountSid,
channel: this.channelId,
workspace_sid: this.workspaceSid,
policies: this.policies.map((policy) => policy.payload()),
};
if (this.channelId.startsWith("WK")) {
payload.worker_sid = this.channelId;
}
else if (this.channelId.startsWith("WQ")) {
payload.taskqueue_sid = this.channelId;
}
return jsonwebtoken_1.default.sign(payload, this.authToken);
}
}
TaskRouterCapability.Policy = Policy;
exports.default = TaskRouterCapability;

66
node_modules/twilio/lib/jwt/taskrouter/util.d.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import { Policy } from "./TaskRouterCapability";
/**
* Build the default Policies for a worker
*
* @param version - TaskRouter version
* @param workspaceSid - workspace sid
* @param workerSid - worker sid
* @returns list of Policies
*/
export declare function defaultWorkerPolicies(version: string, workspaceSid: string, workerSid: string): Policy[];
/**
* Build the default Event Bridge Policies
*
* @param accountSid - account sid
* @param channelId - channel id
* @returns list of Policies
*/
export declare function defaultEventBridgePolicies(accountSid: string, channelId: string): Policy[];
/**
* Generate TaskRouter workspace url
*
* @param workspaceSid - workspace sid or '**' for all workspaces
* @returns generated url
*/
export declare function workspacesUrl(workspaceSid?: string): string;
/**
* Generate TaskRouter task queue url
*
* @param workspaceSid - workspace sid
* @param taskQueueSid - task queue sid or '**' for all task queues
* @returns generated url
*/
export declare function taskQueuesUrl(workspaceSid: string, taskQueueSid?: string): string;
/**
* Generate TaskRouter task url
*
* @param workspaceSid - workspace sid
* @param taskSid - task sid or '**' for all tasks
* @returns generated url
*/
export declare function tasksUrl(workspaceSid: string, taskSid?: string): string;
/**
* Generate TaskRouter activity url
*
* @param workspaceSid - workspace sid
* @param activitySid - activity sid or '**' for all activities
* @returns generated url
*/
export declare function activitiesUrl(workspaceSid: string, activitySid?: string): string;
/**
* Generate TaskRouter worker url
*
* @param workspaceSid - workspace sid
* @param workerSid - worker sid or '**' for all workers
* @returns generated url
*/
export declare function workersUrl(workspaceSid: string, workerSid?: string): string;
/**
* Generate TaskRouter worker reservation url
*
* @param workspaceSid - workspace sid
* @param workerSid - worker sid
* @param reservationSid - reservation sid or '**' for all reservations
* @returns generated url
*/
export declare function reservationsUrl(workspaceSid: string, workerSid: string, reservationSid?: string): string;

168
node_modules/twilio/lib/jwt/taskrouter/util.js generated vendored Normal file
View File

@@ -0,0 +1,168 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultWorkerPolicies = defaultWorkerPolicies;
exports.defaultEventBridgePolicies = defaultEventBridgePolicies;
exports.workspacesUrl = workspacesUrl;
exports.taskQueuesUrl = taskQueuesUrl;
exports.tasksUrl = tasksUrl;
exports.activitiesUrl = activitiesUrl;
exports.workersUrl = workersUrl;
exports.reservationsUrl = reservationsUrl;
const TaskRouterCapability_1 = require("./TaskRouterCapability");
const EVENT_URL_BASE = "https://event-bridge.twilio.com/v1/wschannels";
const TASKROUTER_BASE_URL = "https://taskrouter.twilio.com";
const TASKROUTER_VERSION = "v1";
/**
* Build the default Policies for a worker
*
* @param version - TaskRouter version
* @param workspaceSid - workspace sid
* @param workerSid - worker sid
* @returns list of Policies
*/
function defaultWorkerPolicies(version, workspaceSid, workerSid) {
var activities = new TaskRouterCapability_1.Policy({
url: [
TASKROUTER_BASE_URL,
version,
"Workspaces",
workspaceSid,
"Activities",
].join("/"),
method: "GET",
allow: true,
});
var tasks = new TaskRouterCapability_1.Policy({
url: [
TASKROUTER_BASE_URL,
version,
"Workspaces",
workspaceSid,
"Tasks",
"**",
].join("/"),
method: "GET",
allow: true,
});
var reservations = new TaskRouterCapability_1.Policy({
url: [
TASKROUTER_BASE_URL,
version,
"Workspaces",
workspaceSid,
"Workers",
workerSid,
"Reservations",
"**",
].join("/"),
method: "GET",
allow: true,
});
var workerFetch = new TaskRouterCapability_1.Policy({
url: [
TASKROUTER_BASE_URL,
version,
"Workspaces",
workspaceSid,
"Workers",
workerSid,
].join("/"),
method: "GET",
allow: true,
});
return [activities, tasks, reservations, workerFetch];
}
/**
* Build the default Event Bridge Policies
*
* @param accountSid - account sid
* @param channelId - channel id
* @returns list of Policies
*/
function defaultEventBridgePolicies(accountSid, channelId) {
var url = [EVENT_URL_BASE, accountSid, channelId].join("/");
return [
new TaskRouterCapability_1.Policy({
url: url,
method: "GET",
allow: true,
}),
new TaskRouterCapability_1.Policy({
url: url,
method: "POST",
allow: true,
}),
];
}
/**
* Generate TaskRouter workspace url
*
* @param workspaceSid - workspace sid or '**' for all workspaces
* @returns generated url
*/
function workspacesUrl(workspaceSid) {
return [TASKROUTER_BASE_URL, TASKROUTER_VERSION, "Workspaces", workspaceSid]
.filter((item) => typeof item === "string")
.join("/");
}
/**
* Generate TaskRouter task queue url
*
* @param workspaceSid - workspace sid
* @param taskQueueSid - task queue sid or '**' for all task queues
* @returns generated url
*/
function taskQueuesUrl(workspaceSid, taskQueueSid) {
return [workspacesUrl(workspaceSid), "TaskQueues", taskQueueSid]
.filter((item) => typeof item === "string")
.join("/");
}
/**
* Generate TaskRouter task url
*
* @param workspaceSid - workspace sid
* @param taskSid - task sid or '**' for all tasks
* @returns generated url
*/
function tasksUrl(workspaceSid, taskSid) {
return [workspacesUrl(workspaceSid), "Tasks", taskSid]
.filter((item) => typeof item === "string")
.join("/");
}
/**
* Generate TaskRouter activity url
*
* @param workspaceSid - workspace sid
* @param activitySid - activity sid or '**' for all activities
* @returns generated url
*/
function activitiesUrl(workspaceSid, activitySid) {
return [workspacesUrl(workspaceSid), "Activities", activitySid]
.filter((item) => typeof item === "string")
.join("/");
}
/**
* Generate TaskRouter worker url
*
* @param workspaceSid - workspace sid
* @param workerSid - worker sid or '**' for all workers
* @returns generated url
*/
function workersUrl(workspaceSid, workerSid) {
return [workspacesUrl(workspaceSid), "Workers", workerSid]
.filter((item) => typeof item === "string")
.join("/");
}
/**
* Generate TaskRouter worker reservation url
*
* @param workspaceSid - workspace sid
* @param workerSid - worker sid
* @param reservationSid - reservation sid or '**' for all reservations
* @returns generated url
*/
function reservationsUrl(workspaceSid, workerSid, reservationSid) {
return [workersUrl(workspaceSid, workerSid), "Reservations", reservationSid]
.filter((item) => typeof item === "string")
.join("/");
}

View File

@@ -0,0 +1,20 @@
declare class RequestCanonicalizer {
method: string;
uri: string;
queryParams: Record<string, string>;
requestBody: any;
headers: Record<string, string>;
constructor(method: string, uri: string, queryParams: Record<string, string>, requestBody: any, headers: Record<string, string>);
getCanonicalizedMethod(): string;
customEncode(str: string): string;
ASCIICompare(a: string, b: string): number;
getCanonicalizedPath(): string;
getCanonicalizedQueryParams(): string;
getCanonicalizedHeaders(): string;
getCanonicalizedHashedHeaders(): string;
getCanonicalizedRequestBody(): string;
sha256Hex(body: string): string;
getCanonicalizedRequestString(): string;
create(): string;
}
export default RequestCanonicalizer;

View File

@@ -0,0 +1,97 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = __importDefault(require("crypto"));
class RequestCanonicalizer {
constructor(method, uri, queryParams, requestBody, headers) {
this.method = method;
this.uri = uri;
this.queryParams = queryParams;
this.requestBody = requestBody;
this.headers = headers;
}
getCanonicalizedMethod() {
return this.method.toUpperCase();
}
customEncode(str) {
return encodeURIComponent(decodeURIComponent(str))
.replace(/\*/g, "%2A")
.replace(/%7E/g, "~");
}
ASCIICompare(a, b) {
if (a < b)
return -1;
return a > b ? 1 : 0;
}
getCanonicalizedPath() {
// Remove query string from path
const path = this.uri.split("?")[0];
// Normalize duplicate slashes (but preserve the leading one)
const normalizedPath = path.replace(/\/+/g, "/");
// We must preserve slashes (as path delimiters) but encode each segment
// Split and encode, but first decode each segment to avoid double-encoding
return normalizedPath
.split("/")
.map((segment) => this.customEncode(segment))
.join("/");
}
getCanonicalizedQueryParams() {
if (!this.queryParams) {
return "";
}
// sort query params on the basis of '{key}={value}'
const sortedQueryParams = Object.entries(this.queryParams)
.map(([key, value]) => {
return `${key}=${value}`;
})
.sort((a, b) => this.ASCIICompare(a, b)) // forces ASCII sorting using custom compare
.map((param) => {
const [key, value] = param.split("=");
return `${this.customEncode(key)}=${this.customEncode(value)}`; // encode and concatenate as `key=value`
});
return sortedQueryParams.join("&");
}
getCanonicalizedHeaders() {
// sort headers on the basis of '{key}:{value}'
const sortedHeaders = Object.keys(this.headers)
.map((key) => {
if (!this.headers[key]) {
return `${key.toLowerCase()}:`;
}
return `${key.toLowerCase()}:${this.headers[key].trim()}`;
})
.sort((a, b) => this.ASCIICompare(a, b)); // forces ASCII sorting using custom compare
return `${sortedHeaders.join("\n")}\n`;
}
getCanonicalizedHashedHeaders() {
const sortedHeaders = Object.keys(this.headers).sort((a, b) => this.ASCIICompare(a, b)); // forces ASCII sorting using custom compare
return sortedHeaders.join(";");
}
getCanonicalizedRequestBody() {
if (!this.requestBody) {
return "";
}
if (typeof this.requestBody === "string") {
return this.sha256Hex(this.requestBody);
}
else
return this.sha256Hex(JSON.stringify(this.requestBody));
}
sha256Hex(body) {
return crypto_1.default.createHash("sha256").update(body).digest("hex");
}
getCanonicalizedRequestString() {
return `${this.getCanonicalizedMethod()}
${this.getCanonicalizedPath()}
${this.getCanonicalizedQueryParams()}
${this.getCanonicalizedHeaders()}
${this.getCanonicalizedHashedHeaders()}
${this.getCanonicalizedRequestBody()}`;
}
create() {
return this.sha256Hex(this.getCanonicalizedRequestString());
}
}
exports.default = RequestCanonicalizer;

View File

@@ -0,0 +1,45 @@
import { ValidationClientOptions } from "../../base/ValidationClient";
import RequestCanonicalizer from "./RequestCanonicalizer";
import jwt, { Algorithm } from "jsonwebtoken";
declare class ValidationToken {
static readonly DEFAULT_ALGORITHM: "RS256";
static readonly ALGORITHMS: readonly [jwt.Algorithm, jwt.Algorithm];
private readonly _accountSid;
private readonly _credentialSid;
private readonly _signingKey;
private readonly _privateKey;
private readonly _algorithm;
ttl: number;
get accountSid(): string;
get credentialSid(): string;
get signingKey(): string;
get privateKey(): string;
get algorithm(): Algorithm;
/**
* @constructor
* @param opts - The Options used to configure the ValidationToken
* @param opts.accountSid - The account SID
* @param opts.credentialSid - The credential SID for public key submitted to Twilio
* @param opts.signingKey - The signing key
* @param opts.privateKey - The private key for signing the token
* @param opts.algorithm - The algorithm to use for signing the token
* @param opts.ttl - The time to live for the token in seconds
*/
constructor(opts: ValidationClientOptions);
/**
* Generates a `RequestCanonicalizer` instance for the given HTTP request.
*
* @param request - The HTTP request object containing details such as headers, URL, method, query parameters, and body.
* @throws {Error} If the request URL or method is missing.
* @returns {RequestCanonicalizer} - An instance of `RequestCanonicalizer` initialized with the canonicalized request details.
*/
getRequestCanonicalizer(request: any): RequestCanonicalizer;
/**
* Generate a JWT token to include in the request header for PKCV
* @param request - The request object
* @returns {string} - The JWT token
*/
fromHttpRequest(request: any): string;
}
declare namespace ValidationToken { }
export = ValidationToken;

View File

@@ -0,0 +1,121 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const RequestCanonicalizer_1 = __importDefault(require("./RequestCanonicalizer"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
class ValidationToken {
get accountSid() {
return this._accountSid;
}
get credentialSid() {
return this._credentialSid;
}
get signingKey() {
return this._signingKey;
}
get privateKey() {
return this._privateKey;
}
get algorithm() {
return this._algorithm;
}
/**
* @constructor
* @param opts - The Options used to configure the ValidationToken
* @param opts.accountSid - The account SID
* @param opts.credentialSid - The credential SID for public key submitted to Twilio
* @param opts.signingKey - The signing key
* @param opts.privateKey - The private key for signing the token
* @param opts.algorithm - The algorithm to use for signing the token
* @param opts.ttl - The time to live for the token in seconds
*/
constructor(opts) {
if (!opts.accountSid) {
throw new Error("accountSid is required");
}
if (!opts.credentialSid) {
throw new Error("credentialSid is required");
}
if (!opts.signingKey) {
throw new Error("signingKey is required");
}
if (!opts.privateKey) {
throw new Error("privateKey is required");
}
const algorithm = opts.algorithm ?? ValidationToken.DEFAULT_ALGORITHM; // default to RS256;
if (!ValidationToken.ALGORITHMS.includes(algorithm)) {
throw new Error("Algorithm not supported. Allowed values are " +
ValidationToken.ALGORITHMS.join(", "));
}
this._accountSid = opts.accountSid;
this._credentialSid = opts.credentialSid;
this._signingKey = opts.signingKey;
this._privateKey = opts.privateKey;
this._algorithm = algorithm;
this.ttl = 300;
}
/**
* Generates a `RequestCanonicalizer` instance for the given HTTP request.
*
* @param request - The HTTP request object containing details such as headers, URL, method, query parameters, and body.
* @throws {Error} If the request URL or method is missing.
* @returns {RequestCanonicalizer} - An instance of `RequestCanonicalizer` initialized with the canonicalized request details.
*/
getRequestCanonicalizer(request) {
const headers = request.headers ?? {};
const requestUrl = request.url;
const method = request.method;
const queryParams = request.params;
const requestBody = request.data;
if (!requestUrl) {
throw new Error("Url is required");
}
if (!method) {
throw new Error("Method is required");
}
const url = new URL(requestUrl);
let signedHeaders = {
host: url.host,
authorization: headers["Authorization"],
};
return new RequestCanonicalizer_1.default(method, url.pathname, queryParams, requestBody, signedHeaders);
}
/**
* Generate a JWT token to include in the request header for PKCV
* @param request - The request object
* @returns {string} - The JWT token
*/
fromHttpRequest(request) {
try {
const requestCanonicalizer = this.getRequestCanonicalizer(request);
const canonicalizedRequest = requestCanonicalizer.create();
const header = {
cty: "twilio-pkrv;v=1",
typ: "JWT",
alg: this._algorithm,
kid: this._credentialSid,
};
const payload = {
iss: this._signingKey,
sub: this._accountSid,
hrh: requestCanonicalizer.getCanonicalizedHashedHeaders(),
rqh: canonicalizedRequest,
};
return jsonwebtoken_1.default.sign(payload, this._privateKey, {
header: header,
algorithm: this._algorithm,
expiresIn: this.ttl,
});
}
catch (err) {
throw new Error("Error generating JWT token " + err);
}
}
}
ValidationToken.DEFAULT_ALGORITHM = "RS256";
ValidationToken.ALGORITHMS = [
"RS256",
"PS256",
];
module.exports = ValidationToken;

19
node_modules/twilio/lib/rest/Accounts.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { AuthTokenPromotionListInstance } from "./accounts/v1/authTokenPromotion";
import { CredentialListInstance } from "./accounts/v1/credential";
import { SecondaryAuthTokenListInstance } from "./accounts/v1/secondaryAuthToken";
import AccountsBase from "./AccountsBase";
declare class Accounts extends AccountsBase {
/**
* @deprecated - Use v1.authTokenPromotion; instead
*/
get authTokenPromotion(): AuthTokenPromotionListInstance;
/**
* @deprecated - Use v1.credentials; instead
*/
get credentials(): CredentialListInstance;
/**
* @deprecated - Use v1.secondaryAuthToken; instead
*/
get secondaryAuthToken(): SecondaryAuthTokenListInstance;
}
export = Accounts;

29
node_modules/twilio/lib/rest/Accounts.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const AccountsBase_1 = __importDefault(require("./AccountsBase"));
class Accounts extends AccountsBase_1.default {
/**
* @deprecated - Use v1.authTokenPromotion; instead
*/
get authTokenPromotion() {
console.warn("authTokenPromotion is deprecated. Use v1.authTokenPromotion; instead.");
return this.v1.authTokenPromotion;
}
/**
* @deprecated - Use v1.credentials; instead
*/
get credentials() {
console.warn("credentials is deprecated. Use v1.credentials; instead.");
return this.v1.credentials;
}
/**
* @deprecated - Use v1.secondaryAuthToken; instead
*/
get secondaryAuthToken() {
console.warn("secondaryAuthToken is deprecated. Use v1.secondaryAuthToken; instead.");
return this.v1.secondaryAuthToken;
}
}
module.exports = Accounts;

13
node_modules/twilio/lib/rest/AccountsBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Domain from "../base/Domain";
import V1 from "./accounts/V1";
declare class AccountsBase extends Domain {
_v1?: V1;
/**
* Initialize accounts domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
}
export = AccountsBase;

31
node_modules/twilio/lib/rest/AccountsBase.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./accounts/V1"));
class AccountsBase extends Domain_1.default {
/**
* Initialize accounts domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://accounts.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
}
module.exports = AccountsBase;

127
node_modules/twilio/lib/rest/Api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,127 @@
import { AccountContext, AccountListInstance } from "./api/v2010/account";
import { AddressListInstance } from "./api/v2010/account/address";
import { ApplicationListInstance } from "./api/v2010/account/application";
import { AuthorizedConnectAppListInstance } from "./api/v2010/account/authorizedConnectApp";
import { AvailablePhoneNumberCountryListInstance } from "./api/v2010/account/availablePhoneNumberCountry";
import { BalanceListInstance } from "./api/v2010/account/balance";
import { CallListInstance } from "./api/v2010/account/call";
import { ConferenceListInstance } from "./api/v2010/account/conference";
import { ConnectAppListInstance } from "./api/v2010/account/connectApp";
import { IncomingPhoneNumberListInstance } from "./api/v2010/account/incomingPhoneNumber";
import { KeyListInstance } from "./api/v2010/account/key";
import { MessageListInstance } from "./api/v2010/account/message";
import { NewKeyListInstance } from "./api/v2010/account/newKey";
import { NewSigningKeyListInstance } from "./api/v2010/account/newSigningKey";
import { NotificationListInstance } from "./api/v2010/account/notification";
import { OutgoingCallerIdListInstance } from "./api/v2010/account/outgoingCallerId";
import { QueueListInstance } from "./api/v2010/account/queue";
import { RecordingListInstance } from "./api/v2010/account/recording";
import { ShortCodeListInstance } from "./api/v2010/account/shortCode";
import { SigningKeyListInstance } from "./api/v2010/account/signingKey";
import { SipListInstance } from "./api/v2010/account/sip";
import { TokenListInstance } from "./api/v2010/account/token";
import { TranscriptionListInstance } from "./api/v2010/account/transcription";
import { UsageListInstance } from "./api/v2010/account/usage";
import { ValidationRequestListInstance } from "./api/v2010/account/validationRequest";
import ApiBase from "./ApiBase";
declare class Api extends ApiBase {
get account(): AccountContext;
get accounts(): AccountListInstance;
/**
* @deprecated - Use account.addresses instead
*/
get addresses(): AddressListInstance;
/**
* @deprecated - Use account.applications instead
*/
get applications(): ApplicationListInstance;
/**
* @deprecated - Use account.authorizedConnectApps instead
*/
get authorizedConnectApps(): AuthorizedConnectAppListInstance;
/**
* @deprecated - Use account.availablePhoneNumbers instead
*/
get availablePhoneNumbers(): AvailablePhoneNumberCountryListInstance;
/**
* @deprecated - Use account.balance instead
*/
get balance(): BalanceListInstance;
/**
* @deprecated - Use account.calls instead
*/
get calls(): CallListInstance;
/**
* @deprecated - Use account.conferences instead
*/
get conferences(): ConferenceListInstance;
/**
* @deprecated - Use account.connectApps instead
*/
get connectApps(): ConnectAppListInstance;
/**
* @deprecated - Use account.incomingPhoneNumbers instead
*/
get incomingPhoneNumbers(): IncomingPhoneNumberListInstance;
/**
* @deprecated - Use account.keys instead
*/
get keys(): KeyListInstance;
/**
* @deprecated - Use account.messages instead
*/
get messages(): MessageListInstance;
/**
* @deprecated - Use account.newKeys instead
*/
get newKeys(): NewKeyListInstance;
/**
* @deprecated - Use account.newSigningKeys instead
*/
get newSigningKeys(): NewSigningKeyListInstance;
/**
* @deprecated - Use account.notifications instead
*/
get notifications(): NotificationListInstance;
/**
* @deprecated - Use account.outgoingCallerIds instead
*/
get outgoingCallerIds(): OutgoingCallerIdListInstance;
/**
* @deprecated - Use account.queues instead
*/
get queues(): QueueListInstance;
/**
* @deprecated - Use account.recordings instead
*/
get recordings(): RecordingListInstance;
/**
* @deprecated - Use account.signingKeys instead
*/
get signingKeys(): SigningKeyListInstance;
/**
* @deprecated - Use account.sip instead
*/
get sip(): SipListInstance;
/**
* @deprecated - Use account.shortCodes instead
*/
get shortCodes(): ShortCodeListInstance;
/**
* @deprecated - Use account.tokens instead
*/
get tokens(): TokenListInstance;
/**
* @deprecated - Use account.transcriptions instead
*/
get transcriptions(): TranscriptionListInstance;
/**
* @deprecated - Use account.usage instead
*/
get usage(): UsageListInstance;
/**
* @deprecated - Use account.validationRequests instead
*/
get validationRequests(): ValidationRequestListInstance;
}
export = Api;

182
node_modules/twilio/lib/rest/Api.js generated vendored Normal file
View File

@@ -0,0 +1,182 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const ApiBase_1 = __importDefault(require("./ApiBase"));
class Api extends ApiBase_1.default {
get account() {
return this.v2010.account;
}
get accounts() {
return this.v2010.accounts;
}
/**
* @deprecated - Use account.addresses instead
*/
get addresses() {
console.warn("addresses is deprecated. Use account.addresses instead.");
return this.account.addresses;
}
/**
* @deprecated - Use account.applications instead
*/
get applications() {
console.warn("applications is deprecated. Use account.applications instead.");
return this.account.applications;
}
/**
* @deprecated - Use account.authorizedConnectApps instead
*/
get authorizedConnectApps() {
console.warn("authorizedConnectApps is deprecated. Use account.authorizedConnectApps instead.");
return this.account.authorizedConnectApps;
}
/**
* @deprecated - Use account.availablePhoneNumbers instead
*/
get availablePhoneNumbers() {
console.warn("availablePhoneNumbers is deprecated. Use account.availablePhoneNumbers instead.");
return this.account.availablePhoneNumbers;
}
/**
* @deprecated - Use account.balance instead
*/
get balance() {
console.warn("balance is deprecated. Use account.balance instead.");
return this.account.balance;
}
/**
* @deprecated - Use account.calls instead
*/
get calls() {
console.warn("calls is deprecated. Use account.calls instead.");
return this.account.calls;
}
/**
* @deprecated - Use account.conferences instead
*/
get conferences() {
console.warn("conferences is deprecated. Use account.conferences instead.");
return this.account.conferences;
}
/**
* @deprecated - Use account.connectApps instead
*/
get connectApps() {
console.warn("connectApps is deprecated. Use account.connectApps instead.");
return this.account.connectApps;
}
/**
* @deprecated - Use account.incomingPhoneNumbers instead
*/
get incomingPhoneNumbers() {
console.warn("incomingPhoneNumbers is deprecated. Use account.incomingPhoneNumbers instead.");
return this.account.incomingPhoneNumbers;
}
/**
* @deprecated - Use account.keys instead
*/
get keys() {
console.warn("keys is deprecated. Use account.keys instead.");
return this.account.keys;
}
/**
* @deprecated - Use account.messages instead
*/
get messages() {
console.warn("messages is deprecated. Use account.messages instead.");
return this.account.messages;
}
/**
* @deprecated - Use account.newKeys instead
*/
get newKeys() {
console.warn("newKeys is deprecated. Use account.newKeys instead.");
return this.account.newKeys;
}
/**
* @deprecated - Use account.newSigningKeys instead
*/
get newSigningKeys() {
console.warn("newSigningKeys is deprecated. Use account.newSigningKeys instead.");
return this.account.newSigningKeys;
}
/**
* @deprecated - Use account.notifications instead
*/
get notifications() {
console.warn("notifications is deprecated. Use account.notifications instead.");
return this.account.notifications;
}
/**
* @deprecated - Use account.outgoingCallerIds instead
*/
get outgoingCallerIds() {
console.warn("outgoingCallerIds is deprecated. Use account.outgoingCallerIds instead.");
return this.account.outgoingCallerIds;
}
/**
* @deprecated - Use account.queues instead
*/
get queues() {
console.warn("queues is deprecated. Use account.queues instead.");
return this.account.queues;
}
/**
* @deprecated - Use account.recordings instead
*/
get recordings() {
console.warn("recordings is deprecated. Use account.recordings instead.");
return this.account.recordings;
}
/**
* @deprecated - Use account.signingKeys instead
*/
get signingKeys() {
console.warn("signingKeys is deprecated. Use account.signingKeys instead.");
return this.account.signingKeys;
}
/**
* @deprecated - Use account.sip instead
*/
get sip() {
console.warn("sip is deprecated. Use account.sip instead.");
return this.account.sip;
}
/**
* @deprecated - Use account.shortCodes instead
*/
get shortCodes() {
console.warn("shortCodes is deprecated. Use account.shortCodes instead.");
return this.account.shortCodes;
}
/**
* @deprecated - Use account.tokens instead
*/
get tokens() {
console.warn("tokens is deprecated. Use account.tokens instead.");
return this.account.tokens;
}
/**
* @deprecated - Use account.transcriptions instead
*/
get transcriptions() {
console.warn("transcriptions is deprecated. Use account.transcriptions instead.");
return this.account.transcriptions;
}
/**
* @deprecated - Use account.usage instead
*/
get usage() {
console.warn("usage is deprecated. Use account.usage instead.");
return this.account.usage;
}
/**
* @deprecated - Use account.validationRequests instead
*/
get validationRequests() {
console.warn("validationRequests is deprecated. Use account.validationRequests instead.");
return this.account.validationRequests;
}
}
module.exports = Api;

13
node_modules/twilio/lib/rest/ApiBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Domain from "../base/Domain";
import V2010 from "./api/V2010";
declare class ApiBase extends Domain {
_v2010?: V2010;
/**
* Initialize api domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v2010(): V2010;
}
export = ApiBase;

31
node_modules/twilio/lib/rest/ApiBase.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V2010_1 = __importDefault(require("./api/V2010"));
class ApiBase extends Domain_1.default {
/**
* Initialize api domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://api.twilio.com");
}
get v2010() {
this._v2010 = this._v2010 || new V2010_1.default(this);
return this._v2010;
}
}
module.exports = ApiBase;

4
node_modules/twilio/lib/rest/Assistants.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import AssistantsBase from "./AssistantsBase";
declare class Assistants extends AssistantsBase {
}
export = Assistants;

8
node_modules/twilio/lib/rest/Assistants.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const AssistantsBase_1 = __importDefault(require("./AssistantsBase"));
class Assistants extends AssistantsBase_1.default {
}
module.exports = Assistants;

13
node_modules/twilio/lib/rest/AssistantsBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Domain from "../base/Domain";
import V1 from "./assistants/V1";
declare class AssistantsBase extends Domain {
_v1?: V1;
/**
* Initialize assistants domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
}
export = AssistantsBase;

31
node_modules/twilio/lib/rest/AssistantsBase.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./assistants/V1"));
class AssistantsBase extends Domain_1.default {
/**
* Initialize assistants domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://assistants.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
}
module.exports = AssistantsBase;

14
node_modules/twilio/lib/rest/Bulkexports.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { ExportListInstance } from "./bulkexports/v1/export";
import { ExportConfigurationListInstance } from "./bulkexports/v1/exportConfiguration";
import BulkexportsBase from "./BulkexportsBase";
declare class Bulkexports extends BulkexportsBase {
/**
* @deprecated - Use v1.exports instead
*/
get exports(): ExportListInstance;
/**
* @deprecated - Use v1.exportConfiguration instead
*/
get exportConfiguration(): ExportConfigurationListInstance;
}
export = Bulkexports;

22
node_modules/twilio/lib/rest/Bulkexports.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const BulkexportsBase_1 = __importDefault(require("./BulkexportsBase"));
class Bulkexports extends BulkexportsBase_1.default {
/**
* @deprecated - Use v1.exports instead
*/
get exports() {
console.warn("exports is deprecated. Use v1.exports instead.");
return this.v1.exports;
}
/**
* @deprecated - Use v1.exportConfiguration instead
*/
get exportConfiguration() {
console.warn("exportConfiguration is deprecated. Use v1.exportConfiguration instead.");
return this.v1.exportConfiguration;
}
}
module.exports = Bulkexports;

13
node_modules/twilio/lib/rest/BulkexportsBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Domain from "../base/Domain";
import V1 from "./bulkexports/V1";
declare class BulkexportsBase extends Domain {
_v1?: V1;
/**
* Initialize bulkexports domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
}
export = BulkexportsBase;

31
node_modules/twilio/lib/rest/BulkexportsBase.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./bulkexports/V1"));
class BulkexportsBase extends Domain_1.default {
/**
* Initialize bulkexports domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://bulkexports.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
}
module.exports = BulkexportsBase;

19
node_modules/twilio/lib/rest/Chat.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { CredentialListInstance } from "./chat/v2/credential";
import { ServiceListInstance } from "./chat/v2/service";
import { ChannelListInstance } from "./chat/v3/channel";
import ChatBase from "./ChatBase";
declare class Chat extends ChatBase {
/**
* @deprecated - Use v2.credentials instead
*/
get credentials(): CredentialListInstance;
/**
* @deprecated - Use v2.services instead
*/
get services(): ServiceListInstance;
/**
* @deprecated - Use v3.channels instead
*/
get channels(): ChannelListInstance;
}
export = Chat;

29
node_modules/twilio/lib/rest/Chat.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const ChatBase_1 = __importDefault(require("./ChatBase"));
class Chat extends ChatBase_1.default {
/**
* @deprecated - Use v2.credentials instead
*/
get credentials() {
console.warn("credentials is deprecated. Use v2.credentials instead.");
return this.v2.credentials;
}
/**
* @deprecated - Use v2.services instead
*/
get services() {
console.warn("services is deprecated. Use v2.services instead.");
return this.v2.services;
}
/**
* @deprecated - Use v3.channels instead
*/
get channels() {
console.warn("channels is deprecated. Use v3.channels instead.");
return this.v3.channels;
}
}
module.exports = Chat;

19
node_modules/twilio/lib/rest/ChatBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import Domain from "../base/Domain";
import V1 from "./chat/V1";
import V2 from "./chat/V2";
import V3 from "./chat/V3";
declare class ChatBase extends Domain {
_v1?: V1;
_v2?: V2;
_v3?: V3;
/**
* Initialize chat domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
get v2(): V2;
get v3(): V3;
}
export = ChatBase;

41
node_modules/twilio/lib/rest/ChatBase.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./chat/V1"));
const V2_1 = __importDefault(require("./chat/V2"));
const V3_1 = __importDefault(require("./chat/V3"));
class ChatBase extends Domain_1.default {
/**
* Initialize chat domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://chat.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
get v2() {
this._v2 = this._v2 || new V2_1.default(this);
return this._v2;
}
get v3() {
this._v3 = this._v3 || new V3_1.default(this);
return this._v3;
}
}
module.exports = ChatBase;

9
node_modules/twilio/lib/rest/Content.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import ContentBase from "./ContentBase";
import { ContentListInstance } from "./content/v1/content";
declare class Content extends ContentBase {
/**
* @deprecated - Use v1.contents instead
*/
get contents(): ContentListInstance;
}
export = Content;

15
node_modules/twilio/lib/rest/Content.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const ContentBase_1 = __importDefault(require("./ContentBase"));
class Content extends ContentBase_1.default {
/**
* @deprecated - Use v1.contents instead
*/
get contents() {
console.warn("contents is deprecated. Use v1.contents instead.");
return this.v1.contents;
}
}
module.exports = Content;

16
node_modules/twilio/lib/rest/ContentBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import Domain from "../base/Domain";
import V1 from "./content/V1";
import V2 from "./content/V2";
declare class ContentBase extends Domain {
_v1?: V1;
_v2?: V2;
/**
* Initialize content domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
get v2(): V2;
}
export = ContentBase;

36
node_modules/twilio/lib/rest/ContentBase.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./content/V1"));
const V2_1 = __importDefault(require("./content/V2"));
class ContentBase extends Domain_1.default {
/**
* Initialize content domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://content.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
get v2() {
this._v2 = this._v2 || new V2_1.default(this);
return this._v2;
}
}
module.exports = ContentBase;

44
node_modules/twilio/lib/rest/Conversations.d.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { AddressConfigurationListInstance } from "./conversations/v1/addressConfiguration";
import { ConfigurationListInstance } from "./conversations/v1/configuration";
import { ConversationListInstance } from "./conversations/v1/conversation";
import { CredentialListInstance } from "./conversations/v1/credential";
import { ParticipantConversationListInstance } from "./conversations/v1/participantConversation";
import { RoleListInstance } from "./conversations/v1/role";
import { ServiceListInstance } from "./conversations/v1/service";
import { UserListInstance } from "./conversations/v1/user";
import ConversationsBase from "./ConversationsBase";
declare class Conversations extends ConversationsBase {
/**
* @deprecated - Use v1.configuration instead
*/
get configuration(): ConfigurationListInstance;
/**
* @deprecated - Use v1.addressConfigurations instead
*/
get addressConfigurations(): AddressConfigurationListInstance;
/**
* @deprecated - Use v1.conversations instead
*/
get conversations(): ConversationListInstance;
/**
* @deprecated - Use v1.credentials instead
*/
get credentials(): CredentialListInstance;
/**
* @deprecated - Use v1.participantConversations instead
*/
get participantConversations(): ParticipantConversationListInstance;
/**
* @deprecated - Use v1.roles instead
*/
get roles(): RoleListInstance;
/**
* @deprecated - Use v1.services instead
*/
get services(): ServiceListInstance;
/**
* @deprecated - Use v1.users instead
*/
get users(): UserListInstance;
}
export = Conversations;

64
node_modules/twilio/lib/rest/Conversations.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const ConversationsBase_1 = __importDefault(require("./ConversationsBase"));
class Conversations extends ConversationsBase_1.default {
/**
* @deprecated - Use v1.configuration instead
*/
get configuration() {
console.warn("configuration is deprecated. Use v1.configuration instead.");
return this.v1.configuration;
}
/**
* @deprecated - Use v1.addressConfigurations instead
*/
get addressConfigurations() {
console.warn("addressConfigurations is deprecated. Use v1.addressConfigurations instead.");
return this.v1.addressConfigurations;
}
/**
* @deprecated - Use v1.conversations instead
*/
get conversations() {
console.warn("conversations is deprecated. Use v1.conversations instead.");
return this.v1.conversations;
}
/**
* @deprecated - Use v1.credentials instead
*/
get credentials() {
console.warn("credentials is deprecated. Use v1.credentials instead.");
return this.v1.credentials;
}
/**
* @deprecated - Use v1.participantConversations instead
*/
get participantConversations() {
console.warn("participantConversations is deprecated. Use v1.participantConversations instead.");
return this.v1.participantConversations;
}
/**
* @deprecated - Use v1.roles instead
*/
get roles() {
console.warn("roles is deprecated. Use v1.roles instead.");
return this.v1.roles;
}
/**
* @deprecated - Use v1.services instead
*/
get services() {
console.warn("services is deprecated. Use v1.services instead.");
return this.v1.services;
}
/**
* @deprecated - Use v1.users instead
*/
get users() {
console.warn("users is deprecated. Use v1.users instead.");
return this.v1.users;
}
}
module.exports = Conversations;

13
node_modules/twilio/lib/rest/ConversationsBase.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import Domain from "../base/Domain";
import V1 from "./conversations/V1";
declare class ConversationsBase extends Domain {
_v1?: V1;
/**
* Initialize conversations domain
*
* @param twilio - The twilio client
*/
constructor(twilio: any);
get v1(): V1;
}
export = ConversationsBase;

31
node_modules/twilio/lib/rest/ConversationsBase.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Domain_1 = __importDefault(require("../base/Domain"));
const V1_1 = __importDefault(require("./conversations/V1"));
class ConversationsBase extends Domain_1.default {
/**
* Initialize conversations domain
*
* @param twilio - The twilio client
*/
constructor(twilio) {
super(twilio, "https://conversations.twilio.com");
}
get v1() {
this._v1 = this._v1 || new V1_1.default(this);
return this._v1;
}
}
module.exports = ConversationsBase;

24
node_modules/twilio/lib/rest/Events.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import { EventTypeListInstance } from "./events/v1/eventType";
import { SchemaListInstance } from "./events/v1/schema";
import { SinkListInstance } from "./events/v1/sink";
import { SubscriptionListInstance } from "./events/v1/subscription";
import EventsBase from "./EventsBase";
declare class Events extends EventsBase {
/**
* @deprecated - Use v1.eventTypes instead
*/
get eventTypes(): EventTypeListInstance;
/**
* @deprecated - Use v1.schemas instead
*/
get schemas(): SchemaListInstance;
/**
* @deprecated - Use v1.sinks instead
*/
get sinks(): SinkListInstance;
/**
* @deprecated - Use v1.subscriptions instead
*/
get subscriptions(): SubscriptionListInstance;
}
export = Events;

36
node_modules/twilio/lib/rest/Events.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const EventsBase_1 = __importDefault(require("./EventsBase"));
class Events extends EventsBase_1.default {
/**
* @deprecated - Use v1.eventTypes instead
*/
get eventTypes() {
console.warn("eventTypes is deprecated. Use v1.eventTypes instead.");
return this.v1.eventTypes;
}
/**
* @deprecated - Use v1.schemas instead
*/
get schemas() {
console.warn("schemas is deprecated. Use v1.schemas instead.");
return this.v1.schemas;
}
/**
* @deprecated - Use v1.sinks instead
*/
get sinks() {
console.warn("sinks is deprecated. Use v1.sinks instead.");
return this.v1.sinks;
}
/**
* @deprecated - Use v1.subscriptions instead
*/
get subscriptions() {
console.warn("subscriptions is deprecated. Use v1.subscriptions instead.");
return this.v1.subscriptions;
}
}
module.exports = Events;

Some files were not shown because too many files have changed in this diff Show More