Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

revolt-api

Package Overview
Dependencies
Maintainers
0
Versions
96
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

revolt-api - npm Package Compare versions

Comparing version 0.7.15 to 0.7.16-next.1

codegen.js

183

dist/index.d.ts

@@ -1,176 +0,19 @@

import type { AxiosRequestConfig } from 'axios';
export * from './types';
import type { APIRoutes } from './routes';
declare type Methods = APIRoutes['method'];
declare type PickRoutes<Method extends Methods> = APIRoutes & {
method: Method;
};
declare type GetRoutes = PickRoutes<'get'>;
declare type PatchRoutes = PickRoutes<'patch'>;
declare type PutRoutes = PickRoutes<'put'>;
declare type DeleteRoutes = PickRoutes<'delete'>;
declare type PostRoutes = PickRoutes<'post'>;
declare type Count<Str extends string, SubStr extends string, Matches extends null[] = []> = Str extends `${infer _}${SubStr}${infer After}` ? Count<After, SubStr, [...Matches, null]> : Matches['length'];
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
*/
export declare function getPathName(anyPath: string): string | undefined;
/**
* Client configuration options
*/
export interface Options {
import { ClientOptions } from "openapi-fetch";
import type { paths } from "./api.js";
export type * from "./types.js";
export type FetchConfiguration = ClientOptions & {
/**
* Base URL of the Revolt node
* Specify a bot token to authenticate with Revolt
*/
baseURL: string;
botToken?: string;
/**
* Authentication used for requests
* Specify a session token to authenticate with Revolt
*/
authentication: {
rauth?: string | undefined;
revolt?: {
token: string;
} | string | undefined;
};
}
sessionToken?: string;
};
/**
* API Client
* Create a new Fetch client for the API
* @param config Configuration
* @returns Fetch client
*/
export declare class API {
private baseURL;
private authentication;
constructor({ baseURL, authentication }?: Partial<Options>);
/**
* Generate authentication options.
*/
get auth(): AxiosRequestConfig;
/**
* Generate config to pass through to API.
*/
get config(): AxiosRequestConfig;
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req<Method extends Methods, Routes extends PickRoutes<Method>, Path extends Routes['path'], Route extends Routes & {
path: Path;
parts: Count<Path, '/'>;
}>(method: Method, path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
get<Path extends GetRoutes['path'], Route extends GetRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @returns Typed Response Data
*/
get<Path extends (GetRoutes & {
params: undefined;
})['path'], Route extends GetRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
patch<Path extends PatchRoutes['path'], Route extends PatchRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @returns Typed Response Data
*/
patch<Path extends (PatchRoutes & {
params: undefined;
})['path'], Route extends PatchRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
put<Path extends PutRoutes['path'], Route extends PutRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @returns Typed Response Data
*/
put<Path extends (PutRoutes & {
params: undefined;
})['path'], Route extends PutRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
delete<Path extends DeleteRoutes['path'], Route extends DeleteRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params?: any, config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @returns Typed Response Data
*/
delete<Path extends (DeleteRoutes & {
params: undefined;
})['path'], Route extends DeleteRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params?: any): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
post<Path extends PostRoutes['path'], Route extends PostRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @returns Typed Response Data
*/
post<Path extends (PostRoutes & {
params: undefined;
})['path'], Route extends PostRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
}
export declare function createClient(config?: FetchConfiguration): import("openapi-fetch").Client<paths, `${string}/${string}`>;
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};

