You've already forked AstralRinth
forked from didirus/AstralRinth
feat: base api-client impl (#4694)
* feat: base api-client impl * fix: doc * feat: start work on module stuff * feat: migrate v2/v3 projects into module system * fix: lint & README.md contributing * refactor: remove utils old api client prototype * fix: lint * fix: api url issues * fix: baseurl in error.vue * fix: readme * fix typo in readme * Update apps/frontend/src/providers/api-client.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> * Update packages/api-client/src/features/verbose-logging.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> * Update packages/api-client/src/features/retry.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> --------- Signed-off-by: Calum H. <hendersoncal117@gmail.com> Co-authored-by: Prospector <6166773+Prospector@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
310
packages/api-client/src/core/abstract-client.ts
Normal file
310
packages/api-client/src/core/abstract-client.ts
Normal file
@@ -0,0 +1,310 @@
|
||||
import type { InferredClientModules } from '../modules'
|
||||
import { buildModuleStructure } from '../modules'
|
||||
import type { ClientConfig } from '../types/client'
|
||||
import type { RequestContext, RequestOptions } from '../types/request'
|
||||
import type { AbstractFeature } from './abstract-feature'
|
||||
import type { AbstractModule } from './abstract-module'
|
||||
import { ModrinthApiError, ModrinthServerError } from './errors'
|
||||
|
||||
/**
|
||||
* Abstract base client for Modrinth APIs
|
||||
*/
|
||||
export abstract class AbstractModrinthClient {
|
||||
protected config: ClientConfig
|
||||
protected features: AbstractFeature[]
|
||||
|
||||
/**
|
||||
* Maps full module ID (e.g., 'labrinth_projects_v2') to instantiated module
|
||||
*/
|
||||
private _moduleInstances: Map<string, AbstractModule> = new Map()
|
||||
|
||||
/**
|
||||
* Maps API name (e.g., 'labrinth') to namespace object
|
||||
*/
|
||||
private _moduleNamespaces: Map<string, Record<string, AbstractModule>> = new Map()
|
||||
|
||||
// TODO: When adding kyros/archon add readonly fields for those too.
|
||||
public readonly labrinth!: InferredClientModules['labrinth']
|
||||
|
||||
constructor(config: ClientConfig) {
|
||||
this.config = {
|
||||
timeout: 10000,
|
||||
labrinthBaseUrl: 'https://api.modrinth.com',
|
||||
archonBaseUrl: 'https://archon.modrinth.com',
|
||||
...config,
|
||||
}
|
||||
this.features = config.features ?? []
|
||||
this.initializeModules()
|
||||
}
|
||||
|
||||
/**
|
||||
* This creates the nested API structure (e.g., client.labrinth.projects_v2)
|
||||
* but doesn't instantiate modules until first access
|
||||
*
|
||||
* Module IDs in the registry are validated at runtime to ensure they match
|
||||
* what the module declares via getModuleID().
|
||||
*/
|
||||
private initializeModules(): void {
|
||||
const structure = buildModuleStructure()
|
||||
|
||||
for (const [api, modules] of Object.entries(structure)) {
|
||||
const namespaceObj: Record<string, AbstractModule> = {}
|
||||
|
||||
// Define lazy getters for each module
|
||||
for (const [moduleName, ModuleConstructor] of Object.entries(modules)) {
|
||||
const fullModuleId = `${api}_${moduleName}`
|
||||
|
||||
Object.defineProperty(namespaceObj, moduleName, {
|
||||
get: () => {
|
||||
// Lazy instantiation
|
||||
if (!this._moduleInstances.has(fullModuleId)) {
|
||||
const instance = new ModuleConstructor(this)
|
||||
|
||||
// Validate the module ID matches what we expect
|
||||
const declaredId = instance.getModuleID()
|
||||
if (declaredId !== fullModuleId) {
|
||||
throw new Error(
|
||||
`Module ID mismatch: registry expects "${fullModuleId}" but module declares "${declaredId}"`,
|
||||
)
|
||||
}
|
||||
|
||||
this._moduleInstances.set(fullModuleId, instance)
|
||||
}
|
||||
return this._moduleInstances.get(fullModuleId)!
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
})
|
||||
}
|
||||
|
||||
// Assign namespace to client (e.g., this.labrinth = namespaceObj)
|
||||
// defineProperty bypasses readonly restriction
|
||||
Object.defineProperty(this, api, {
|
||||
value: namespaceObj,
|
||||
writable: false,
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
})
|
||||
|
||||
this._moduleNamespaces.set(api, namespaceObj)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a request to the API
|
||||
*
|
||||
* @param path - API path (e.g., '/project/sodium')
|
||||
* @param options - Request options
|
||||
* @returns Promise resolving to the response data
|
||||
* @throws {ModrinthApiError} When the request fails or features throw errors
|
||||
*/
|
||||
async request<T>(path: string, options: RequestOptions): Promise<T> {
|
||||
let baseUrl: string
|
||||
if (options.api === 'labrinth') {
|
||||
baseUrl = this.config.labrinthBaseUrl!
|
||||
} else if (options.api === 'archon') {
|
||||
baseUrl = this.config.archonBaseUrl!
|
||||
} else {
|
||||
baseUrl = options.api
|
||||
}
|
||||
|
||||
const url = this.buildUrl(path, baseUrl, options.version)
|
||||
|
||||
// Merge options with defaults
|
||||
const mergedOptions: RequestOptions = {
|
||||
method: 'GET',
|
||||
timeout: this.config.timeout,
|
||||
...options,
|
||||
headers: {
|
||||
...this.buildDefaultHeaders(),
|
||||
...options.headers,
|
||||
},
|
||||
}
|
||||
|
||||
const context = this.buildContext(url, path, mergedOptions)
|
||||
|
||||
try {
|
||||
const result = await this.executeFeatureChain<T>(context)
|
||||
|
||||
await this.config.hooks?.onResponse?.(result, context)
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
const apiError = this.normalizeError(error, context)
|
||||
await this.config.hooks?.onError?.(apiError, context)
|
||||
|
||||
throw apiError
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the feature chain and the actual request
|
||||
*
|
||||
* Features are executed in order, with each feature calling next() to continue.
|
||||
* The last "feature" in the chain is the actual request execution.
|
||||
*/
|
||||
protected async executeFeatureChain<T>(context: RequestContext): Promise<T> {
|
||||
// Filter to only features that should apply
|
||||
const applicableFeatures = this.features.filter((feature) => feature.shouldApply(context))
|
||||
|
||||
// Build the feature chain
|
||||
// We work backwards from the actual request, wrapping each feature around the previous
|
||||
let index = applicableFeatures.length
|
||||
|
||||
const next = async (): Promise<T> => {
|
||||
index--
|
||||
|
||||
if (index >= 0) {
|
||||
// Execute the next feature in the chain
|
||||
const feature = applicableFeatures[index]
|
||||
return feature.execute(next, context)
|
||||
} else {
|
||||
// We've reached the end of the chain, execute the actual request
|
||||
await this.config.hooks?.onRequest?.(context)
|
||||
return this.executeRequest<T>(context.url, context.options)
|
||||
}
|
||||
}
|
||||
|
||||
return next()
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the full URL for a request
|
||||
*/
|
||||
protected buildUrl(path: string, baseUrl: string, version: number | 'internal'): string {
|
||||
// Remove trailing slash from base URL
|
||||
const base = baseUrl.replace(/\/$/, '')
|
||||
|
||||
// Build version path
|
||||
let versionPath = ''
|
||||
if (version === 'internal') {
|
||||
versionPath = '/_internal'
|
||||
} else if (typeof version === 'number') {
|
||||
versionPath = `/v${version}`
|
||||
}
|
||||
|
||||
const cleanPath = path.startsWith('/') ? path : `/${path}`
|
||||
|
||||
return `${base}${versionPath}${cleanPath}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request context
|
||||
*/
|
||||
protected buildContext(url: string, path: string, options: RequestOptions): RequestContext {
|
||||
return {
|
||||
url,
|
||||
path,
|
||||
options,
|
||||
attempt: 1,
|
||||
startTime: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build default headers for all requests
|
||||
*
|
||||
* Subclasses can override this to add platform-specific headers
|
||||
* (e.g., Nuxt rate limit key)
|
||||
*/
|
||||
protected buildDefaultHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...this.config.headers,
|
||||
}
|
||||
|
||||
if (this.config.userAgent) {
|
||||
headers['User-Agent'] = this.config.userAgent
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the actual HTTP request
|
||||
*
|
||||
* This must be implemented by platform-specific clients.
|
||||
*
|
||||
* @param url - Full URL to request
|
||||
* @param options - Request options
|
||||
* @returns Promise resolving to the response data
|
||||
* @throws {Error} Platform-specific errors that will be normalized by normalizeError()
|
||||
*/
|
||||
protected abstract executeRequest<T>(url: string, options: RequestOptions): Promise<T>
|
||||
|
||||
/**
|
||||
* Normalize an error into a ModrinthApiError
|
||||
*
|
||||
* Platform implementations should override this to handle platform-specific errors
|
||||
* (e.g., FetchError from ofetch, Tauri HTTP errors)
|
||||
*/
|
||||
protected normalizeError(error: unknown, context?: RequestContext): ModrinthApiError {
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return error
|
||||
}
|
||||
|
||||
return ModrinthApiError.fromUnknown(error, context?.path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a normalized error from extracted status code and response data
|
||||
*/
|
||||
protected createNormalizedError(
|
||||
error: Error,
|
||||
statusCode: number | undefined,
|
||||
responseData: unknown,
|
||||
): ModrinthApiError {
|
||||
if (statusCode && responseData) {
|
||||
return ModrinthServerError.fromResponse(statusCode, responseData)
|
||||
}
|
||||
|
||||
return new ModrinthApiError(error.message, {
|
||||
statusCode,
|
||||
originalError: error,
|
||||
responseData,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a feature to this client
|
||||
*
|
||||
* Features are executed in the order they are added.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new GenericModrinthClient()
|
||||
* client.addFeature(new AuthFeature({ token: 'mrp_...' }))
|
||||
* client.addFeature(new RetryFeature({ maxAttempts: 3 }))
|
||||
* ```
|
||||
*/
|
||||
addFeature(feature: AbstractFeature): this {
|
||||
this.features.push(feature)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a feature from this client
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const retryFeature = new RetryFeature({ maxAttempts: 3 })
|
||||
* client.addFeature(retryFeature)
|
||||
* // Later, remove it
|
||||
* client.removeFeature(retryFeature)
|
||||
* ```
|
||||
*/
|
||||
removeFeature(feature: AbstractFeature): this {
|
||||
const index = this.features.indexOf(feature)
|
||||
if (index !== -1) {
|
||||
this.features.splice(index, 1)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all features on this client
|
||||
*/
|
||||
getFeatures(): AbstractFeature[] {
|
||||
return [...this.features]
|
||||
}
|
||||
}
|
||||
91
packages/api-client/src/core/abstract-feature.ts
Normal file
91
packages/api-client/src/core/abstract-feature.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
/**
|
||||
* Base configuration for features
|
||||
*/
|
||||
export interface FeatureConfig {
|
||||
/**
|
||||
* Optional name for this feature (for debugging)
|
||||
*/
|
||||
name?: string
|
||||
|
||||
/**
|
||||
* Whether this feature is enabled
|
||||
* @default true
|
||||
*/
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract base class for request features
|
||||
*
|
||||
* Features are composable middleware that can intercept and modify requests.
|
||||
* They are executed in a chain, with each feature calling next() to continue the chain.
|
||||
*/
|
||||
export abstract class AbstractFeature {
|
||||
protected config: FeatureConfig
|
||||
|
||||
constructor(config?: FeatureConfig) {
|
||||
this.config = {
|
||||
enabled: true,
|
||||
...config,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the feature logic
|
||||
*
|
||||
* @param next - Function to call the next feature in the chain (or the actual request)
|
||||
* @param context - Full request context
|
||||
* @returns Promise resolving to the response data
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
* // Do something before request
|
||||
* console.log('Before request:', context.url)
|
||||
*
|
||||
* try {
|
||||
* const result = await next()
|
||||
*
|
||||
* // Do something after successful request
|
||||
* console.log('Request succeeded')
|
||||
*
|
||||
* return result
|
||||
* } catch (error) {
|
||||
* // Handle errors
|
||||
* console.error('Request failed:', error)
|
||||
* throw error
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
abstract execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T>
|
||||
|
||||
/**
|
||||
* Determine if this feature should apply to the given request
|
||||
*
|
||||
* By default, features apply if they are enabled.
|
||||
* Override this to add custom logic (e.g., only apply to GET requests).
|
||||
*
|
||||
* @param context - Request context
|
||||
* @returns true if the feature should execute, false to skip
|
||||
*/
|
||||
shouldApply(_context: RequestContext): boolean {
|
||||
return this.config.enabled !== false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of this feature (for debugging)
|
||||
*/
|
||||
get name(): string {
|
||||
return this.config.name ?? this.constructor.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this feature is enabled
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this.config.enabled !== false
|
||||
}
|
||||
}
|
||||
15
packages/api-client/src/core/abstract-module.ts
Normal file
15
packages/api-client/src/core/abstract-module.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { AbstractModrinthClient } from './abstract-client'
|
||||
|
||||
export abstract class AbstractModule {
|
||||
protected client: AbstractModrinthClient
|
||||
|
||||
public constructor(client: AbstractModrinthClient) {
|
||||
this.client = client
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the module's name, used for error reporting & for module field generation.
|
||||
* @returns Module name
|
||||
*/
|
||||
public abstract getModuleID(): string
|
||||
}
|
||||
142
packages/api-client/src/core/errors.ts
Normal file
142
packages/api-client/src/core/errors.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import type { ApiErrorData, ModrinthErrorResponse } from '../types/errors'
|
||||
import { isModrinthErrorResponse } from '../types/errors'
|
||||
|
||||
/**
|
||||
* Base error class for all Modrinth API errors
|
||||
*/
|
||||
export class ModrinthApiError extends Error {
|
||||
/**
|
||||
* HTTP status code (if available)
|
||||
*/
|
||||
readonly statusCode?: number
|
||||
|
||||
/**
|
||||
* Original error that was caught
|
||||
*/
|
||||
readonly originalError?: Error
|
||||
|
||||
/**
|
||||
* Response data from the API (if available)
|
||||
*/
|
||||
readonly responseData?: unknown
|
||||
|
||||
/**
|
||||
* Error context (e.g., module name, operation being performed)
|
||||
*/
|
||||
readonly context?: string
|
||||
|
||||
constructor(message: string, data?: ApiErrorData) {
|
||||
super(message)
|
||||
this.name = 'ModrinthApiError'
|
||||
|
||||
this.statusCode = data?.statusCode
|
||||
this.originalError = data?.originalError
|
||||
this.responseData = data?.responseData
|
||||
this.context = data?.context
|
||||
|
||||
// Maintains proper stack trace for where our error was thrown (only available on V8)
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ModrinthApiError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthApiError from an unknown error
|
||||
*/
|
||||
static fromUnknown(error: unknown, context?: string): ModrinthApiError {
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ModrinthApiError(error.message, {
|
||||
originalError: error,
|
||||
context,
|
||||
})
|
||||
}
|
||||
|
||||
return new ModrinthApiError(String(error), { context })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error class for Modrinth server errors (kyros/archon)
|
||||
* Extends ModrinthApiError with V1 error response parsing
|
||||
*/
|
||||
export class ModrinthServerError extends ModrinthApiError {
|
||||
/**
|
||||
* V1 error information (if available)
|
||||
*/
|
||||
readonly v1Error?: ModrinthErrorResponse
|
||||
|
||||
constructor(message: string, data?: ApiErrorData & { v1Error?: ModrinthErrorResponse }) {
|
||||
// If we have a V1 error, format the message nicely
|
||||
let errorMessage = message
|
||||
if (data?.v1Error) {
|
||||
errorMessage = `[${data.v1Error.error}] ${data.v1Error.description}`
|
||||
if (data.v1Error.context) {
|
||||
errorMessage = `${data.v1Error.context}: ${errorMessage}`
|
||||
}
|
||||
}
|
||||
|
||||
super(errorMessage, data)
|
||||
this.name = 'ModrinthServerError'
|
||||
this.v1Error = data?.v1Error
|
||||
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ModrinthServerError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthServerError from response data
|
||||
*/
|
||||
static fromResponse(
|
||||
statusCode: number,
|
||||
responseData: unknown,
|
||||
context?: string,
|
||||
): ModrinthServerError {
|
||||
const v1Error = isModrinthErrorResponse(responseData) ? responseData : undefined
|
||||
|
||||
let message = `HTTP ${statusCode}`
|
||||
if (v1Error) {
|
||||
message = v1Error.description
|
||||
} else if (typeof responseData === 'string') {
|
||||
message = responseData
|
||||
}
|
||||
|
||||
return new ModrinthServerError(message, {
|
||||
statusCode,
|
||||
responseData,
|
||||
context,
|
||||
v1Error,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthServerError from an unknown error
|
||||
*/
|
||||
static fromUnknown(error: unknown, context?: string): ModrinthServerError {
|
||||
if (error instanceof ModrinthServerError) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return new ModrinthServerError(error.message, {
|
||||
statusCode: error.statusCode,
|
||||
originalError: error.originalError,
|
||||
responseData: error.responseData,
|
||||
context: context ?? error.context,
|
||||
})
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ModrinthServerError(error.message, {
|
||||
originalError: error,
|
||||
context,
|
||||
})
|
||||
}
|
||||
|
||||
return new ModrinthServerError(String(error), { context })
|
||||
}
|
||||
}
|
||||
89
packages/api-client/src/features/auth.ts
Normal file
89
packages/api-client/src/features/auth.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { AbstractFeature, type FeatureConfig } from '../core/abstract-feature'
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
/**
|
||||
* Authentication feature configuration
|
||||
*/
|
||||
export interface AuthConfig extends FeatureConfig {
|
||||
/**
|
||||
* Authentication token
|
||||
* - string: static token
|
||||
* - function: async function that returns token (useful for dynamic tokens)
|
||||
*/
|
||||
token: string | (() => Promise<string | undefined>)
|
||||
|
||||
/**
|
||||
* Token prefix (e.g., 'Bearer', 'Token')
|
||||
* @default 'Bearer'
|
||||
*/
|
||||
tokenPrefix?: string
|
||||
|
||||
/**
|
||||
* Custom header name for the token
|
||||
* @default 'Authorization'
|
||||
*/
|
||||
headerName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication feature
|
||||
*
|
||||
* Automatically injects authentication tokens into request headers.
|
||||
* Supports both static tokens and dynamic token providers.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Static token
|
||||
* const auth = new AuthFeature({
|
||||
* token: 'mrp_...'
|
||||
* })
|
||||
*
|
||||
* // Dynamic token (e.g., from auth state)
|
||||
* const auth = new AuthFeature({
|
||||
* token: async () => await getAuthToken()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class AuthFeature extends AbstractFeature {
|
||||
protected declare config: AuthConfig
|
||||
|
||||
async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
const token = await this.getToken()
|
||||
|
||||
if (token) {
|
||||
const headerName = this.config.headerName ?? 'Authorization'
|
||||
const tokenPrefix = this.config.tokenPrefix ?? 'Bearer'
|
||||
const headerValue = tokenPrefix ? `${tokenPrefix} ${token}` : token
|
||||
|
||||
context.options.headers = {
|
||||
...context.options.headers,
|
||||
[headerName]: headerValue,
|
||||
}
|
||||
}
|
||||
|
||||
return next()
|
||||
}
|
||||
|
||||
shouldApply(context: RequestContext): boolean {
|
||||
if (context.options.skipAuth) {
|
||||
return false
|
||||
}
|
||||
|
||||
return super.shouldApply(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the authentication token
|
||||
*
|
||||
* Handles both static tokens and async token providers
|
||||
*/
|
||||
private async getToken(): Promise<string | undefined> {
|
||||
const { token } = this.config
|
||||
|
||||
if (typeof token === 'function') {
|
||||
return await token()
|
||||
}
|
||||
|
||||
return token
|
||||
}
|
||||
}
|
||||
269
packages/api-client/src/features/circuit-breaker.ts
Normal file
269
packages/api-client/src/features/circuit-breaker.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
import { AbstractFeature, type FeatureConfig } from '../core/abstract-feature'
|
||||
import { ModrinthApiError } from '../core/errors'
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
/**
|
||||
* Circuit breaker state
|
||||
*/
|
||||
export type CircuitBreakerState = {
|
||||
/**
|
||||
* Number of consecutive failures
|
||||
*/
|
||||
failures: number
|
||||
|
||||
/**
|
||||
* Timestamp of last failure
|
||||
*/
|
||||
lastFailure: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Circuit breaker storage interface
|
||||
*/
|
||||
export interface CircuitBreakerStorage {
|
||||
/**
|
||||
* Get circuit breaker state for a key
|
||||
*/
|
||||
get(key: string): CircuitBreakerState | undefined
|
||||
|
||||
/**
|
||||
* Set circuit breaker state for a key
|
||||
*/
|
||||
set(key: string, state: CircuitBreakerState): void
|
||||
|
||||
/**
|
||||
* Clear circuit breaker state for a key
|
||||
*/
|
||||
clear?(key: string): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Circuit breaker feature configuration
|
||||
*/
|
||||
export interface CircuitBreakerConfig extends FeatureConfig {
|
||||
/**
|
||||
* Maximum number of consecutive failures before opening circuit
|
||||
* @default 3
|
||||
*/
|
||||
maxFailures?: number
|
||||
|
||||
/**
|
||||
* Time in milliseconds before circuit resets after opening
|
||||
* @default 30000
|
||||
*/
|
||||
resetTimeout?: number
|
||||
|
||||
/**
|
||||
* HTTP status codes that count as failures
|
||||
* @default [500, 502, 503, 504]
|
||||
*/
|
||||
failureStatusCodes?: number[]
|
||||
|
||||
/**
|
||||
* Storage implementation for circuit state
|
||||
* If not provided, uses in-memory Map
|
||||
*/
|
||||
storage?: CircuitBreakerStorage
|
||||
|
||||
/**
|
||||
* Function to generate circuit key from request context
|
||||
* By default, uses the base path (without query params)
|
||||
*/
|
||||
getCircuitKey?: (url: string, method: string) => string
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory storage for circuit breaker state
|
||||
*/
|
||||
export class InMemoryCircuitBreakerStorage implements CircuitBreakerStorage {
|
||||
private state = new Map<string, CircuitBreakerState>()
|
||||
|
||||
get(key: string): CircuitBreakerState | undefined {
|
||||
return this.state.get(key)
|
||||
}
|
||||
|
||||
set(key: string, state: CircuitBreakerState): void {
|
||||
this.state.set(key, state)
|
||||
}
|
||||
|
||||
clear(key: string): void {
|
||||
this.state.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Circuit breaker feature
|
||||
*
|
||||
* Prevents requests to failing endpoints by "opening the circuit" after
|
||||
* a threshold of consecutive failures. The circuit automatically resets
|
||||
* after a timeout period.
|
||||
*
|
||||
* This implements the circuit breaker pattern to prevent cascading failures
|
||||
* and give failing services time to recover.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const circuitBreaker = new CircuitBreakerFeature({
|
||||
* maxFailures: 3,
|
||||
* resetTimeout: 30000, // 30 seconds
|
||||
* failureStatusCodes: [500, 502, 503, 504]
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class CircuitBreakerFeature extends AbstractFeature {
|
||||
protected declare config: Required<CircuitBreakerConfig>
|
||||
private storage: CircuitBreakerStorage
|
||||
|
||||
constructor(config?: CircuitBreakerConfig) {
|
||||
super(config)
|
||||
|
||||
this.config = {
|
||||
enabled: true,
|
||||
name: 'circuit-breaker',
|
||||
maxFailures: 3,
|
||||
resetTimeout: 30000,
|
||||
failureStatusCodes: [500, 502, 503, 504],
|
||||
...config,
|
||||
} as Required<CircuitBreakerConfig>
|
||||
|
||||
// Use provided storage or default to in-memory
|
||||
this.storage = config?.storage ?? new InMemoryCircuitBreakerStorage()
|
||||
}
|
||||
|
||||
async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
const circuitKey = this.getCircuitKey(context)
|
||||
|
||||
if (this.isCircuitOpen(circuitKey)) {
|
||||
throw new ModrinthApiError('Circuit breaker open - too many recent failures', {
|
||||
statusCode: 503,
|
||||
context: context.path,
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await next()
|
||||
|
||||
this.recordSuccess(circuitKey)
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
if (this.isFailureError(error)) {
|
||||
this.recordFailure(circuitKey)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
shouldApply(context: RequestContext): boolean {
|
||||
if (context.options.circuitBreaker === false) {
|
||||
return false
|
||||
}
|
||||
|
||||
return super.shouldApply(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the circuit key for a request
|
||||
*
|
||||
* By default, uses the path and method to identify unique circuits
|
||||
*/
|
||||
private getCircuitKey(context: RequestContext): string {
|
||||
if (this.config.getCircuitKey) {
|
||||
return this.config.getCircuitKey(context.url, context.options.method ?? 'GET')
|
||||
}
|
||||
|
||||
// Default: use method + path (without query params)
|
||||
const method = context.options.method ?? 'GET'
|
||||
const pathWithoutQuery = context.path.split('?')[0]
|
||||
|
||||
return `${method}_${pathWithoutQuery}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the circuit is open for a given key
|
||||
*/
|
||||
private isCircuitOpen(key: string): boolean {
|
||||
const state = this.storage.get(key)
|
||||
|
||||
if (!state) {
|
||||
return false
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const timeSinceLastFailure = now - state.lastFailure
|
||||
|
||||
if (timeSinceLastFailure > this.config.resetTimeout) {
|
||||
this.storage.clear?.(key)
|
||||
return false
|
||||
}
|
||||
|
||||
return state.failures >= this.config.maxFailures
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successful request
|
||||
*/
|
||||
private recordSuccess(key: string): void {
|
||||
this.storage.clear?.(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a failed request
|
||||
*/
|
||||
private recordFailure(key: string): void {
|
||||
const now = Date.now()
|
||||
const state = this.storage.get(key)
|
||||
|
||||
if (!state) {
|
||||
// First failure
|
||||
this.storage.set(key, {
|
||||
failures: 1,
|
||||
lastFailure: now,
|
||||
})
|
||||
} else {
|
||||
// Subsequent failure
|
||||
this.storage.set(key, {
|
||||
failures: state.failures + 1,
|
||||
lastFailure: now,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an error should count as a circuit failure
|
||||
*/
|
||||
private isFailureError(error: unknown): boolean {
|
||||
if (error instanceof ModrinthApiError && error.statusCode) {
|
||||
return this.config.failureStatusCodes.includes(error.statusCode)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current circuit state for debugging
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const state = circuitBreaker.getCircuitState('GET_/v2/project/sodium')
|
||||
* console.log(`Failures: ${state?.failures}, Last failure: ${state?.lastFailure}`)
|
||||
* ```
|
||||
*/
|
||||
getCircuitState(key: string): CircuitBreakerState | undefined {
|
||||
return this.storage.get(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually reset a circuit
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Reset circuit after manual intervention
|
||||
* circuitBreaker.resetCircuit('GET_/v2/project/sodium')
|
||||
* ```
|
||||
*/
|
||||
resetCircuit(key: string): void {
|
||||
this.storage.clear?.(key)
|
||||
}
|
||||
}
|
||||
220
packages/api-client/src/features/retry.ts
Normal file
220
packages/api-client/src/features/retry.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import { AbstractFeature, type FeatureConfig } from '../core/abstract-feature'
|
||||
import { ModrinthApiError } from '../core/errors'
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
/**
|
||||
* Backoff strategy for retries
|
||||
*/
|
||||
export type BackoffStrategy = 'exponential' | 'linear' | 'constant'
|
||||
|
||||
/**
|
||||
* Retry feature configuration
|
||||
*/
|
||||
export interface RetryConfig extends FeatureConfig {
|
||||
/**
|
||||
* Maximum number of retry attempts
|
||||
* @default 3
|
||||
*/
|
||||
maxAttempts?: number
|
||||
|
||||
/**
|
||||
* Backoff strategy to use
|
||||
* @default 'exponential'
|
||||
*/
|
||||
backoffStrategy?: BackoffStrategy
|
||||
|
||||
/**
|
||||
* Initial delay in milliseconds before first retry
|
||||
* @default 1000
|
||||
*/
|
||||
initialDelay?: number
|
||||
|
||||
/**
|
||||
* Maximum delay in milliseconds between retries
|
||||
* @default 15000
|
||||
*/
|
||||
maxDelay?: number
|
||||
|
||||
/**
|
||||
* HTTP status codes that should trigger a retry
|
||||
* @default [408, 429, 500, 502, 503, 504]
|
||||
*/
|
||||
retryableStatusCodes?: number[]
|
||||
|
||||
/**
|
||||
* Whether to retry on network errors (connection refused, timeout, etc.)
|
||||
* @default true
|
||||
*/
|
||||
retryOnNetworkError?: boolean
|
||||
|
||||
/**
|
||||
* Custom function to determine if an error should be retried
|
||||
*/
|
||||
shouldRetry?: (error: unknown, attempt: number) => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry feature
|
||||
*
|
||||
* Automatically retries failed requests with configurable backoff strategy.
|
||||
* Only retries errors that are likely to succeed on retry (e.g., timeout, 5xx errors).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const retry = new RetryFeature({
|
||||
* maxAttempts: 3,
|
||||
* backoffStrategy: 'exponential',
|
||||
* initialDelay: 1000,
|
||||
* maxDelay: 15000
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class RetryFeature extends AbstractFeature {
|
||||
protected declare config: Required<RetryConfig>
|
||||
|
||||
constructor(config?: RetryConfig) {
|
||||
super(config)
|
||||
|
||||
this.config = {
|
||||
enabled: true,
|
||||
name: 'retry',
|
||||
maxAttempts: 3,
|
||||
backoffStrategy: 'exponential',
|
||||
initialDelay: 1000,
|
||||
maxDelay: 15000,
|
||||
retryableStatusCodes: [408, 429, 500, 502, 503, 504],
|
||||
retryOnNetworkError: true,
|
||||
...config,
|
||||
} as Required<RetryConfig>
|
||||
}
|
||||
|
||||
async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
let lastError: Error | null = null
|
||||
const maxAttempts = this.getMaxAttempts(context)
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
context.attempt = attempt
|
||||
|
||||
try {
|
||||
const result = await next()
|
||||
return result
|
||||
} catch (error) {
|
||||
lastError = error as Error
|
||||
|
||||
const shouldRetry = this.shouldRetryError(error, attempt, maxAttempts)
|
||||
|
||||
if (!shouldRetry || attempt >= maxAttempts) {
|
||||
throw error
|
||||
}
|
||||
|
||||
const delay = this.calculateDelay(attempt)
|
||||
|
||||
console.warn(
|
||||
`[${this.name}] Retrying request to ${context.path} (attempt ${attempt + 1}/${maxAttempts}) after ${delay}ms`,
|
||||
)
|
||||
|
||||
await this.sleep(delay)
|
||||
}
|
||||
}
|
||||
|
||||
// This shouldn't be reached, but TypeScript requires it
|
||||
throw lastError ?? new Error('Max retry attempts reached')
|
||||
}
|
||||
|
||||
shouldApply(context: RequestContext): boolean {
|
||||
if (context.options.retry === false) {
|
||||
return false
|
||||
}
|
||||
|
||||
return super.shouldApply(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an error should be retried
|
||||
*/
|
||||
private shouldRetryError(error: unknown, attempt: number, _maxAttempts: number): boolean {
|
||||
if (this.config.shouldRetry) {
|
||||
return this.config.shouldRetry(error, attempt)
|
||||
}
|
||||
|
||||
if (this.config.retryOnNetworkError && this.isNetworkError(error)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (error instanceof ModrinthApiError && error.statusCode) {
|
||||
return this.config.retryableStatusCodes.includes(error.statusCode)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is a network error
|
||||
*/
|
||||
private isNetworkError(error: unknown): boolean {
|
||||
// Common network error indicators
|
||||
const networkErrorPatterns = [
|
||||
/network/i,
|
||||
/timeout/i,
|
||||
/ECONNREFUSED/i,
|
||||
/ENOTFOUND/i,
|
||||
/ETIMEDOUT/i,
|
||||
/ECONNRESET/i,
|
||||
]
|
||||
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
return networkErrorPatterns.some((pattern) => pattern.test(errorMessage))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get max attempts for this request
|
||||
*/
|
||||
private getMaxAttempts(context: RequestContext): number {
|
||||
if (typeof context.options.retry === 'number') {
|
||||
return context.options.retry
|
||||
}
|
||||
|
||||
return this.config.maxAttempts
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate delay before next retry based on backoff strategy
|
||||
*/
|
||||
private calculateDelay(attempt: number): number {
|
||||
const { backoffStrategy, initialDelay, maxDelay } = this.config
|
||||
|
||||
let delay: number
|
||||
|
||||
switch (backoffStrategy) {
|
||||
case 'exponential':
|
||||
// Exponential: delay = initialDelay * 2^(attempt-1)
|
||||
delay = initialDelay * Math.pow(2, attempt - 1)
|
||||
break
|
||||
|
||||
case 'linear':
|
||||
// Linear: delay = initialDelay * attempt
|
||||
delay = initialDelay * attempt
|
||||
break
|
||||
|
||||
case 'constant':
|
||||
// Constant: delay = initialDelay
|
||||
delay = initialDelay
|
||||
break
|
||||
|
||||
default:
|
||||
delay = initialDelay
|
||||
}
|
||||
|
||||
// Add jitter (random 0-1000ms) to prevent thundering herd
|
||||
delay += Math.random() * 1000
|
||||
|
||||
return Math.min(delay, maxDelay)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep for a given duration
|
||||
*/
|
||||
private sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
}
|
||||
30
packages/api-client/src/features/verbose-logging.ts
Normal file
30
packages/api-client/src/features/verbose-logging.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { AbstractFeature, type FeatureConfig } from '../core/abstract-feature'
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
export type VerboseLoggingConfig = FeatureConfig
|
||||
|
||||
export class VerboseLoggingFeature extends AbstractFeature {
|
||||
async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
const method = context.options.method ?? 'GET'
|
||||
const api = context.options.api
|
||||
const version = context.options.version
|
||||
const prefix = `[${method}] [${api}_v${version}]`
|
||||
|
||||
console.debug(`${prefix} ${context.url} SENT`)
|
||||
|
||||
try {
|
||||
const result = await next()
|
||||
try {
|
||||
const size = result ? JSON.stringify(result).length : 0
|
||||
console.debug(`${prefix} ${context.url} RECEIVED ${size} bytes`)
|
||||
} catch {
|
||||
// ignore size calc fail
|
||||
console.debug(`${prefix} ${context.url} RECEIVED`)
|
||||
}
|
||||
return result
|
||||
} catch (error) {
|
||||
console.debug(`${prefix} ${context.url} FAILED`)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
21
packages/api-client/src/index.ts
Normal file
21
packages/api-client/src/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
export { AbstractModrinthClient } from './core/abstract-client'
|
||||
export { AbstractFeature, type FeatureConfig } from './core/abstract-feature'
|
||||
export { ModrinthApiError, ModrinthServerError } from './core/errors'
|
||||
export { type AuthConfig, AuthFeature } from './features/auth'
|
||||
export {
|
||||
type CircuitBreakerConfig,
|
||||
CircuitBreakerFeature,
|
||||
type CircuitBreakerState,
|
||||
type CircuitBreakerStorage,
|
||||
InMemoryCircuitBreakerStorage,
|
||||
} from './features/circuit-breaker'
|
||||
export { type BackoffStrategy, type RetryConfig, RetryFeature } from './features/retry'
|
||||
export { type VerboseLoggingConfig, VerboseLoggingFeature } from './features/verbose-logging'
|
||||
export type { InferredClientModules } from './modules'
|
||||
export * from './modules/types'
|
||||
export { GenericModrinthClient } from './platform/generic'
|
||||
export type { NuxtClientConfig } from './platform/nuxt'
|
||||
export { NuxtCircuitBreakerStorage, NuxtModrinthClient } from './platform/nuxt'
|
||||
export type { TauriClientConfig } from './platform/tauri'
|
||||
export { TauriModrinthClient } from './platform/tauri'
|
||||
export * from './types'
|
||||
0
packages/api-client/src/modules/archon/.gitkeep
Normal file
0
packages/api-client/src/modules/archon/.gitkeep
Normal file
106
packages/api-client/src/modules/index.ts
Normal file
106
packages/api-client/src/modules/index.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import type { AbstractModrinthClient } from '../core/abstract-client'
|
||||
import type { AbstractModule } from '../core/abstract-module'
|
||||
import { LabrinthProjectsV2Module } from './labrinth/projects/v2'
|
||||
import { LabrinthProjectsV3Module } from './labrinth/projects/v3'
|
||||
|
||||
type ModuleConstructor = new (client: AbstractModrinthClient) => AbstractModule
|
||||
|
||||
/**
|
||||
* To add a new module:
|
||||
* 1. Create your module class extending AbstractModule
|
||||
* 2. Add one line here: `<api>_<module>: YourModuleClass`
|
||||
*
|
||||
* TypeScript will automatically infer the client's field structure from this registry.
|
||||
*
|
||||
* TODO: Better way? Probably not
|
||||
*/
|
||||
export const MODULE_REGISTRY = {
|
||||
labrinth_projects_v2: LabrinthProjectsV2Module,
|
||||
labrinth_projects_v3: LabrinthProjectsV3Module,
|
||||
} as const satisfies Record<string, ModuleConstructor>
|
||||
|
||||
export type ModuleID = keyof typeof MODULE_REGISTRY
|
||||
|
||||
/**
|
||||
* Parse a module ID into [api, moduleName] tuple
|
||||
*
|
||||
* @param id - Module ID in format `<api>_<module>` (e.g., 'labrinth_projects_v2')
|
||||
* @returns Tuple of [api, moduleName] (e.g., ['labrinth', 'projects_v2'])
|
||||
* @throws Error if module ID doesn't match expected format
|
||||
*/
|
||||
export function parseModuleID(id: string): [string, string] {
|
||||
const parts = id.split('_')
|
||||
if (parts.length < 2) {
|
||||
throw new Error(
|
||||
`Invalid module ID "${id}". Expected format: <api>_<module> (e.g., "labrinth_projects_v2")`,
|
||||
)
|
||||
}
|
||||
const api = parts[0]
|
||||
const moduleName = parts.slice(1).join('_')
|
||||
return [api, moduleName]
|
||||
}
|
||||
|
||||
/**
|
||||
* Build nested module structure from flat registry
|
||||
*
|
||||
* Transforms:
|
||||
* ```
|
||||
* { labrinth_projects_v2: Constructor, labrinth_users_v2: Constructor }
|
||||
* ```
|
||||
* Into:
|
||||
* ```
|
||||
* { labrinth: { projects_v2: Constructor, users_v2: Constructor } }
|
||||
* ```
|
||||
*
|
||||
* @returns Nested structure organized by API namespace
|
||||
*/
|
||||
export function buildModuleStructure(): Record<string, Record<string, ModuleConstructor>> {
|
||||
const structure: Record<string, Record<string, ModuleConstructor>> = {}
|
||||
|
||||
for (const [id, constructor] of Object.entries(MODULE_REGISTRY)) {
|
||||
const [api, moduleName] = parseModuleID(id)
|
||||
|
||||
if (!structure[api]) {
|
||||
structure[api] = {}
|
||||
}
|
||||
|
||||
structure[api][moduleName] = constructor
|
||||
}
|
||||
|
||||
return structure
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract API name from module ID
|
||||
* @example ParseAPI<'labrinth_projects_v2'> = 'labrinth'
|
||||
*/
|
||||
type ParseAPI<T extends string> = T extends `${infer API}_${string}` ? API : never
|
||||
|
||||
/**
|
||||
* Extract module name for a given API
|
||||
* @example ParseModule<'labrinth_projects_v2', 'labrinth'> = 'projects_v2'
|
||||
*/
|
||||
type ParseModule<T extends string, API extends string> = T extends `${API}_${infer Module}`
|
||||
? Module
|
||||
: never
|
||||
|
||||
/**
|
||||
* Group registry modules by API namespace
|
||||
*
|
||||
* Transforms flat registry into nested structure at the type level:
|
||||
* ```
|
||||
* { labrinth_projects_v2: ModuleClass } → { labrinth: { projects_v2: ModuleInstance } }
|
||||
* ```
|
||||
*/
|
||||
type GroupByAPI<Registry extends Record<string, ModuleConstructor>> = {
|
||||
[API in ParseAPI<keyof Registry & string>]: {
|
||||
[Module in ParseModule<keyof Registry & string, API>]: InstanceType<
|
||||
Registry[`${API}_${Module}`]
|
||||
>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inferred client module structure
|
||||
**/
|
||||
export type InferredClientModules = GroupByAPI<typeof MODULE_REGISTRY>
|
||||
0
packages/api-client/src/modules/kyros/.gitkeep
Normal file
0
packages/api-client/src/modules/kyros/.gitkeep
Normal file
2
packages/api-client/src/modules/labrinth/index.ts
Normal file
2
packages/api-client/src/modules/labrinth/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './projects/v2'
|
||||
export * from './projects/v3'
|
||||
115
packages/api-client/src/modules/labrinth/projects/types/v2.ts
Normal file
115
packages/api-client/src/modules/labrinth/projects/types/v2.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
export type Environment = 'required' | 'optional' | 'unsupported' | 'unknown'
|
||||
|
||||
export type ProjectStatus =
|
||||
| 'approved'
|
||||
| 'archived'
|
||||
| 'rejected'
|
||||
| 'draft'
|
||||
| 'unlisted'
|
||||
| 'processing'
|
||||
| 'withheld'
|
||||
| 'scheduled'
|
||||
| 'private'
|
||||
| 'unknown'
|
||||
|
||||
export type MonetizationStatus = 'monetized' | 'demonetized' | 'force-demonetized'
|
||||
|
||||
export type ProjectType = 'mod' | 'modpack' | 'resourcepack' | 'shader' | 'plugin' | 'datapack'
|
||||
|
||||
export type GalleryImageV2 = {
|
||||
url: string
|
||||
featured: boolean
|
||||
title?: string
|
||||
description?: string
|
||||
created: string
|
||||
ordering: number
|
||||
}
|
||||
|
||||
export type DonationLinkV2 = {
|
||||
id: string
|
||||
platform: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export type ProjectV2 = {
|
||||
id: string
|
||||
slug: string
|
||||
project_type: ProjectType
|
||||
team: string
|
||||
title: string
|
||||
description: string
|
||||
body: string
|
||||
published: string
|
||||
updated: string
|
||||
approved?: string
|
||||
queued?: string
|
||||
status: ProjectStatus
|
||||
requested_status?: ProjectStatus
|
||||
moderator_message?: {
|
||||
message: string
|
||||
body?: string
|
||||
}
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
downloads: number
|
||||
followers: number
|
||||
categories: string[]
|
||||
additional_categories: string[]
|
||||
game_versions: string[]
|
||||
loaders: string[]
|
||||
versions: string[]
|
||||
icon_url?: string
|
||||
issues_url?: string
|
||||
source_url?: string
|
||||
wiki_url?: string
|
||||
discord_url?: string
|
||||
donation_urls?: DonationLinkV2[]
|
||||
gallery?: GalleryImageV2[]
|
||||
color?: number
|
||||
thread_id: string
|
||||
monetization_status: MonetizationStatus
|
||||
}
|
||||
|
||||
export type SearchResultHit = {
|
||||
project_id: string
|
||||
project_type: ProjectType
|
||||
slug: string
|
||||
author: string
|
||||
title: string
|
||||
description: string
|
||||
categories: string[]
|
||||
display_categories: string[]
|
||||
versions: string[]
|
||||
downloads: number
|
||||
follows: number
|
||||
icon_url: string
|
||||
date_created: string
|
||||
date_modified: string
|
||||
latest_version?: string
|
||||
license: string
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
gallery: string[]
|
||||
color?: number
|
||||
}
|
||||
|
||||
export type SearchResult = {
|
||||
hits: SearchResultHit[]
|
||||
offset: number
|
||||
limit: number
|
||||
total_hits: number
|
||||
}
|
||||
|
||||
export type ProjectSearchParams = {
|
||||
query?: string
|
||||
facets?: string[][]
|
||||
filters?: string
|
||||
index?: 'relevance' | 'downloads' | 'follows' | 'newest' | 'updated'
|
||||
offset?: number
|
||||
limit?: number
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { MonetizationStatus, ProjectStatus } from './v2'
|
||||
|
||||
export type GalleryItemV3 = {
|
||||
url: string
|
||||
raw_url: string
|
||||
featured: boolean
|
||||
name?: string
|
||||
description?: string
|
||||
created: string
|
||||
ordering: number
|
||||
}
|
||||
|
||||
export type LinkV3 = {
|
||||
platform: string
|
||||
donation: boolean
|
||||
url: string
|
||||
}
|
||||
|
||||
export type ProjectV3 = {
|
||||
id: string
|
||||
slug?: string
|
||||
project_types: string[]
|
||||
games: string[]
|
||||
team_id: string
|
||||
organization?: string
|
||||
name: string
|
||||
summary: string
|
||||
description: string
|
||||
published: string
|
||||
updated: string
|
||||
approved?: string
|
||||
queued?: string
|
||||
status: ProjectStatus
|
||||
requested_status?: ProjectStatus
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
downloads: number
|
||||
followers: number
|
||||
categories: string[]
|
||||
additional_categories: string[]
|
||||
loaders: string[]
|
||||
versions: string[]
|
||||
icon_url?: string
|
||||
link_urls: Record<string, LinkV3>
|
||||
gallery: GalleryItemV3[]
|
||||
color?: number
|
||||
thread_id: string
|
||||
monetization_status: MonetizationStatus
|
||||
side_types_migration_review_status: 'reviewed' | 'pending'
|
||||
[key: string]: unknown
|
||||
}
|
||||
112
packages/api-client/src/modules/labrinth/projects/v2.ts
Normal file
112
packages/api-client/src/modules/labrinth/projects/v2.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { AbstractModule } from '../../../core/abstract-module'
|
||||
import type { ProjectSearchParams, ProjectV2, SearchResult } from './types/v2'
|
||||
|
||||
export class LabrinthProjectsV2Module extends AbstractModule {
|
||||
public getModuleID(): string {
|
||||
return 'labrinth_projects_v2'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID or slug
|
||||
*
|
||||
* @param id - Project ID or slug (e.g., 'sodium' or 'AANobbMI')
|
||||
* @returns Promise resolving to the project data
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const project = await client.labrinth.projects_v2.get('sodium')
|
||||
* console.log(project.title) // "Sodium"
|
||||
* ```
|
||||
*/
|
||||
public async get(id: string): Promise<ProjectV2> {
|
||||
return this.client.request<ProjectV2>(`/project/${id}`, {
|
||||
api: 'labrinth',
|
||||
version: 2,
|
||||
method: 'GET',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get multiple projects by IDs
|
||||
*
|
||||
* @param ids - Array of project IDs or slugs
|
||||
* @returns Promise resolving to array of projects
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const projects = await client.labrinth.projects_v2.getMultiple(['sodium', 'lithium', 'phosphor'])
|
||||
* ```
|
||||
*/
|
||||
public async getMultiple(ids: string[]): Promise<ProjectV2[]> {
|
||||
return this.client.request<ProjectV2[]>(`/projects`, {
|
||||
api: 'labrinth',
|
||||
version: 2,
|
||||
method: 'GET',
|
||||
params: { ids: JSON.stringify(ids) },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects
|
||||
*
|
||||
* @param params - Search parameters (query, facets, filters, etc.)
|
||||
* @returns Promise resolving to search results
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const results = await client.labrinth.projects_v2.search({
|
||||
* query: 'optimization',
|
||||
* facets: [['categories:optimization'], ['project_type:mod']],
|
||||
* limit: 20
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
public async search(params: ProjectSearchParams): Promise<SearchResult> {
|
||||
return this.client.request<SearchResult>(`/search`, {
|
||||
api: 'labrinth',
|
||||
version: 2,
|
||||
method: 'GET',
|
||||
params: params as Record<string, unknown>,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a project
|
||||
*
|
||||
* @param id - Project ID or slug
|
||||
* @param data - Project update data
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* await client.labrinth.projects_v2.edit('sodium', {
|
||||
* description: 'Updated description'
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
public async edit(id: string, data: Partial<ProjectV2>): Promise<void> {
|
||||
return this.client.request(`/project/${id}`, {
|
||||
api: 'labrinth',
|
||||
version: 2,
|
||||
method: 'PATCH',
|
||||
body: data,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project
|
||||
*
|
||||
* @param id - Project ID or slug
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* await client.labrinth.projects_v2.delete('my-project')
|
||||
* ```
|
||||
*/
|
||||
public async delete(id: string): Promise<void> {
|
||||
return this.client.request(`/project/${id}`, {
|
||||
api: 'labrinth',
|
||||
version: 2,
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
}
|
||||
70
packages/api-client/src/modules/labrinth/projects/v3.ts
Normal file
70
packages/api-client/src/modules/labrinth/projects/v3.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { AbstractModule } from '../../../core/abstract-module'
|
||||
import type { ProjectV3 } from './types/v3'
|
||||
|
||||
export class LabrinthProjectsV3Module extends AbstractModule {
|
||||
public getModuleID(): string {
|
||||
return 'labrinth_projects_v3'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID or slug (v3)
|
||||
*
|
||||
* @param id - Project ID or slug (e.g., 'sodium' or 'AANobbMI')
|
||||
* @returns Promise resolving to the v3 project data
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const project = await client.labrinth.projects_v3.get('sodium')
|
||||
* console.log(project.project_types) // v3 field
|
||||
* ```
|
||||
*/
|
||||
public async get(id: string): Promise<ProjectV3> {
|
||||
return this.client.request<ProjectV3>(`/project/${id}`, {
|
||||
api: 'labrinth',
|
||||
version: 3,
|
||||
method: 'GET',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get multiple projects by IDs (v3)
|
||||
*
|
||||
* @param ids - Array of project IDs or slugs
|
||||
* @returns Promise resolving to array of v3 projects
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const projects = await client.labrinth.projects_v3.getMultiple(['sodium', 'lithium'])
|
||||
* ```
|
||||
*/
|
||||
public async getMultiple(ids: string[]): Promise<ProjectV3[]> {
|
||||
return this.client.request<ProjectV3[]>(`/projects`, {
|
||||
api: 'labrinth',
|
||||
version: 3,
|
||||
method: 'GET',
|
||||
params: { ids: JSON.stringify(ids) },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a project (v3)
|
||||
*
|
||||
* @param id - Project ID or slug
|
||||
* @param data - Project update data (v3 fields)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* await client.labrinth.projects_v3.edit('sodium', {
|
||||
* environment: 'client_and_server'
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
public async edit(id: string, data: Partial<ProjectV3>): Promise<void> {
|
||||
return this.client.request(`/project/${id}`, {
|
||||
api: 'labrinth',
|
||||
version: 3,
|
||||
method: 'PATCH',
|
||||
body: data,
|
||||
})
|
||||
}
|
||||
}
|
||||
2
packages/api-client/src/modules/types.ts
Normal file
2
packages/api-client/src/modules/types.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './labrinth/projects/types/v2'
|
||||
export * from './labrinth/projects/types/v3'
|
||||
51
packages/api-client/src/platform/generic.ts
Normal file
51
packages/api-client/src/platform/generic.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { $fetch, FetchError } from 'ofetch'
|
||||
|
||||
import { AbstractModrinthClient } from '../core/abstract-client'
|
||||
import type { ModrinthApiError } from '../core/errors'
|
||||
import type { RequestOptions } from '../types/request'
|
||||
|
||||
/**
|
||||
* Generic platform client using ofetch
|
||||
*
|
||||
* This client works in any JavaScript environment (Node.js, browser, workers).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new GenericModrinthClient({
|
||||
* userAgent: 'my-app/1.0.0',
|
||||
* features: [
|
||||
* new AuthFeature({ token: 'mrp_...' }),
|
||||
* new RetryFeature({ maxAttempts: 3 })
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
* const project = await client.request('/project/sodium', { api: 'labrinth', version: 2 })
|
||||
* ```
|
||||
*/
|
||||
export class GenericModrinthClient extends AbstractModrinthClient {
|
||||
protected async executeRequest<T>(url: string, options: RequestOptions): Promise<T> {
|
||||
try {
|
||||
const response = await $fetch<T>(url, {
|
||||
method: options.method ?? 'GET',
|
||||
headers: options.headers,
|
||||
body: options.body as BodyInit,
|
||||
params: options.params as Record<string, string>,
|
||||
timeout: options.timeout,
|
||||
signal: options.signal,
|
||||
})
|
||||
|
||||
return response
|
||||
} catch (error) {
|
||||
// ofetch throws FetchError for HTTP errors
|
||||
throw this.normalizeError(error)
|
||||
}
|
||||
}
|
||||
|
||||
protected normalizeError(error: unknown): ModrinthApiError {
|
||||
if (error instanceof FetchError) {
|
||||
return this.createNormalizedError(error, error.response?.status, error.data)
|
||||
}
|
||||
|
||||
return super.normalizeError(error)
|
||||
}
|
||||
}
|
||||
113
packages/api-client/src/platform/nuxt.ts
Normal file
113
packages/api-client/src/platform/nuxt.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { FetchError } from 'ofetch'
|
||||
|
||||
import { AbstractModrinthClient } from '../core/abstract-client'
|
||||
import type { ModrinthApiError } from '../core/errors'
|
||||
import type { CircuitBreakerState, CircuitBreakerStorage } from '../features/circuit-breaker'
|
||||
import type { ClientConfig } from '../types/client'
|
||||
import type { RequestOptions } from '../types/request'
|
||||
|
||||
/**
|
||||
* Circuit breaker storage using Nuxt's useState
|
||||
*
|
||||
* This provides cross-request persistence in SSR while also working in client-side.
|
||||
* State is shared between requests in the same Nuxt context.
|
||||
*/
|
||||
export class NuxtCircuitBreakerStorage implements CircuitBreakerStorage {
|
||||
private getState(): Map<string, CircuitBreakerState> {
|
||||
// @ts-expect-error - useState is provided by Nuxt runtime
|
||||
const state = useState<Map<string, CircuitBreakerState>>(
|
||||
'circuit-breaker-state',
|
||||
() => new Map(),
|
||||
)
|
||||
return state.value
|
||||
}
|
||||
|
||||
get(key: string): CircuitBreakerState | undefined {
|
||||
return this.getState().get(key)
|
||||
}
|
||||
|
||||
set(key: string, state: CircuitBreakerState): void {
|
||||
this.getState().set(key, state)
|
||||
}
|
||||
|
||||
clear(key: string): void {
|
||||
this.getState().delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nuxt-specific configuration
|
||||
*/
|
||||
export interface NuxtClientConfig extends ClientConfig {
|
||||
// TODO: do we want to provide this for tauri+base as well? its not used on app
|
||||
/**
|
||||
* Rate limit key for server-side requests
|
||||
* This is injected as x-ratelimit-key header on server-side
|
||||
*/
|
||||
rateLimitKey?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Nuxt platform client using Nuxt's $fetch
|
||||
*
|
||||
* This client is optimized for Nuxt applications and handles SSR/CSR automatically.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // In a Nuxt composable
|
||||
* const config = useRuntimeConfig()
|
||||
* const auth = await useAuth()
|
||||
*
|
||||
* const client = new NuxtModrinthClient({
|
||||
* userAgent: 'my-nuxt-app/1.0.0',
|
||||
* rateLimitKey: import.meta.server ? config.rateLimitKey : undefined,
|
||||
* features: [
|
||||
* new AuthFeature({ token: () => auth.value.token })
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
* const project = await client.request('/project/sodium', { api: 'labrinth', version: 2 })
|
||||
* ```
|
||||
*/
|
||||
export class NuxtModrinthClient extends AbstractModrinthClient {
|
||||
protected declare config: NuxtClientConfig
|
||||
|
||||
protected async executeRequest<T>(url: string, options: RequestOptions): Promise<T> {
|
||||
try {
|
||||
// @ts-expect-error - $fetch is provided by Nuxt runtime
|
||||
const response = await $fetch<T>(url, {
|
||||
method: options.method ?? 'GET',
|
||||
headers: options.headers,
|
||||
body: options.body,
|
||||
params: options.params,
|
||||
timeout: options.timeout,
|
||||
signal: options.signal,
|
||||
})
|
||||
|
||||
return response
|
||||
} catch (error) {
|
||||
throw this.normalizeError(error)
|
||||
}
|
||||
}
|
||||
|
||||
protected normalizeError(error: unknown): ModrinthApiError {
|
||||
if (error instanceof FetchError) {
|
||||
return this.createNormalizedError(error, error.response?.status, error.data)
|
||||
}
|
||||
|
||||
return super.normalizeError(error)
|
||||
}
|
||||
|
||||
protected buildDefaultHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
...super.buildDefaultHeaders(),
|
||||
}
|
||||
|
||||
// @ts-expect-error - import.meta is provided by Nuxt
|
||||
if (import.meta.server && this.config.rateLimitKey) {
|
||||
headers['x-ratelimit-key'] = this.config.rateLimitKey
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
}
|
||||
102
packages/api-client/src/platform/tauri.ts
Normal file
102
packages/api-client/src/platform/tauri.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { AbstractModrinthClient } from '../core/abstract-client'
|
||||
import type { ModrinthApiError } from '../core/errors'
|
||||
import type { ClientConfig } from '../types/client'
|
||||
import type { RequestOptions } from '../types/request'
|
||||
|
||||
/**
|
||||
* Tauri-specific configuration
|
||||
* TODO: extend into interface if needed.
|
||||
*/
|
||||
export type TauriClientConfig = ClientConfig
|
||||
|
||||
/**
|
||||
* Extended error type with HTTP response metadata
|
||||
*/
|
||||
interface HttpError extends Error {
|
||||
statusCode?: number
|
||||
responseData?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Tauri platform client using Tauri v2 HTTP plugin
|
||||
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { getVersion } from '@tauri-apps/api/app'
|
||||
*
|
||||
* const version = await getVersion()
|
||||
* const client = new TauriModrinthClient({
|
||||
* userAgent: `modrinth/theseus/${version} (support@modrinth.com)`,
|
||||
* features: [
|
||||
* new AuthFeature({ token: 'mrp_...' })
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
* const project = await client.request('/project/sodium', { api: 'labrinth', version: 2 })
|
||||
* ```
|
||||
*/
|
||||
export class TauriModrinthClient extends AbstractModrinthClient {
|
||||
protected declare config: TauriClientConfig
|
||||
|
||||
protected async executeRequest<T>(url: string, options: RequestOptions): Promise<T> {
|
||||
try {
|
||||
// Dynamically import Tauri HTTP plugin
|
||||
// This allows the package to be used in non-Tauri environments
|
||||
const { fetch: tauriFetch } = await import('@tauri-apps/plugin-http')
|
||||
|
||||
let body: BodyInit | null | undefined = undefined
|
||||
if (options.body) {
|
||||
if (typeof options.body === 'object' && !(options.body instanceof FormData)) {
|
||||
body = JSON.stringify(options.body)
|
||||
} else {
|
||||
body = options.body as BodyInit
|
||||
}
|
||||
}
|
||||
|
||||
let fullUrl = url
|
||||
if (options.params) {
|
||||
const queryParams = new URLSearchParams(options.params as Record<string, string>).toString()
|
||||
fullUrl = `${url}?${queryParams}`
|
||||
}
|
||||
|
||||
const response = await tauriFetch(fullUrl, {
|
||||
method: options.method ?? 'GET',
|
||||
headers: options.headers,
|
||||
body,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
let responseData: unknown
|
||||
try {
|
||||
responseData = await response.json()
|
||||
} catch {
|
||||
responseData = undefined
|
||||
}
|
||||
|
||||
const error = new Error(`HTTP ${response.status}: ${response.statusText}`) as HttpError
|
||||
|
||||
error.statusCode = response.status
|
||||
error.responseData = responseData
|
||||
|
||||
throw error
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return data as T
|
||||
} catch (error) {
|
||||
throw this.normalizeError(error)
|
||||
}
|
||||
}
|
||||
|
||||
protected normalizeError(error: unknown): ModrinthApiError {
|
||||
if (error instanceof Error) {
|
||||
const httpError = error as HttpError
|
||||
const statusCode = httpError.statusCode
|
||||
const responseData = httpError.responseData
|
||||
|
||||
return this.createNormalizedError(error, statusCode, responseData)
|
||||
}
|
||||
|
||||
return super.normalizeError(error)
|
||||
}
|
||||
}
|
||||
0
packages/api-client/src/tests/.gitkeep
Normal file
0
packages/api-client/src/tests/.gitkeep
Normal file
68
packages/api-client/src/types/client.ts
Normal file
68
packages/api-client/src/types/client.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import type { AbstractFeature } from '../core/abstract-feature'
|
||||
import type { RequestContext } from './request'
|
||||
|
||||
/**
|
||||
* Request lifecycle hooks
|
||||
*/
|
||||
export type RequestHooks = {
|
||||
/**
|
||||
* Called before request is sent (after all features have processed)
|
||||
*/
|
||||
onRequest?: (context: RequestContext) => void | Promise<void>
|
||||
|
||||
/**
|
||||
* Called after successful response (before features process response)
|
||||
*/
|
||||
onResponse?: <T>(data: T, context: RequestContext) => void | Promise<void>
|
||||
|
||||
/**
|
||||
* Called when request fails (after all features have processed error)
|
||||
*/
|
||||
onError?: (error: Error, context: RequestContext) => void | Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Client configuration
|
||||
*/
|
||||
export interface ClientConfig {
|
||||
/**
|
||||
* User agent string for requests
|
||||
* Should identify your application (e.g., 'my-app/1.0.0')
|
||||
* If not provided, the platform's default user agent will be used
|
||||
*/
|
||||
userAgent?: string
|
||||
|
||||
/**
|
||||
* Base URL for Labrinth API (main Modrinth API)
|
||||
* @default 'https://api.modrinth.com'
|
||||
*/
|
||||
labrinthBaseUrl?: string
|
||||
|
||||
/**
|
||||
* Base URL for Archon API (Modrinth Servers API)
|
||||
* @default 'https://archon.modrinth.com'
|
||||
*/
|
||||
archonBaseUrl?: string
|
||||
|
||||
/**
|
||||
* Default request timeout in milliseconds
|
||||
* @default 10000
|
||||
*/
|
||||
timeout?: number
|
||||
|
||||
/**
|
||||
* Additional default headers to include in all requests
|
||||
*/
|
||||
headers?: Record<string, string>
|
||||
|
||||
/**
|
||||
* Features to enable for this client
|
||||
* Features are applied in the order they appear in this array
|
||||
*/
|
||||
features?: AbstractFeature[]
|
||||
|
||||
/**
|
||||
* Request lifecycle hooks
|
||||
*/
|
||||
hooks?: RequestHooks
|
||||
}
|
||||
56
packages/api-client/src/types/errors.ts
Normal file
56
packages/api-client/src/types/errors.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Data for API errors
|
||||
*/
|
||||
export type ApiErrorData = {
|
||||
/**
|
||||
* HTTP status code (if available)
|
||||
*/
|
||||
statusCode?: number
|
||||
|
||||
/**
|
||||
* Original error that was caught
|
||||
*/
|
||||
originalError?: Error
|
||||
|
||||
/**
|
||||
* Response data from the API (if available)
|
||||
*/
|
||||
responseData?: unknown
|
||||
|
||||
/**
|
||||
* Error context (e.g., module name, operation being performed)
|
||||
*/
|
||||
context?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Modrinth V1 error response format
|
||||
* Used by kyros + archon APIs
|
||||
*/
|
||||
export type ModrinthErrorResponse = {
|
||||
/**
|
||||
* Error code/identifier
|
||||
*/
|
||||
error: string
|
||||
|
||||
/**
|
||||
* Human-readable error description
|
||||
*/
|
||||
description: string
|
||||
|
||||
/**
|
||||
* Optional context about where the error occurred
|
||||
*/
|
||||
context?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if an object is a ModrinthErrorResponse
|
||||
*/
|
||||
export function isModrinthErrorResponse(obj: unknown): obj is ModrinthErrorResponse {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return false
|
||||
}
|
||||
const record = obj as Record<string, unknown>
|
||||
return typeof record.error === 'string' && typeof record.description === 'string'
|
||||
}
|
||||
12
packages/api-client/src/types/index.ts
Normal file
12
packages/api-client/src/types/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export type { FeatureConfig } from '../core/abstract-feature'
|
||||
export type { AuthConfig } from '../features/auth'
|
||||
export type {
|
||||
CircuitBreakerConfig,
|
||||
CircuitBreakerState,
|
||||
CircuitBreakerStorage,
|
||||
} from '../features/circuit-breaker'
|
||||
export type { BackoffStrategy, RetryConfig } from '../features/retry'
|
||||
export type { ClientConfig, RequestHooks } from './client'
|
||||
export type { ApiErrorData, ModrinthErrorResponse } from './errors'
|
||||
export { isModrinthErrorResponse } from './errors'
|
||||
export type { HttpMethod, RequestContext, RequestOptions, ResponseData } from './request'
|
||||
131
packages/api-client/src/types/request.ts
Normal file
131
packages/api-client/src/types/request.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* HTTP method types
|
||||
*/
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
||||
|
||||
/**
|
||||
* Options for making a request
|
||||
*/
|
||||
export type RequestOptions = {
|
||||
/**
|
||||
* API to use for this request
|
||||
* - 'labrinth': Main Modrinth API (resolves to labrinthBaseUrl)
|
||||
* - 'archon': Modrinth Servers API (resolves to archonBaseUrl)
|
||||
* - string: Custom base URL (e.g., 'https://custom-api.com')
|
||||
*/
|
||||
api: 'labrinth' | 'archon' | string
|
||||
|
||||
/**
|
||||
* API version to use
|
||||
* - number: version number (e.g., 2 for v2, 3 for v3)
|
||||
* - 'internal': use internal API
|
||||
*/
|
||||
version: number | 'internal'
|
||||
|
||||
/**
|
||||
* HTTP method to use
|
||||
* @default 'GET'
|
||||
*/
|
||||
method?: HttpMethod
|
||||
|
||||
/**
|
||||
* Request headers
|
||||
*/
|
||||
headers?: Record<string, string>
|
||||
|
||||
/**
|
||||
* Request body (will be JSON stringified if object)
|
||||
*/
|
||||
body?: unknown
|
||||
|
||||
/**
|
||||
* URL query parameters
|
||||
*/
|
||||
params?: Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Request timeout in milliseconds
|
||||
*/
|
||||
timeout?: number
|
||||
|
||||
/**
|
||||
* Abort signal for cancelling requests
|
||||
*/
|
||||
signal?: AbortSignal
|
||||
|
||||
/**
|
||||
* Retry configuration for this specific request
|
||||
* - false: no retries
|
||||
* - true: use default retry config
|
||||
* - number: max retry attempts
|
||||
*/
|
||||
retry?: boolean | number
|
||||
|
||||
/**
|
||||
* Circuit breaker configuration for this specific request
|
||||
* - false: disable circuit breaker
|
||||
* - true: use default circuit breaker config
|
||||
*/
|
||||
circuitBreaker?: boolean
|
||||
|
||||
/**
|
||||
* Whether to skip authentication for this request
|
||||
* @default false
|
||||
*/
|
||||
skipAuth?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Full context passed to features during request execution
|
||||
*/
|
||||
export type RequestContext = {
|
||||
/**
|
||||
* Full URL being requested (with base URL and versioning applied)
|
||||
*/
|
||||
url: string
|
||||
|
||||
/**
|
||||
* Original path (before base URL and versioning)
|
||||
*/
|
||||
path: string
|
||||
|
||||
/**
|
||||
* Request options
|
||||
*/
|
||||
options: RequestOptions
|
||||
|
||||
/**
|
||||
* Current attempt number (1-indexed)
|
||||
*/
|
||||
attempt: number
|
||||
|
||||
/**
|
||||
* Timestamp when request started
|
||||
*/
|
||||
startTime: number
|
||||
|
||||
/**
|
||||
* Additional metadata that features can attach
|
||||
*/
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic response wrapper
|
||||
*/
|
||||
export type ResponseData<T = unknown> = {
|
||||
/**
|
||||
* Response data
|
||||
*/
|
||||
data: T
|
||||
|
||||
/**
|
||||
* HTTP status code
|
||||
*/
|
||||
status: number
|
||||
|
||||
/**
|
||||
* Response headers
|
||||
*/
|
||||
headers: Record<string, string>
|
||||
}
|
||||
Reference in New Issue
Block a user