1 Commits

Author SHA1 Message Date
0d24ecca3f Generate api with NSwag 2024-07-23 20:29:30 -03:00
23 changed files with 1847 additions and 4562 deletions

View File

@ -1 +0,0 @@
src/api.generated.ts

View File

@ -1,16 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT AND Apache-2.0
import dotenv from "dotenv";
import { TribufuApi } from "../build/index.mjs";
dotenv.config();
async function main() {
const tribufu = TribufuApi.fromEnv();
console.log(
await tribufu.getServerByAddressAndQueryPort("mine.tribufu.com", 25565),
);
}
main();

View File

@ -1,14 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT AND Apache-2.0
import dotenv from "dotenv";
import { TribufuClient } from "../build/index.mjs";
dotenv.config();
async function main() {
const tribufu = TribufuClient.fromEnv();
console.log(await tribufu.getClientInfo());
}
main();

13
examples/openid.js Normal file
View File

@ -0,0 +1,13 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import dotenv from 'dotenv';
import { TribufuClient } from '../build/index.mjs';
async function main() {
const client = new TribufuClient();
const config = await client.openidConfiguration();
console.log(config);
}
main();

View File

@ -1,6 +1,6 @@
{
"name": "tribufu",
"version": "1.0.0",
"version": "0.1.17",
"description": "Tribufu JS SDK",
"repository": "https://github.com/Tribufu/TribufuJs",
"author": "Tribufu <contact@Tribufu.com>",
@ -9,28 +9,22 @@
"types": "./build/index.d.ts",
"exports": {
"import": "./build/index.mjs",
"require": "./build/index.cjs",
"types": "./build/index.d.ts"
},
"typesVersions": {
"*": {
"*": [
"./build/*"
]
}
"require": "./build/index.cjs"
},
"scripts": {
"clean": "rimraf build",
"build": "npm run clean && tsc && node scripts/esbuild.js"
},
"dependencies": {},
"dependencies": {
"@tribufu/mintaka": "0.1.8",
"axios": "^1.7.2"
},
"devDependencies": {
"@types/node": "^20.10.6",
"cross-env": "^7.0.3",
"dotenv": "^16.3.1",
"esbuild": "^0.19.10",
"esbuild-node-externals": "^1.12.0",
"eslint": "9.11.1",
"prettier": "3.3.3",
"rimraf": "^5.0.5",
"typescript": "^5.3.3"
}

1475
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -22,26 +22,12 @@ const moduleConfig = {
format: "esm",
};
const moduleMinConfig = {
...moduleConfig,
outfile: "build/index.min.mjs",
minify: true,
sourcemap: true,
};
const legacyConfig = {
...baseConfig,
outfile: "build/index.cjs",
format: "cjs",
};
const legacyMinConfig = {
...legacyConfig,
outfile: "build/index.min.cjs",
minify: true,
sourcemap: true,
};
async function addCopyrightHeader(filename) {
const header = `// Copyright (c) Tribufu. All Rights Reserved.\n// SPDX-License-Identifier: MIT\n\n`;
const content = await fs.readFile(filename, 'utf-8');
@ -58,8 +44,5 @@ async function buildAndAddHeader(config) {
}
};
await buildAndAddHeader(legacyConfig);
await buildAndAddHeader(moduleConfig);
//await buildAndAddHeader(legacyMinConfig);
//await buildAndAddHeader(moduleMinConfig);
await buildAndAddHeader(legacyConfig);

View File

@ -1,3 +0,0 @@
#!/usr/bin/env sh
nswag run ./src/api/api.nswag

1248
src/api.generated.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,104 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: UNLICENSED
import { HttpHeaders } from "../http/headers";
import { JavaScriptRuntime } from "../node";
import { TRIBUFU_VERSION } from "..";
export abstract class TribufuApiBase {
protected apiKey: string | null = null;
/**
* Check if debug mode is enabled.
*
* - Debug mode is enabled if the environment variable `NODE_ENV` is set to `development`.
* - Debug mode is disabled by default.
* - Debug mode is disabled in the browser.
*
* @returns boolean
*/
public static debugEnabled(): boolean {
if (typeof process !== "undefined") {
return process.env.NODE_ENV === "development";
}
return false;
}
/**
* Detect the current JavaScript runtime.
*
* - This is used to determine if the code is running in a browser or in Node.js.
*
* @returns JavaScriptRuntime
*/
public static detectRuntime(): JavaScriptRuntime {
if (typeof window !== "undefined") {
return JavaScriptRuntime.Browser;
}
if (typeof process !== "undefined" && process?.versions?.node) {
return JavaScriptRuntime.Node;
}
return JavaScriptRuntime.Other;
}
/**
* Check if the current JavaScript runtime is a browser.
* @returns boolean
*/
public static isBrowser(): boolean {
return TribufuApiBase.detectRuntime() === JavaScriptRuntime.Browser;
}
/**
* Check if the current JavaScript runtime is Node.js.
* @returns boolean
*/
public static isNode(): boolean {
return TribufuApiBase.detectRuntime() === JavaScriptRuntime.Node;
}
/**
* Get the default headers for the Tribufu API.
* @returns HeaderMap
*/
protected static defaultHeaders(): HttpHeaders {
const headers = {};
headers["X-Tribufu-Library"] = "javascript";
headers["X-Tribufu-Version"] = TRIBUFU_VERSION;
return headers;
}
/**
* Get current headers with the api key or access token.
* @returns HeaderMap
*/
protected getHeaders(): HttpHeaders {
let headers = TribufuApiBase.defaultHeaders();
if (this.apiKey) {
headers["Authorization"] = `ApiKey ${this.apiKey}`;
return headers;
}
return headers;
}
/**
* Transform the options before sending the request.
* @param options
* @returns
*/
protected transformOptions(options: RequestInit) {
if (this.apiKey) {
options.headers = {
...options.headers,
...this.getHeaders(),
};
}
return Promise.resolve(options);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
import { TribufuApiBase } from "./api.base";

View File

@ -1,74 +0,0 @@
{
"runtime": "Default",
"defaultVariables": null,
"documentGenerator": {
"fromDocument": {
"json": "",
"url": "http://localhost:5000/v1/openapi.json",
"output": null,
"newLineBehavior": "Auto"
}
},
"codeGenerators": {
"openApiToTypeScriptClient": {
"className": "TribufuApiGenerated",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 4.3,
"template": "Fetch",
"promiseType": "Promise",
"httpClass": "HttpClient",
"withCredentials": false,
"useSingletonProvider": false,
"injectionTokenType": "OpaqueToken",
"rxJsVersion": 6,
"dateTimeType": "String",
"nullValue": "Null",
"generateClientClasses": true,
"generateClientInterfaces": false,
"generateOptionalParameters": true,
"exportTypes": true,
"wrapDtoExceptions": false,
"exceptionClass": "TribufuApiError",
"clientBaseClass": "TribufuApiBase",
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"protectedMethods": [],
"configurationClass": null,
"useTransformOptionsMethod": true,
"useTransformResultMethod": false,
"generateDtoTypes": true,
"operationGenerationMode": "SingleClientFromOperationId",
"markOptionalProperties": false,
"generateCloneMethod": false,
"typeStyle": "Interface",
"enumStyle": "Enum",
"useLeafType": false,
"classTypes": [],
"extendedClasses": [],
"extensionCode": "api.include.ts",
"generateDefaultValues": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"handleReferences": false,
"generateTypeCheckFunctions": false,
"generateConstructorInterface": true,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"useAbortSignal": false,
"inlineNamedDictionaries": false,
"inlineNamedAny": false,
"includeHttpContext": false,
"templateDirectory": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "api.generated.ts",
"newLineBehavior": "LF"
}
}
}

View File

@ -1,133 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import { TribufuApi } from ".";
import { GrantType, TokenHintType } from "./generated";
/**
* **Tribufu Client**
*
* Use this class to interact with Tribufu OAuth service.
*/
export class TribufuClient extends TribufuApi {
private clientId: string | null = null;
private clientSecret: string | null = null;
private accessToken: string | null = null;
private refreshToken: string | null = null;
private expiresIn: number = 0;
constructor(clientId: string, clientSecret: string) {
if (!clientId || !clientSecret) {
throw new Error("ClientId and ClientSecret are required");
}
super({ credentials: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}` });
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/**
* Try to create a TribufuClient from environment variables.
*
* - This will only work if the environment variables are set.
*
* @param prefix A prefix for the environment variables. Default is `TRIBUFU`.
* @returns TribufuClient | null
* @example
* ```ts
* // process.env.TRIBUFU_CLIENT_ID
* // process.env.TRIBUFU_CLIENT_SECRET
* const client = TribufuClient.fromEnv();
* ```
*/
public static fromEnv(prefix?: string | null): TribufuApi | null {
if (typeof process === "undefined") {
return null;
}
const clientId = process.env[`${prefix || "TRIBUFU"}_CLIENT_ID`];
const clientSecret = process.env[`${prefix || "TRIBUFU"}_CLIENT_SECRET`];
if (clientId && clientSecret) {
return new TribufuClient(clientId, clientSecret);
}
return null;
}
private useClientCredentials(): void {
if (this.clientId && this.clientSecret) {
this.credentials = `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64")}`;
}
}
private useBearerCredentials(): void {
if (this.accessToken) {
this.credentials = `Bearer ${this.accessToken}`;
}
}
public async login(username: string, password: string): Promise<boolean> {
this.useClientCredentials();
const response = await this.createToken({
grant_type: GrantType.Password,
code: null,
username,
password,
refresh_token: null,
client_id: this.clientId,
redirect_uri: null,
code_verifier: null,
});
if (response) {
this.accessToken = response.access_token;
this.refreshToken = response.refresh_token;
this.expiresIn = response.expires_in;
this.useBearerCredentials();
}
return !!response;
}
public async refresh(): Promise<boolean> {
this.useClientCredentials();
const response = await this.createToken({
grant_type: GrantType.Refresh_token,
code: null,
username: null,
password: null,
refresh_token: this.refreshToken,
client_id: this.clientId,
redirect_uri: null,
code_verifier: null,
});
if (response) {
this.accessToken = response.access_token;
this.refreshToken = response.refresh_token;
this.expiresIn = response.expires_in;
this.useBearerCredentials();
}
return !!response;
}
public logout(): Promise<any> {
this.useClientCredentials();
const response = this.revokeToken({
token: this.refreshToken,
token_type_hint: TokenHintType.Refresh_token,
});
this.accessToken = null;
this.refreshToken = null;
this.expiresIn = 0;
return response;
}
}

View File

@ -1,105 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import { TRIBUFU_API_URL } from "..";
import { TribufuApiBase } from "./api.base";
import { TribufuApiGenerated } from "./api.generated";
import { TribufuApiOptions } from "../options";
/**
* **Tribufu API**
*
* Use this class to interact with the Tribufu API.
*/
export class TribufuApi extends TribufuApiGenerated {
constructor(options?: TribufuApiOptions | null) {
const baseUrl = options?.baseUrl || TribufuApi.getBaseUrl();
const http = options?.fetch ? { fetch: options.fetch } : { fetch };
super(baseUrl, http);
this.apiKey = options?.apiKey || null;
}
/**
* Create a TribufuApi with the default options.
* @returns
*/
public static default(): TribufuApi {
return new TribufuApi();
}
/**
* Create a TribufuApi with the given api key.
*
* - A api key give you public read only access to the Tribufu API.
*
* @param apiKey
* @returns TribufuApi
*/
public static withApiKey(apiKey: string): TribufuApi {
return new TribufuApi({ apiKey });
}
/**
* Try to create a TribufuApi from environment variables.
*
* - This will only work if the environment variables are set.
*
* @param prefix A prefix for the environment variables. Default is `TRIBUFU`.
* @returns TribufuApi | null
* @example
* ```ts
* // process.env.TRIBUFU_API_KEY
* const api = TribufuApi.fromEnv();
* ```
*/
public static fromEnv(prefix?: string | null): TribufuApi | null {
if (typeof process === "undefined") {
return null;
}
const apiKey = process.env[`${prefix || "TRIBUFU"}_API_KEY`];
if (apiKey) {
return TribufuApi.withApiKey(apiKey);
}
return null;
}
/**
* Create a TribufuApi from environment variables or the default api.
*
* - This will fallback to the default api if the environment variables are not set.
*
* @param prefix A prefix for the environment variables. Default is `TRIBUFU`.
* @returns TribufuApi | null
* @example
* ```ts
* // process.env.TRIBUFU_API_KEY = null
* const api = TribufuApi.fromEnvOrDefault();
* ```
*/
public static fromEnvOrDefault(prefix: string = ""): TribufuApi {
return TribufuApi.fromEnv(prefix) || TribufuApi.default();
}
/**
* Get the base url for the Tribufu API.
*
* - The base url can be set using the environment variable `TRIBUFU_API_URL`.
* - The custom base url is only used if debug mode is enabled.
* - The default base url is `https://api.tribufu.com`.
*
* @returns string
*/
protected static getBaseUrl(): string {
if (typeof process === "undefined") {
return TRIBUFU_API_URL;
}
const baseUrl = process.env[`TRIBUFU_API_URL`] || null;
return TribufuApiBase.debugEnabled() && baseUrl
? baseUrl
: TRIBUFU_API_URL;
}
}

View File

@ -1,23 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import { TribufuApi } from "./index";
/**
* **Tribufu API**
*
* Helper class to get a singleton instance of the Tribufu API.
*/
export class TribufuApiSingleton {
private static INSTANCE: TribufuApi | null = null;
private constructor() {}
public static getInstance(): TribufuApi {
if (!TribufuApiSingleton.INSTANCE) {
TribufuApiSingleton.INSTANCE = TribufuApi.fromEnvOrDefault();
}
return TribufuApiSingleton.INSTANCE;
}
}

10
src/client.ts Normal file
View File

@ -0,0 +1,10 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import { TribufuApi } from "./api.generated";
export class TribufuClient extends TribufuApi {
constructor() {
super("http://localhost:5000", { fetch });
}
}

View File

@ -1,29 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import packageJson from "../package.json";
/**
* The version of the Tribufu SDK.
*/
export const TRIBUFU_VERSION: string = packageJson.version;
/**
* The default Tribufu WEB URL.
*/
export const TRIBUFU_WEB_URL: string = "https://www.tribufu.com";
/**
* The default Tribufu API URL.
*/
export const TRIBUFU_API_URL: string = "https://api.tribufu.com";
/**
* The default Tribufu CDN URL.
*/
export const TRIBUFU_CDN_URL: string = "https://cdn.tribufu.com";
/**
* Tribufu copyright notice.
*/
export const TRIBUFU_COPYRIGHT = `© ${new Date().getFullYear()} Tribufu.`;

View File

@ -1,11 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
/**
* Http Headers
*
* Helper type to represent HTTP headers.
*/
export type HttpHeaders = {
[key: string]: string;
};

View File

@ -1,31 +1,8 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
import {
TRIBUFU_API_URL,
TRIBUFU_CDN_URL,
TRIBUFU_VERSION,
TRIBUFU_WEB_URL,
} from "./constants";
import { TribufuApi } from "./api";
import { TribufuApiOptions } from "./options";
import { TribufuApiSingleton } from "./api/singletion";
import { TribufuClient } from "./client";
export {
TRIBUFU_API_URL,
TRIBUFU_CDN_URL,
TRIBUFU_VERSION,
TRIBUFU_WEB_URL,
TribufuApi,
TribufuApiOptions,
TribufuApiSingleton,
TribufuClient,
};
export * from "./api/api.base";
export * from "./api/api.generated";
export * from "./api/api.include";
export * from "./api/index";
export * from "./api/singletion";
export * from "./http/headers";
export * from "./node";

View File

@ -1,8 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
export enum JavaScriptRuntime {
Browser,
Node,
Other,
}

View File

@ -1,8 +0,0 @@
// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
export interface TribufuApiOptions {
baseUrl?: string;
apiKey?: string;
fetch?: (url: RequestInfo, init?: RequestInit) => Promise<Response>;
}

View File

@ -1,13 +1,12 @@
{
"compilerOptions": {
"strict": true,
"target": "esnext",
"target": "ESNext",
"declaration": true,
"emitDeclarationOnly": true,
"noImplicitAny": false,
"moduleResolution": "Node",
"esModuleInterop": true,
"module": "esnext",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"rootDir": "src",