@@ -20,133 +15,28 @@ var __importDefault = (this && this.__importDefault) || function (mod) {

Object.defineProperty(exports, "__esModule", { value: true });
exports.API = exports.getPathName = void 0;
// This file was auto-generated by @insertish/oapi!
const axios_1 = __importDefault(require("axios"));
const lodash_defaultsdeep_1 = __importDefault(require("lodash.defaultsdeep"));
__exportStar(require("./types"), exports);
const baseURL_1 = require("./baseURL");
const params_1 = require("./params");
exports.createClient = createClient;
const openapi_fetch_1 = __importDefault(require("openapi-fetch"));
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
* Create a new Fetch client for the API
* @param config Configuration
* @returns Fetch client
*/
function getPathName(anyPath) {
const segments = anyPath.split('/');
const list = params_1.pathResolve[(segments.length - 1).toString()] || [];
for (const entry of list) {
let i = 1;
let copy = [...segments];
for (i; i < segments.length; i++) {
if (Array.isArray(entry[i - 1])) {
copy[i] = entry[i - 1];
continue;
}
else if (entry[i - 1] !== segments[i])
break;
}
if (i === segments.length)
return copy.join('/');
}
}
exports.getPathName = getPathName;
/**
* API Client
*/
class API {
constructor({ baseURL, authentication } = {}) {
this.baseURL = baseURL || baseURL_1.defaultBaseURL;
this.authentication = authentication || {};
}
/**
* Generate authentication options.
*/
get auth() {
if (this.authentication.rauth) {
if (typeof this.authentication.rauth === 'string') {
return {
headers: {
'X-Session-Token': this.authentication.rauth
function createClient(config) {
const client = (0, openapi_fetch_1.default)(Object.assign({ baseUrl: "https://revolt.chat/api" }, config));
if ((config === null || config === void 0 ? void 0 : config.sessionToken) || (config === null || config === void 0 ? void 0 : config.botToken)) {
const authMiddleware = {
onRequest(_a) {
return __awaiter(this, arguments, void 0, function* ({ request }) {
if (config.sessionToken) {
request.headers.set("X-Session-Token", config.sessionToken);
}
};
}
}
else if (this.authentication.revolt) {
switch (typeof this.authentication.revolt) {
case 'string': {
return {
headers: {
'X-Bot-Token': this.authentication.revolt
}
};
}
case 'object': {
return {
headers: {
'X-Session-Token': this.authentication.revolt.token
}
};
}
}
}
return {};
if (config.botToken) {
request.headers.set("X-Bot-Token", config.botToken);
}
return request;
});
},
};
client.use(authMiddleware);
}
/**
* Generate config to pass through to API.
*/
get config() {
return Object.assign({ baseURL: this.baseURL }, this.auth);
}
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req(method, path, params, config) {
let query, body;
let named = getPathName(path);
// If we are aware of this route, then match the parameters given.
if (named && typeof params === 'object') {
const route = params_1.queryParams[named];
const allowed_query = route[method];
// Map each parameter to the correct object.
for (const parameter of Object.keys(params)) {
if (allowed_query === null || allowed_query === void 0 ? void 0 : allowed_query.includes(parameter)) {
query = Object.assign(Object.assign({}, (query || {})), { [parameter]: params[parameter] });
}
else {
body = Object.assign(Object.assign({}, (body || {})), { [parameter]: params[parameter] });
}
}
}
return (0, axios_1.default)(path, (0, lodash_defaultsdeep_1.default)({
method,
params: query,
data: body
}, (0, lodash_defaultsdeep_1.default)(config, this.config)))
.then(res => res.data);
}
get(path, params, config) {
// @ts-ignore-next-line
return this.req('get', path, params, config);
}
patch(path, params, config) {
// @ts-ignore-next-line
return this.req('patch', path, params, config);
}
put(path, params, config) {
// @ts-ignore-next-line
return this.req('put', path, params, config);
}
delete(path, params, config) {
// @ts-ignore-next-line
return this.req('delete', path, params, config);
}
post(path, params, config) {
// @ts-ignore-next-line
return this.req('post', path, params, config);
}
return client;
}
exports.API = API;

@@ -1,176 +0,19 @@

import type { AxiosRequestConfig } from 'axios';
export * from './types';
import type { APIRoutes } from './routes';
declare type Methods = APIRoutes['method'];
declare type PickRoutes<Method extends Methods> = APIRoutes & {
method: Method;
};
declare type GetRoutes = PickRoutes<'get'>;
declare type PatchRoutes = PickRoutes<'patch'>;
declare type PutRoutes = PickRoutes<'put'>;
declare type DeleteRoutes = PickRoutes<'delete'>;
declare type PostRoutes = PickRoutes<'post'>;
declare type Count<Str extends string, SubStr extends string, Matches extends null[] = []> = Str extends `${infer _}${SubStr}${infer After}` ? Count<After, SubStr, [...Matches, null]> : Matches['length'];
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
*/
export declare function getPathName(anyPath: string): string | undefined;
/**
* Client configuration options
*/
export interface Options {
import { ClientOptions } from "openapi-fetch";
import type { paths } from "./api.js";
export type * from "./types.js";
export type FetchConfiguration = ClientOptions & {
/**
* Base URL of the Revolt node
* Specify a bot token to authenticate with Revolt
*/
baseURL: string;
botToken?: string;
/**
* Authentication used for requests
* Specify a session token to authenticate with Revolt
*/
authentication: {
rauth?: string | undefined;
revolt?: {
token: string;
} | string | undefined;
};
}
sessionToken?: string;
};
/**
* API Client
* Create a new Fetch client for the API
* @param config Configuration
* @returns Fetch client
*/
export declare class API {
private baseURL;
private authentication;
constructor({ baseURL, authentication }?: Partial<Options>);
/**
* Generate authentication options.
*/
get auth(): AxiosRequestConfig;
/**
* Generate config to pass through to API.
*/
get config(): AxiosRequestConfig;
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req<Method extends Methods, Routes extends PickRoutes<Method>, Path extends Routes['path'], Route extends Routes & {
path: Path;
parts: Count<Path, '/'>;
}>(method: Method, path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
get<Path extends GetRoutes['path'], Route extends GetRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @returns Typed Response Data
*/
get<Path extends (GetRoutes & {
params: undefined;
})['path'], Route extends GetRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
patch<Path extends PatchRoutes['path'], Route extends PatchRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @returns Typed Response Data
*/
patch<Path extends (PatchRoutes & {
params: undefined;
})['path'], Route extends PatchRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
put<Path extends PutRoutes['path'], Route extends PutRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @returns Typed Response Data
*/
put<Path extends (PutRoutes & {
params: undefined;
})['path'], Route extends PutRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
delete<Path extends DeleteRoutes['path'], Route extends DeleteRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params?: any, config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @returns Typed Response Data
*/
delete<Path extends (DeleteRoutes & {
params: undefined;
})['path'], Route extends DeleteRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params?: any): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
post<Path extends PostRoutes['path'], Route extends PostRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @returns Typed Response Data
*/
post<Path extends (PostRoutes & {
params: undefined;
})['path'], Route extends PostRoutes & {
path: Path;
parts: Count<Path, '/'>;
}>(path: Path): Promise<Route['response']>;
}
export declare function createClient(config?: FetchConfiguration): import("openapi-fetch").Client<paths, `${string}/${string}`>;

@@ -1,140 +0,27 @@

// This file was auto-generated by @insertish/oapi!
import Axios from 'axios';
import defaultsDeep from 'lodash.defaultsdeep';
export * from './types';
import { defaultBaseURL } from './baseURL';
import { pathResolve, queryParams } from './params';
import createFetchClient from "openapi-fetch";
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
* Create a new Fetch client for the API
* @param config Configuration
* @returns Fetch client
*/
export function getPathName(anyPath) {
const segments = anyPath.split('/');
const list = pathResolve[(segments.length - 1).toString()] || [];
for (const entry of list) {
let i = 1;
let copy = [...segments];
for (i; i < segments.length; i++) {
if (Array.isArray(entry[i - 1])) {
copy[i] = entry[i - 1];
continue;
}
else if (entry[i - 1] !== segments[i])
break;
}
if (i === segments.length)
return copy.join('/');
}
}
/**
* API Client
*/
export class API {
baseURL;
authentication;
constructor({ baseURL, authentication } = {}) {
this.baseURL = baseURL || defaultBaseURL;
this.authentication = authentication || {};
}
/**
* Generate authentication options.
*/
get auth() {
if (this.authentication.rauth) {
if (typeof this.authentication.rauth === 'string') {
return {
headers: {
'X-Session-Token': this.authentication.rauth
}
};
}
}
else if (this.authentication.revolt) {
switch (typeof this.authentication.revolt) {
case 'string': {
return {
headers: {
'X-Bot-Token': this.authentication.revolt
}
};
export function createClient(config) {
const client = createFetchClient({
baseUrl: "https://revolt.chat/api",
...config,
});
if (config?.sessionToken || config?.botToken) {
const authMiddleware = {
async onRequest({ request }) {
if (config.sessionToken) {
request.headers.set("X-Session-Token", config.sessionToken);
}
case 'object': {
return {
headers: {
'X-Session-Token': this.authentication.revolt.token
}
};
if (config.botToken) {
request.headers.set("X-Bot-Token", config.botToken);
}
}
}
return {};
}
/**
* Generate config to pass through to API.
*/
get config() {
return {
baseURL: this.baseURL,
...this.auth,
return request;
},
};
client.use(authMiddleware);
}
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req(method, path, params, config) {
let query, body;
let named = getPathName(path);
// If we are aware of this route, then match the parameters given.
if (named && typeof params === 'object') {
const route = queryParams[named];
const allowed_query = route[method];
// Map each parameter to the correct object.
for (const parameter of Object.keys(params)) {
if (allowed_query?.includes(parameter)) {
query = {
...(query || {}),
[parameter]: params[parameter]
};
}
else {
body = {
...(body || {}),
[parameter]: params[parameter]
};
}
}
}
return Axios(path, defaultsDeep({
method,
params: query,
data: body
}, defaultsDeep(config, this.config)))
.then(res => res.data);
}
get(path, params, config) {
// @ts-ignore-next-line
return this.req('get', path, params, config);
}
patch(path, params, config) {
// @ts-ignore-next-line
return this.req('patch', path, params, config);
}
put(path, params, config) {
// @ts-ignore-next-line
return this.req('put', path, params, config);
}
delete(path, params, config) {
// @ts-ignore-next-line
return this.req('delete', path, params, config);
}
post(path, params, config) {
// @ts-ignore-next-line
return this.req('post', path, params, config);
}
return client;
}
{
"name": "revolt-api",
"version": "0.7.15",
"version": "0.7.16-next.1",
"description": "Revolt API Library",

@@ -12,15 +12,15 @@ "main": "dist/index.js",

"scripts": {
"build": "REWRITE_ANYOF=1 oapilib && tsc && tsc -p tsconfig.esm.json",
"gen": "REWRITE_ANYOF=1 openapi-typescript ./OpenAPI.json -o ./src/api.d.ts && node codegen.js",
"build": "rimraf dist esm && tsc && tsc -p tsconfig.esm.json",
"typecheck": "tsc --noEmit",
"prepublish": "in-publish && yarn build || echo Skipping build."
},
"devDependencies": {
"@insertish/oapi": "0.1.18",
"@types/lodash.defaultsdeep": "^4.6.6",
"in-publish": "^2.0.1",
"openapi-typescript": "^5.2.0",
"typescript": "^4.6.2"
"openapi-typescript": "^7.4.0",
"rimraf": "^6.0.1",
"typescript": "^5.5.4"
},
"dependencies": {
"axios": "^0.26.1",
"lodash.defaultsdeep": "^4.6.1"
"openapi-fetch": "^0.12.0"
},

@@ -31,2 +31,3 @@ "files": [

"esm",
"codegen.js",
"OpenAPI.json",

@@ -36,2 +37,2 @@ "LICENSE",

]
}
}

@@ -5,3 +5,3 @@ # Revolt API

This package contains typings for objects in the [Revolt API](https://developers.revolt.chat/api/) and a fully typed API request builder.
This package contains typings for objects in the [Revolt API](https://developers.revolt.chat/api/) and a fully typed API request builder using [openapi-fetch](https://openapi-ts.dev).

@@ -13,3 +13,3 @@ ### Example Usage

```typescript
import type { User } from 'revolt-api';
import type { User } from "revolt-api";
```

@@ -20,23 +20,27 @@

```typescript
import { API } from 'revolt-api';
import { createClient } from "./esm/index.js";
// Initialise a new API client:
const client = new API();
const api = createClient({
// specify bot token:
botToken: "bot-token",
// .. or a user session token:
sessionToken: "session-token",
// .. also accepts options from openapi-fetch
// such as custom middleware, baseURL, etc
});
// or with authentication:
const client = new API({ authentication: { revolt: 'bot-token' } });
// Fetch information about user
api.GET("/users/@me").then((res) => console.info(res.data));
// Make requests with ease:
client.get('/users/@me')
// Fully typed responses!
.then(user => user.username);
// No need to worry about the details:
let channel_id = "some channel id";
client.post(`/channels/${channel_id}/messages`, {
// Parameters given are fully typed as well!
content: "some content"
// Send a message to a channel
api.POST("/channels/{target}/messages", {
params: {
path: {
target: "01F92C5ZXBQWQ8KY7J8KY917NM",
},
},
body: {
content: "Hello from Fetch/Node.js/Bun/Deno!",
},
});
```
For more details on how this works, see the [README of @insertish/oapi](https://github.com/insertish/oapi#example).

@@ -1,271 +0,48 @@

// This file was auto-generated by @insertish/oapi!
import Axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import createFetchClient, { ClientOptions, Middleware } from "openapi-fetch";
import type { paths } from "./api.js";
import defaultsDeep from 'lodash.defaultsdeep';
export type * from "./types.js";
export * from './types';
import type { APIRoutes } from './routes';
export type FetchConfiguration = ClientOptions & {
/**
* Specify a bot token to authenticate with Revolt
*/
botToken?: string;
import { defaultBaseURL } from './baseURL';
import { pathResolve, queryParams } from './params';
/**
* Specify a session token to authenticate with Revolt
*/
sessionToken?: string;
};
type Methods = APIRoutes['method'];
type PickRoutes<Method extends Methods> = APIRoutes & { method: Method };
type GetRoutes = PickRoutes<'get'>;
type PatchRoutes = PickRoutes<'patch'>;
type PutRoutes = PickRoutes<'put'>;
type DeleteRoutes = PickRoutes<'delete'>;
type PostRoutes = PickRoutes<'post'>;
type Count<Str extends string, SubStr extends string, Matches extends null[] = []> =
Str extends `${infer _}${SubStr}${infer After}` ? Count<After, SubStr, [...Matches, null]> : Matches['length'];
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
* Create a new Fetch client for the API
* @param config Configuration
* @returns Fetch client
*/
export function getPathName(anyPath: string) {
const segments = anyPath.split('/');
export function createClient(config?: FetchConfiguration) {
const client = createFetchClient<paths>({
baseUrl: "https://revolt.chat/api",
...config,
});
const list = (pathResolve as unknown as Record<string, (string | [string])[]>)[(segments.length - 1).toString()] || [];
for (const entry of list) {
let i = 1;
let copy = [...segments];
for (i;i<segments.length;i++) {
if (Array.isArray(entry[i - 1])) {
copy[i] = entry[i - 1];
continue;
}
else if (entry[i - 1] !== segments[i]) break;
if (config?.sessionToken || config?.botToken) {
const authMiddleware: Middleware = {
async onRequest({ request }) {
if (config.sessionToken) {
request.headers.set("X-Session-Token", config.sessionToken);
}
if (i === segments.length) return copy.join('/');
}
}
if (config.botToken) {
request.headers.set("X-Bot-Token", config.botToken);
}
/**
* Client configuration options
*/
export interface Options {
/**
* Base URL of the Revolt node
*/
baseURL: string;
/**
* Authentication used for requests
*/
authentication: {
rauth?: string | undefined;
revolt?: { token: string } | string | undefined;
return request;
},
};
}
/**
* API Client
*/
export class API {
private baseURL: Options['baseURL'];
private authentication: Options['authentication'];
client.use(authMiddleware);
}
constructor({ baseURL, authentication }: Partial<Options> = { }) {
this.baseURL = baseURL || defaultBaseURL;
this.authentication = authentication || { };
}
/**
* Generate authentication options.
*/
get auth(): AxiosRequestConfig {
if (this.authentication.rauth) {
if (typeof this.authentication.rauth === 'string') {
return {
headers: {
'X-Session-Token': this.authentication.rauth
}
}
}
} else if (this.authentication.revolt) {
switch (typeof this.authentication.revolt) {
case 'string': {
return {
headers: {
'X-Bot-Token': this.authentication.revolt
}
}
}
case 'object': {
return {
headers: {
'X-Session-Token': this.authentication.revolt.token
}
}
}
}
}
return { };
}
/**
* Generate config to pass through to API.
*/
get config(): AxiosRequestConfig {
return {
baseURL: this.baseURL,
...this.auth,
};
}
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req<Method extends Methods, Routes extends PickRoutes<Method>, Path extends Routes['path'], Route extends Routes & { path: Path, parts: Count<Path, '/'> }>(method: Method, path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']> {
let query, body;
let named = getPathName(path);
// If we are aware of this route, then match the parameters given.
if (named && typeof params === 'object') {
const route = queryParams[named as keyof typeof queryParams];
const allowed_query = (route as unknown as Record<Method, string[]>)[method];
// Map each parameter to the correct object.
for (const parameter of Object.keys(params)) {
if (allowed_query?.includes(parameter)) {
query = {
...(query || {}),
[parameter]: (params as Record<any, any>)[parameter]
};
} else {
body = {
...(body || {}),
[parameter]: (params as Record<any, any>)[parameter]
};
}
}
}
return Axios(path, defaultsDeep({
method,
params: query,
data: body
}, defaultsDeep(
config,
this.config
)))
.then(res => res.data);
}
/**
* Send HTTP GET request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
get<Path extends GetRoutes['path'], Route extends GetRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @returns Typed Response Data
*/
get<Path extends (GetRoutes & { params: undefined })['path'], Route extends GetRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
get(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('get', path, params, config);
}
/**
* Send HTTP PATCH request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
patch<Path extends PatchRoutes['path'], Route extends PatchRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @returns Typed Response Data
*/
patch<Path extends (PatchRoutes & { params: undefined })['path'], Route extends PatchRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
patch(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('patch', path, params, config);
}
/**
* Send HTTP PUT request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
put<Path extends PutRoutes['path'], Route extends PutRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @returns Typed Response Data
*/
put<Path extends (PutRoutes & { params: undefined })['path'], Route extends PutRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
put(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('put', path, params, config);
}
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
delete<Path extends DeleteRoutes['path'], Route extends DeleteRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params?: any, config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @returns Typed Response Data
*/
delete<Path extends (DeleteRoutes & { params: undefined })['path'], Route extends DeleteRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params?: any): Promise<Route['response']>;
delete(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('delete', path, params, config);
}
/**
* Send HTTP POST request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
post<Path extends PostRoutes['path'], Route extends PostRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @returns Typed Response Data
*/
post<Path extends (PostRoutes & { params: undefined })['path'], Route extends PostRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
post(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('post', path, params, config);
}
return client;
}

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc