@api-buddy/types
Version:
Shared types for API Buddy
1,456 lines (1,440 loc) • 49.2 kB
TypeScript
// @ts-nocheck
import { z } from 'zod';
export { z } from 'zod';
type FieldType = 'String' | 'Number' | 'Boolean' | 'Date' | 'JSON' | 'ID' | 'Relation';
declare const fieldTypeSchema: z.ZodEnum<["String", "Number", "Boolean", "Date", "JSON", "ID", "Relation"]>;
interface BaseFieldDefinition {
type: FieldType;
required?: boolean;
unique?: boolean;
default?: any;
isArray?: boolean;
validators?: Array<(value: any) => string | null>;
description?: string;
}
interface StringFieldDefinition extends BaseFieldDefinition {
type: 'String';
enum?: string[];
minLength?: number;
maxLength?: number;
pattern?: string;
format?: 'email' | 'uri' | 'uuid' | 'date-time' | 'date' | 'time' | string;
}
interface NumberFieldDefinition extends BaseFieldDefinition {
type: 'Number';
minimum?: number;
maximum?: number;
exclusiveMinimum?: boolean;
exclusiveMaximum?: boolean;
multipleOf?: number;
}
interface BooleanFieldDefinition extends BaseFieldDefinition {
type: 'Boolean';
}
interface DateFieldDefinition extends BaseFieldDefinition {
type: 'Date';
}
interface JsonFieldDefinition extends BaseFieldDefinition {
type: 'JSON';
}
interface IDFieldDefinition extends BaseFieldDefinition {
type: 'ID';
autoIncrement?: boolean;
autoGenerate?: boolean;
}
interface RelationFieldDefinition extends BaseFieldDefinition {
type: 'Relation';
relation: {
model: string;
type: 'hasOne' | 'hasMany' | 'belongsTo' | 'manyToMany';
foreignKey?: string;
through?: string;
};
}
type FieldDefinition = StringFieldDefinition | NumberFieldDefinition | BooleanFieldDefinition | DateFieldDefinition | JsonFieldDefinition | IDFieldDefinition | RelationFieldDefinition;
interface ModelDefinition {
fields: Record<string, FieldDefinition>;
timestamps?: boolean;
softDelete?: boolean;
tableName?: string;
indexes?: Array<{
fields: string | string[];
unique?: boolean;
name?: string;
}>;
}
interface Schema {
models: Record<string, ModelDefinition>;
enums?: Record<string, string[]>;
config?: {
database?: {
provider?: 'postgresql' | 'mysql' | 'sqlite' | 'mongodb';
url?: string;
ssl?: boolean;
};
auth?: {
enabled?: boolean;
providers?: ('credentials' | 'github' | 'google')[];
};
};
}
/**
* Base interface that all adapters must implement
* @template TConfig - Type of the configuration object
* @template TSchema - Type of the Zod schema for the configuration
* @template TType - Type of the adapter (from AdapterType)
*/
interface BaseAdapter<TConfig = unknown, TSchema extends z.ZodType<any, any, any> = z.ZodType<any, any, any>, TType extends AdapterType = AdapterType> {
/** Unique identifier for the adapter instance */
readonly id: string;
/** Type of the adapter (auth, database, storage, etc.) */
readonly type: TType;
/** Current configuration of the adapter */
readonly config: TConfig;
/** Zod schema for validating the configuration */
readonly schema: TSchema;
/**
* Initialize the adapter with the given configuration
* @param config Configuration object for the adapter
*/
init(config: TConfig): Promise<void>;
/**
* Clean up resources when the adapter is no longer needed
*/
destroy(): Promise<void>;
/**
* Check if the adapter is properly initialized
*/
isInitialized(): boolean;
/**
* Update the adapter's configuration
* @param config Partial configuration to update
*/
updateConfig(config: Partial<TConfig>): Promise<void>;
/**
* Validate the configuration against the schema
* @param config Configuration to validate
* @returns The validated configuration
*/
validateConfig(config: unknown): TConfig;
}
/**
* Adapter that can execute operations
* @template TConfig - Type of the configuration object
* @template TSchema - Zod schema for the configuration
* @template TResult - Type of the result
* @template TInput - Type of the input parameters
*/
interface ExecutableAdapter<TConfig = unknown, TSchema extends z.ZodType = z.ZodType, TResult = unknown, TInput = unknown> extends BaseAdapter<TConfig, TSchema> {
/**
* Execute an operation with the given parameters
* @param params Input parameters for the operation
*/
execute(params: TInput): Promise<TResult>;
}
/**
* Adapter that can subscribe to data changes
* @template TConfig - Type of the configuration object
* @template TSchema - Zod schema for the configuration
* @template TData - Type of the data being subscribed to
* @template TParams - Type of the subscription parameters
*/
interface SubscribableAdapter<TConfig = unknown, TSchema extends z.ZodType = z.ZodType, TData = unknown, TParams = unknown> extends BaseAdapter<TConfig, TSchema> {
/**
* Subscribe to data changes
* @param callback Function to call when data changes
* @param params Optional parameters for the subscription
* @returns Unsubscribe function
*/
subscribe(callback: (data: TData) => void, params?: TParams): () => void;
}
/**
* Adapter that can be used as a factory to create other adapters
*/
interface AdapterFactory<T extends BaseAdapter = BaseAdapter> {
/**
* Create a new adapter instance
* @param config Configuration for the adapter
*/
create(config: unknown): Promise<T>;
/**
* Get the default configuration for the adapter
*/
getDefaultConfig(): unknown;
/**
* Get the schema for the adapter configuration
*/
getSchema(): z.ZodType;
}
/**
* Event types that can be emitted by adapters
*/
declare enum AdapterEventType {
INITIALIZED = "initialized",
DESTROYED = "destroyed",
ERROR = "error",
CONFIG_UPDATED = "config_updated",
STATE_CHANGED = "state_changed",
DATA_CHANGED = "data_changed"
}
/**
* Base event interface for adapter events
* @template T - Type of the event data
*/
interface AdapterEvent<T = unknown> {
/** Type of the event */
type: AdapterEventType;
/** Timestamp when the event occurred */
timestamp: Date;
/** Event data */
data?: T;
/** Error if the event represents an error */
error?: Error;
/** Metadata about the event */
metadata?: Record<string, unknown>;
}
/**
* Event listener function
* @template T - Type of the event data
*/
type AdapterEventListener<T = unknown> = (event: AdapterEvent<T>) => void;
/**
* Event emitter interface for adapters
*/
interface AdapterEventEmitter {
/**
* Add an event listener
* @param event Event type to listen for
* @param listener Callback function
*/
on<T = unknown>(event: AdapterEventType | string, listener: AdapterEventListener<T>): void;
/**
* Remove an event listener
* @param event Event type to remove listener from
* @param listener Callback function to remove
*/
off<T = unknown>(event: AdapterEventType | string, listener: AdapterEventListener<T>): void;
/**
* Emit an event
* @param event Event to emit
*/
emit<T = unknown>(event: AdapterEvent<T>): void;
}
/**
* Options for initializing an adapter
*/
interface AdapterOptions {
/** Whether to automatically initialize the adapter */
autoInit?: boolean;
/** Whether to throw an error if initialization fails */
throwOnError?: boolean;
/** Logger instance */
logger?: {
debug: (...args: any[]) => void;
info: (...args: any[]) => void;
warn: (...args: any[]) => void;
error: (...args: any[]) => void;
};
}
/**
* Supported adapter types
*/
declare enum AdapterType {
/** Authentication adapter (handles users, sessions, etc.) */
AUTH = "auth",
/** Database adapter (CRUD operations) */
DATABASE = "database",
/** Storage adapter (file storage) */
STORAGE = "storage",
/** Payment processing adapter */
PAYMENT = "payment"
}
/**
* Configuration for initializing an adapter
* @template T - Type of the configuration object
*/
interface AdapterConfig<T = unknown> {
/** Type of adapter to create */
type: AdapterType;
/** Unique identifier for the adapter instance */
id: string;
/** Provider-specific configuration */
config: T;
}
/**
* Registry of all adapters by type
*/
interface AdapterRegistry {
[AdapterType.AUTH]?: Map<string, BaseAdapter<unknown, z.ZodType, AdapterType.AUTH>>;
[AdapterType.DATABASE]?: Map<string, BaseAdapter<unknown, z.ZodType, AdapterType.DATABASE>>;
[AdapterType.STORAGE]?: Map<string, BaseAdapter<unknown, z.ZodType, AdapterType.STORAGE>>;
[AdapterType.PAYMENT]?: Map<string, BaseAdapter<unknown, z.ZodType, AdapterType.PAYMENT>>;
[key: string]: Map<string, BaseAdapter> | undefined;
}
declare const userProfileSchema: z.ZodObject<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, z.ZodTypeAny, "passthrough">>;
declare const authSessionSchema: z.ZodObject<{
user: z.ZodObject<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
id: z.ZodString;
email: z.ZodOptional<z.ZodString>;
emailVerified: z.ZodOptional<z.ZodBoolean>;
name: z.ZodOptional<z.ZodString>;
avatar: z.ZodOptional<z.ZodString>;
}, z.ZodTypeAny, "passthrough">>;
accessToken: z.ZodString;
refreshToken: z.ZodOptional<z.ZodString>;
expiresAt: z.ZodOptional<z.ZodUnion<[z.ZodDate, z.ZodString]>>;
}, "strip", z.ZodTypeAny, {
user: {
id: string;
email?: string | undefined;
emailVerified?: boolean | undefined;
name?: string | undefined;
avatar?: string | undefined;
} & {
[k: string]: unknown;
};
accessToken: string;
refreshToken?: string | undefined;
expiresAt?: string | Date | undefined;
}, {
user: {
id: string;
email?: string | undefined;
emailVerified?: boolean | undefined;
name?: string | undefined;
avatar?: string | undefined;
} & {
[k: string]: unknown;
};
accessToken: string;
refreshToken?: string | undefined;
expiresAt?: string | Date | undefined;
}>;
declare const emailPasswordCredentialsSchema: z.ZodObject<{
email: z.ZodString;
password: z.ZodString;
}, "strip", z.ZodTypeAny, {
email: string;
password: string;
}, {
email: string;
password: string;
}>;
interface UserProfile {
id: string;
email?: string;
emailVerified?: boolean;
name?: string;
avatar?: string;
[key: string]: any;
}
interface AuthSession<TUser extends UserProfile = UserProfile> {
user: TUser;
accessToken: string;
refreshToken?: string;
expiresAt?: Date;
}
interface EmailPasswordCredentials {
email: string;
password: string;
}
interface AuthAdapter<TUser extends UserProfile = UserProfile> extends BaseAdapter {
readonly type: AdapterType.AUTH;
signIn(credentials: any): Promise<AuthSession<TUser>>;
signOut(): Promise<void>;
getCurrentUser(): Promise<TUser | null>;
onAuthStateChanged(callback: (user: TUser | null) => void): () => void;
signUp?(credentials: any): Promise<TUser>;
sendPasswordResetEmail?(email: string): Promise<void>;
confirmPasswordReset?(code: string, newPassword: string): Promise<void>;
updateProfile?(updates: Partial<TUser>): Promise<TUser>;
updateEmail?(email: string, currentPassword?: string): Promise<void>;
updatePassword?(newPassword: string, currentPassword?: string): Promise<void>;
signInWithProvider?(providerId: string, options?: any): Promise<AuthSession<TUser>>;
getAccessToken?(forceRefresh?: boolean): Promise<string | null>;
refreshSession?(): Promise<AuthSession<TUser>>;
getIdToken?(forceRefresh?: boolean): Promise<string | null>;
}
/**
* Options for configuring an auth adapter
*/
interface AuthAdapterOptions {
/**
* The persistence mechanism to use for the auth state
* @default 'local'
*/
persistence?: 'local' | 'session' | 'none';
/**
* Whether to automatically refresh the access token when it expires
* @default true
*/
autoRefreshToken?: boolean;
/**
* The threshold in seconds before token expiration to attempt a refresh
* @default 300 (5 minutes)
*/
refreshThreshold?: number;
/**
* The URL to redirect to after successful authentication
*/
redirectTo?: string;
/**
* The URL to redirect to after sign out
*/
redirectAfterSignOut?: string;
}
/**
* Configuration for a social authentication provider
*/
interface SocialProviderConfig {
/** The OAuth client ID */
clientId: string;
/** The OAuth client secret (server-side only) */
clientSecret?: string;
/** The OAuth scopes to request */
scopes?: string[];
/** The redirect URI for OAuth callbacks */
redirectUri?: string;
/** Additional provider-specific parameters */
params?: Record<string, string>;
}
/**
* Schema for validating social provider configurations
*/
declare const socialProviderConfigSchema: z.ZodObject<{
clientId: z.ZodString;
clientSecret: z.ZodOptional<z.ZodString>;
scopes: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
redirectUri: z.ZodOptional<z.ZodString>;
params: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
}, "strip", z.ZodTypeAny, {
clientId: string;
scopes: string[];
params?: Record<string, string> | undefined;
clientSecret?: string | undefined;
redirectUri?: string | undefined;
}, {
clientId: string;
params?: Record<string, string> | undefined;
clientSecret?: string | undefined;
scopes?: string[] | undefined;
redirectUri?: string | undefined;
}>;
/**
* Type guard for UserProfile
* @param value - The value to check
* @returns True if the value is a valid UserProfile
*/
declare function isUserProfile(value: unknown): value is UserProfile;
/**
* Type guard for AuthSession
* @param value - The value to check
* @returns True if the value is a valid AuthSession
*/
declare function isAuthSession<T extends UserProfile = UserProfile>(value: unknown): value is AuthSession<T>;
/**
* Type guard for EmailPasswordCredentials
* @param value - The value to check
* @returns True if the value is a valid EmailPasswordCredentials
*/
declare function isEmailPasswordCredentials(value: unknown): value is EmailPasswordCredentials;
/**
* Supported comparison operators for database queries
*/
type Operator = '==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any';
/**
* Schema for validating query operators
*/
declare const operatorSchema: z.ZodUnion<[z.ZodLiteral<"==">, z.ZodLiteral<"!=">, z.ZodLiteral<"<">, z.ZodLiteral<"<=">, z.ZodLiteral<">">, z.ZodLiteral<">=">, z.ZodLiteral<"in">, z.ZodLiteral<"not-in">, z.ZodLiteral<"array-contains">, z.ZodLiteral<"array-contains-any">]>;
/**
* Represents a filter condition for database queries
*/
interface QueryFilter<T = unknown> {
/** The field to filter on */
field: string;
/** The comparison operator */
operator: Operator;
/** The value to compare against */
value: T;
}
/**
* Schema for validating query filters
*/
declare const queryFilterSchema: z.ZodObject<{
field: z.ZodString;
operator: z.ZodUnion<[z.ZodLiteral<"==">, z.ZodLiteral<"!=">, z.ZodLiteral<"<">, z.ZodLiteral<"<=">, z.ZodLiteral<">">, z.ZodLiteral<">=">, z.ZodLiteral<"in">, z.ZodLiteral<"not-in">, z.ZodLiteral<"array-contains">, z.ZodLiteral<"array-contains-any">]>;
value: z.ZodAny;
}, "strip", z.ZodTypeAny, {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}, {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}>;
/**
* Options for database adapter queries
* @template T - Type of the document being queried
*/
interface DatabaseAdapterQueryOptions<T = unknown> {
/** Filter conditions */
where?: QueryFilter[];
/** Sorting order as [field, direction] */
orderBy?: [string, 'asc' | 'desc'];
/** Maximum number of results to return */
limit?: number;
/** Cursor for pagination - start after this document */
startAfter?: unknown;
/** Cursor for pagination - end before this document */
endBefore?: unknown;
/** Fields to include in the result */
select?: (keyof T)[];
/** Number of documents to skip */
offset?: number;
}
/**
* Schema for validating database query options
*/
declare const databaseQueryOptionsSchema: z.ZodObject<{
where: z.ZodOptional<z.ZodArray<z.ZodObject<{
field: z.ZodString;
operator: z.ZodUnion<[z.ZodLiteral<"==">, z.ZodLiteral<"!=">, z.ZodLiteral<"<">, z.ZodLiteral<"<=">, z.ZodLiteral<">">, z.ZodLiteral<">=">, z.ZodLiteral<"in">, z.ZodLiteral<"not-in">, z.ZodLiteral<"array-contains">, z.ZodLiteral<"array-contains-any">]>;
value: z.ZodAny;
}, "strip", z.ZodTypeAny, {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}, {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}>, "many">>;
orderBy: z.ZodOptional<z.ZodTuple<[z.ZodString, z.ZodEnum<["asc", "desc"]>], null>>;
limit: z.ZodOptional<z.ZodNumber>;
startAfter: z.ZodOptional<z.ZodAny>;
endBefore: z.ZodOptional<z.ZodAny>;
select: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
offset: z.ZodOptional<z.ZodNumber>;
}, "strict", z.ZodTypeAny, {
where?: {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}[] | undefined;
orderBy?: [string, "asc" | "desc"] | undefined;
limit?: number | undefined;
startAfter?: any;
endBefore?: any;
select?: any[] | undefined;
offset?: number | undefined;
}, {
where?: {
field: string;
operator: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "array-contains" | "array-contains-any";
value?: any;
}[] | undefined;
orderBy?: [string, "asc" | "desc"] | undefined;
limit?: number | undefined;
startAfter?: any;
endBefore?: any;
select?: any[] | undefined;
offset?: number | undefined;
}>;
/**
* Options for database transactions
*/
interface TransactionOptions {
/** Maximum number of retry attempts */
maxAttempts?: number;
/** Whether to allow writes in the transaction */
readOnly?: boolean;
/** Transaction timeout in milliseconds */
timeout?: number;
}
/**
* Schema for validating transaction options
*/
declare const transactionOptionsSchema: z.ZodObject<{
maxAttempts: z.ZodOptional<z.ZodNumber>;
readOnly: z.ZodOptional<z.ZodBoolean>;
timeout: z.ZodOptional<z.ZodNumber>;
}, "strict", z.ZodTypeAny, {
maxAttempts?: number | undefined;
readOnly?: boolean | undefined;
timeout?: number | undefined;
}, {
maxAttempts?: number | undefined;
readOnly?: boolean | undefined;
timeout?: number | undefined;
}>;
/**
* Interface for database adapters
* @template T - Default document type
* @template TConfig - Type of the configuration object
*/
interface DatabaseAdapter<T = unknown, TConfig = unknown> extends BaseAdapter<TConfig> {
readonly type: AdapterType.DATABASE;
/**
* Creates a new document in the specified collection
* @param collection - The name of the collection
* @param data - The document data (without ID)
* @returns A promise that resolves to the created document with ID
* @throws {DatabaseError} If the operation fails
*/
create(collection: string, data: Omit<T, 'id'>): Promise<T & {
id: string;
}>;
/**
* Reads a document by ID
* @param collection - The name of the collection
* @param id - The document ID
* @returns A promise that resolves to the document, or null if not found
* @throws {DatabaseError} If the operation fails
*/
read(collection: string, id: string): Promise<T | null>;
/**
* Updates a document
* @param collection - The name of the collection
* @param id - The document ID
* @param data - The fields to update
* @returns A promise that resolves to the updated document
* @throws {DatabaseError} If the operation fails
*/
update(collection: string, id: string, data: Partial<T>): Promise<T>;
/**
* Deletes a document
* @param collection - The name of the collection
* @param id - The document ID
* @returns A promise that resolves when the operation completes
* @throws {DatabaseError} If the operation fails
*/
delete(collection: string, id: string): Promise<void>;
/**
* Finds documents matching the query options
* @template TQuery - Type of the document being queried
* @param collection - The name of the collection
* @param options - Query options
* @returns A promise that resolves to an array of matching documents
* @throws {DatabaseError} If the operation fails
*/
find<TQuery = T>(collection: string, options?: DatabaseAdapterQueryOptions<TQuery>): Promise<TQuery[]>;
/**
* Finds a single document by ID with optional query options
* @template TQuery - Type of the document being queried
* @param collection - The name of the collection
* @param id - The document ID
* @param options - Additional query options
* @returns A promise that resolves to the document, or null if not found
* @throws {DatabaseError} If the operation fails
*/
findOne<TQuery = T>(collection: string, id: string, options?: Omit<DatabaseAdapterQueryOptions<TQuery>, 'limit' | 'offset'>): Promise<TQuery | null>;
/**
* Counts documents matching the query criteria
* @template TQuery - Type of the document being queried
* @param collection - The name of the collection
* @param options - Query options
* @returns A promise that resolves to the count of matching documents
* @throws {DatabaseError} If the operation fails
*/
count<TQuery = T>(collection: string, options?: Pick<DatabaseAdapterQueryOptions<TQuery>, 'where'>): Promise<number>;
subscribe(collection: string, callback: (data: T[]) => void, options?: DatabaseAdapterQueryOptions<T>): () => void;
transaction<U>(updateFunction: (transaction: any) => Promise<U>): Promise<U>;
}
/**
* Represents a file-like object that can be uploaded to storage
*/
type FileLike = File | Blob | ArrayBuffer | Uint8Array | string;
/**
* Schema for validating file metadata
*/
declare const fileMetadataSchema: z.ZodObject<{
/** Name of the file */
name: z.ZodString;
/** Size of the file in bytes */
size: z.ZodNumber;
/** MIME type of the file */
type: z.ZodString;
/** Last modified timestamp */
lastModified: z.ZodOptional<z.ZodNumber>;
/** Custom metadata key-value pairs */
customMetadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
}, "strict", z.ZodTypeAny, {
type: string;
name: string;
size: number;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}, {
type: string;
name: string;
size: number;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}>;
/**
* Represents metadata for a stored file
*/
interface FileMetadata extends z.infer<typeof fileMetadataSchema> {
}
/**
* Represents a file in storage with its metadata
*/
interface StoredFile extends FileMetadata {
/** Full path to the file in storage */
path: string;
/** Public URL to access the file */
url: string;
/** When the file was created */
createdAt: Date;
/** When the file was last updated */
updatedAt: Date;
}
/**
* Schema for validating stored file objects
*/
declare const storedFileSchema: z.ZodObject<{
/** Name of the file */
name: z.ZodString;
/** Size of the file in bytes */
size: z.ZodNumber;
/** MIME type of the file */
type: z.ZodString;
/** Last modified timestamp */
lastModified: z.ZodOptional<z.ZodNumber>;
/** Custom metadata key-value pairs */
customMetadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
} & {
path: z.ZodString;
url: z.ZodString;
createdAt: z.ZodDate;
updatedAt: z.ZodDate;
}, "strict", z.ZodTypeAny, {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}, {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}>;
/**
* Options for file uploads
*/
interface UploadOptions {
/** Whether to make the file publicly accessible */
public?: boolean;
/** Custom metadata to store with the file */
metadata?: Omit<FileMetadata, 'name' | 'size' | 'type'>;
/** Content type override */
contentType?: string;
/** Cache control header value */
cacheControl?: string;
/** Content encoding */
contentEncoding?: string;
/** Content disposition header value */
contentDisposition?: string;
}
/**
* Schema for validating upload options
*/
declare const uploadOptionsSchema: z.ZodObject<{
public: z.ZodDefault<z.ZodBoolean>;
metadata: z.ZodOptional<z.ZodObject<Omit<{
/** Name of the file */
name: z.ZodString;
/** Size of the file in bytes */
size: z.ZodNumber;
/** MIME type of the file */
type: z.ZodString;
/** Last modified timestamp */
lastModified: z.ZodOptional<z.ZodNumber>;
/** Custom metadata key-value pairs */
customMetadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
}, "type" | "name" | "size">, "strict", z.ZodTypeAny, {
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}, {
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}>>;
contentType: z.ZodOptional<z.ZodString>;
cacheControl: z.ZodOptional<z.ZodString>;
contentEncoding: z.ZodOptional<z.ZodString>;
contentDisposition: z.ZodOptional<z.ZodString>;
}, "strict", z.ZodTypeAny, {
public: boolean;
metadata?: {
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
} | undefined;
contentType?: string | undefined;
cacheControl?: string | undefined;
contentEncoding?: string | undefined;
contentDisposition?: string | undefined;
}, {
public?: boolean | undefined;
metadata?: {
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
} | undefined;
contentType?: string | undefined;
cacheControl?: string | undefined;
contentEncoding?: string | undefined;
contentDisposition?: string | undefined;
}>;
/**
* Options for file downloads
*/
interface DownloadOptions {
/** Whether to get a temporary download URL */
temporary?: boolean;
/** Expiration time in seconds for temporary URLs */
expiresIn?: number;
/** Response content type override */
responseContentType?: string;
/** Response content disposition */
responseContentDisposition?: string;
}
/**
* Schema for validating download options
*/
declare const downloadOptionsSchema: z.ZodObject<{
temporary: z.ZodDefault<z.ZodBoolean>;
expiresIn: z.ZodOptional<z.ZodNumber>;
responseContentType: z.ZodOptional<z.ZodString>;
responseContentDisposition: z.ZodOptional<z.ZodString>;
}, "strict", z.ZodTypeAny, {
temporary: boolean;
expiresIn?: number | undefined;
responseContentType?: string | undefined;
responseContentDisposition?: string | undefined;
}, {
temporary?: boolean | undefined;
expiresIn?: number | undefined;
responseContentType?: string | undefined;
responseContentDisposition?: string | undefined;
}>;
/**
* Options for listing files
*/
interface ListOptions {
/** Maximum number of results to return */
maxResults?: number;
/** Pagination token */
pageToken?: string;
/** Whether to include file metadata in results */
includeMetadata?: boolean;
}
/**
* Schema for validating list options
*/
declare const listOptionsSchema: z.ZodObject<{
maxResults: z.ZodOptional<z.ZodNumber>;
pageToken: z.ZodOptional<z.ZodString>;
includeMetadata: z.ZodDefault<z.ZodBoolean>;
}, "strict", z.ZodTypeAny, {
includeMetadata: boolean;
maxResults?: number | undefined;
pageToken?: string | undefined;
}, {
maxResults?: number | undefined;
pageToken?: string | undefined;
includeMetadata?: boolean | undefined;
}>;
/**
* Result of a list operation
*/
interface ListResult {
/** Array of file paths or objects */
items: (string | StoredFile)[];
/** Pagination token for the next page */
nextPageToken?: string;
/** Whether there are more results */
hasMore: boolean;
}
/**
* Schema for validating list results
*/
declare const listResultSchema: z.ZodObject<{
items: z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodObject<{
/** Name of the file */
name: z.ZodString;
/** Size of the file in bytes */
size: z.ZodNumber;
/** MIME type of the file */
type: z.ZodString;
/** Last modified timestamp */
lastModified: z.ZodOptional<z.ZodNumber>;
/** Custom metadata key-value pairs */
customMetadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
} & {
path: z.ZodString;
url: z.ZodString;
createdAt: z.ZodDate;
updatedAt: z.ZodDate;
}, "strict", z.ZodTypeAny, {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}, {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
}>]>, "many">;
nextPageToken: z.ZodOptional<z.ZodString>;
hasMore: z.ZodBoolean;
}, "strict", z.ZodTypeAny, {
items: (string | {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
})[];
hasMore: boolean;
nextPageToken?: string | undefined;
}, {
items: (string | {
path: string;
type: string;
name: string;
size: number;
url: string;
createdAt: Date;
updatedAt: Date;
lastModified?: number | undefined;
customMetadata?: Record<string, string> | undefined;
})[];
hasMore: boolean;
nextPageToken?: string | undefined;
}>;
/**
* Interface for storage adapters
* @template TConfig - Type of the configuration object
*/
interface StorageAdapter<TConfig = unknown> extends BaseAdapter<TConfig> {
readonly type: AdapterType.STORAGE;
/**
* Uploads a file to storage
* @param file - The file to upload
* @param path - The destination path in storage
* @param options - Upload options
* @returns A promise that resolves to the public URL of the uploaded file
* @throws {StorageError} If the upload fails
*/
upload(file: FileLike, path: string, options?: UploadOptions): Promise<string>;
/**
* Downloads a file from storage
* @param path - The path to the file in storage
* @param options - Download options
* @returns A promise that resolves to the file data as a Blob
* @throws {StorageError} If the download fails
*/
download(path: string, options?: DownloadOptions): Promise<Blob>;
/**
* Gets a download URL for a file
* @param path - The path to the file in storage
* @param options - Download options
* @returns A promise that resolves to a download URL
* @throws {StorageError} If the operation fails
*/
getDownloadUrl(path: string, options?: Omit<DownloadOptions, 'temporary'>): Promise<string>;
/**
* Deletes a file from storage
* @param path - The path to the file in storage
* @returns A promise that resolves when the operation completes
* @throws {StorageError} If the deletion fails
*/
delete(path: string): Promise<void>;
/**
* Lists files in a storage path
* @param path - The directory path to list
* @param options - List options
* @returns A promise that resolves to a list of file paths or objects
* @throws {StorageError} If the operation fails
*/
list(path: string, options?: ListOptions): Promise<ListResult>;
/**
* Gets metadata for a file
* @param path - The path to the file in storage
* @returns A promise that resolves to the file metadata
* @throws {StorageError} If the operation fails
*/
getMetadata(path: string): Promise<StoredFile>;
/**
* Updates file metadata
* @param path - The path to the file in storage
* @param metadata - The metadata to update
* @returns A promise that resolves to the updated file metadata
* @throws {StorageError} If the operation fails
*/
updateMetadata(path: string, metadata: Partial<FileMetadata>): Promise<StoredFile>;
}
declare const baseAdapterConfigSchema: z.ZodObject<{
id: z.ZodString;
type: z.ZodNativeEnum<typeof AdapterType>;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: AdapterType;
id: string;
enabled: boolean;
debug: boolean;
}, {
type: AdapterType;
id: string;
enabled?: boolean | undefined;
debug?: boolean | undefined;
}>;
declare const authConfigSchema: z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.AUTH>;
secret: z.ZodString;
session: z.ZodOptional<z.ZodObject<{
maxAge: z.ZodDefault<z.ZodNumber>;
updateAge: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
maxAge: number;
updateAge: number;
}, {
maxAge?: number | undefined;
updateAge?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.AUTH;
id: string;
enabled: boolean;
debug: boolean;
secret: string;
session?: {
maxAge: number;
updateAge: number;
} | undefined;
}, {
type: AdapterType.AUTH;
id: string;
secret: string;
session?: {
maxAge?: number | undefined;
updateAge?: number | undefined;
} | undefined;
enabled?: boolean | undefined;
debug?: boolean | undefined;
}>;
declare const databaseConfigSchema: z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.DATABASE>;
url: z.ZodString;
ssl: z.ZodDefault<z.ZodBoolean>;
pool: z.ZodOptional<z.ZodObject<{
min: z.ZodDefault<z.ZodNumber>;
max: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
min: number;
max: number;
}, {
min?: number | undefined;
max?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.DATABASE;
id: string;
url: string;
enabled: boolean;
debug: boolean;
ssl: boolean;
pool?: {
min: number;
max: number;
} | undefined;
}, {
type: AdapterType.DATABASE;
id: string;
url: string;
enabled?: boolean | undefined;
debug?: boolean | undefined;
ssl?: boolean | undefined;
pool?: {
min?: number | undefined;
max?: number | undefined;
} | undefined;
}>;
declare const storageConfigSchema: z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.STORAGE>;
bucket: z.ZodString;
region: z.ZodOptional<z.ZodString>;
endpoint: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.STORAGE;
id: string;
enabled: boolean;
debug: boolean;
bucket: string;
region?: string | undefined;
endpoint?: string | undefined;
}, {
type: AdapterType.STORAGE;
id: string;
bucket: string;
enabled?: boolean | undefined;
debug?: boolean | undefined;
region?: string | undefined;
endpoint?: string | undefined;
}>;
declare const adapterConfigSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.AUTH>;
secret: z.ZodString;
session: z.ZodOptional<z.ZodObject<{
maxAge: z.ZodDefault<z.ZodNumber>;
updateAge: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
maxAge: number;
updateAge: number;
}, {
maxAge?: number | undefined;
updateAge?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.AUTH;
id: string;
enabled: boolean;
debug: boolean;
secret: string;
session?: {
maxAge: number;
updateAge: number;
} | undefined;
}, {
type: AdapterType.AUTH;
id: string;
secret: string;
session?: {
maxAge?: number | undefined;
updateAge?: number | undefined;
} | undefined;
enabled?: boolean | undefined;
debug?: boolean | undefined;
}>, z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.DATABASE>;
url: z.ZodString;
ssl: z.ZodDefault<z.ZodBoolean>;
pool: z.ZodOptional<z.ZodObject<{
min: z.ZodDefault<z.ZodNumber>;
max: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
min: number;
max: number;
}, {
min?: number | undefined;
max?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.DATABASE;
id: string;
url: string;
enabled: boolean;
debug: boolean;
ssl: boolean;
pool?: {
min: number;
max: number;
} | undefined;
}, {
type: AdapterType.DATABASE;
id: string;
url: string;
enabled?: boolean | undefined;
debug?: boolean | undefined;
ssl?: boolean | undefined;
pool?: {
min?: number | undefined;
max?: number | undefined;
} | undefined;
}>, z.ZodObject<{
id: z.ZodString;
enabled: z.ZodDefault<z.ZodBoolean>;
debug: z.ZodDefault<z.ZodBoolean>;
} & {
type: z.ZodLiteral<AdapterType.STORAGE>;
bucket: z.ZodString;
region: z.ZodOptional<z.ZodString>;
endpoint: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
type: AdapterType.STORAGE;
id: string;
enabled: boolean;
debug: boolean;
bucket: string;
region?: string | undefined;
endpoint?: string | undefined;
}, {
type: AdapterType.STORAGE;
id: string;
bucket: string;
enabled?: boolean | undefined;
debug?: boolean | undefined;
region?: string | undefined;
endpoint?: string | undefined;
}>]>;
declare function isAuthConfig(config: unknown): config is z.infer<typeof authConfigSchema>;
declare function isDatabaseConfig(config: unknown): config is z.infer<typeof databaseConfigSchema>;
declare function isStorageConfig(config: unknown): config is z.infer<typeof storageConfigSchema>;
declare function validateConfig<T extends z.ZodTypeAny>(schema: T, config: unknown): z.infer<T>;
/**
* Type guard for AuthAdapter
* @param adapter The adapter to check
* @returns boolean indicating if the adapter is an AuthAdapter
*/
declare function isAuthAdapter(adapter: unknown): adapter is AuthAdapter;
/**
* Type guard for DatabaseAdapter
* @param adapter The adapter to check
* @returns boolean indicating if the adapter is a DatabaseAdapter
*/
declare function isDatabaseAdapter(adapter: unknown): adapter is DatabaseAdapter;
/**
* Type guard for StorageAdapter
* @param adapter The adapter to check
* @returns boolean indicating if the adapter is a StorageAdapter
*/
declare function isStorageAdapter(adapter: unknown): adapter is StorageAdapter;
/**
* Type guard for BaseAdapter
* @param adapter The adapter to check
* @returns boolean indicating if the adapter is a BaseAdapter
*/
declare function isBaseAdapter(adapter: unknown): adapter is BaseAdapter;
declare class BuddyError extends Error {
code: string;
details?: any | undefined;
constructor(message: string, code: string, details?: any | undefined);
}
declare class DatabaseError extends BuddyError {
constructor(message: string, code: string, details?: any);
}
declare class APIError extends Error {
code: string;
status: number;
details?: any | undefined;
constructor(code: string, message: string, status?: number, details?: any | undefined);
}
declare class AuthError extends APIError {
constructor(message: string, code?: string, status?: number);
}
declare class ValidationError extends APIError {
fields: Record<string, string[]>;
constructor(message: string, fields: Record<string, string[]>);
}
/**
* Logger interface for consistent logging across the application
*/
interface Logger$1 {
/** Log an info message */
info: (...args: any[]) => void;
/** Log a warning message */
warn: (...args: any[]) => void;
/** Log an error message */
error: (...args: any[]) => void;
/** Log a debug message */
debug: (...args: any[]) => void;
}
declare enum PluginHook {
BeforeSchemaLoad = "beforeSchemaLoad",
AfterSchemaLoad = "afterSchemaLoad",
BeforeCodegen = "beforeCodegen",
AfterCodegen = "afterCodegen",
BeforeTypegen = "beforeTypegen",
AfterTypegen = "afterTypegen",
BeforeMigrate = "beforeMigrate",
AfterMigrate = "afterMigrate"
}
interface PluginContext {
/** Current working directory */
cwd: string;
/** Plugin configuration */
config: Record<string, unknown>;
/** Logger instance */
logger: Logger$1;
/** Plugin data storage */
data: Map<string, unknown>;
/** Plugin utilities */
utils: {
/** Register a hook */
registerHook: (hookName: string, handler: (...args: any[]) => any) => void;
/** Unregister a hook */
unregisterHook: (hookName: string, handler: (...args: any[]) => any) => void;
/** Call a hook */
callHook: (hookName: string, ...args: any[]) => Promise<any>;
};
}
interface Plugin {
/** Plugin name (must be unique) */
name: string;
/** Plugin version */
version: string;
/** Plugin description */
description?: string;
/**
* Initialize the plugin
* Called when the plugin is loaded
* @param context - The plugin context containing logger, config, etc.
*/
initialize?(context: PluginContext): Promise<void> | void;
/**
* Cleanup function
* Called when the plugin is unloaded
*/
destroy?(): Promise<void> | void;
/**
* Optional cleanup function (alias for destroy)
* Called when the plugin is unregistered
*/
cleanup?(context: PluginContext): Promise<void> | void;
/**
* Plugin hooks
* Keys are hook names, values are arrays of handler functions
*/
hooks?: {
[K in PluginHook]?: Array<(context: PluginContext, ...args: any[]) => Promise<void> | void>;
};
/**
* Plugin configuration schema (JSON Schema)
* Used to validate plugin configuration
*/
configSchema?: Record<string, unknown>;
}
/**
* Base interface for plugin manager options
*/
interface PluginManagerOptions {
/** Current working directory */
cwd?: string;
/** Logger instance */
logger?: Partial<Logger$1>;
/** Enable debug mode */
debug?: boolean;
/** Plugin configurations */
plugins?: Record<string, unknown>;
/** Directories to search for plugins */
pluginsDir?: string | string[];
/** Node modules directories to search for plugins */
nodeModulesDirs?: string[];
/** Configuration object */
config?: Record<string, unknown>;
/** Callback when a plugin is loaded */
onPluginLoaded?: (plugin: Plugin) => void;
/** Error handler */
onError?: (error: Error, plugin?: string, phase?: string) => void;
}
type ID = string | number;
/**
* API Buddy Shared Types
*
* This is the main entry point for all shared types used across the API Buddy ecosystem.
* All types are re-exported from their respective modules to avoid circular dependencies.
*/
/**
* Public query options interface for API consumers
* Used in React components and generated hooks
*/
interface QueryOptions {
select?: string[];
include?: string[];
orderBy?: SortOptions;
distinct?: boolean;
ids?: string[];
limit?: number;
offset?: number;
where?: Record<string, any>;
}
type SortOptions = {
field: string;
direction: 'asc' | 'desc';
};
/**
* Base logger interface used throughout the application
*/
interface Logger {
info: (message: string, ...args: any[]) => void;
warn: (message: string, ...args: any[]) => void;
error: (message: string, ...args: any[]) => void;
debug: (message: string, ...args: any[]) => void;
}
export { APIError, type AdapterConfig, type AdapterEvent, type AdapterEventEmitter, type AdapterEventListener, AdapterEventType, type AdapterFactory, type AdapterOptions, type AdapterRegistry, AdapterType, type AuthAdapter, type AuthAdapterOptions, AuthError, type AuthSession, type BaseAdapter, type BaseFieldDefinition, type BooleanFieldDefinition, BuddyError, type DatabaseAdapter, type DatabaseAdapterQueryOptions, DatabaseError, type DateFieldDefinition, type DownloadOptions, type EmailPasswordCredentials, type ExecutableAdapter, type FieldDefinition, type FieldType, type FileLike, type FileMetadata, type ID, type IDFieldDefinition, type JsonFieldDefinition, type ListOptions, type ListResult, type Logger, type ModelDefinition, type NumberFieldDefinition, type Operator, type Plugin, type PluginContext, PluginHook, type PluginManagerOptions, type QueryFilter, type QueryOptions, type RelationFieldDefinition, type Schema, type SocialProviderConfig, type StorageAdapter, type StoredFile, type StringFieldDefinition, type SubscribableAdapter, type TransactionOptions, type UploadOptions, type UserProfile, ValidationError, adapterConfigSchema, authConfigSchema, authSessionSchema, baseAdapterConfigSchema, databaseConfigSchema, databaseQueryOptionsSchema, downloadOptionsSchema, emailPasswordCredentialsSchema, fieldTypeSchema, fileMetadataSchema, isAuthAdapter, isAuthConfig, isAuthSession, isBaseAdapter, isDatabaseAdapter, isDatabaseConfig, isEmailPasswordCredentials, isStorageAdapter, isStorageConfig, isUserProfile, listOptionsSchema, listResultSchema, operatorSchema, queryFilterSchema, socialProviderConfigSchema, storageConfigSchema, storedFileSchema, transactionOptionsSchema, uploadOptionsSchema, userProfileSchema, validateConfig };