@mercnet/core
Version:
Core utilities and types for MercNet ecosystem
578 lines (567 loc) • 21.1 kB
TypeScript
import { GraphQLClient, RequestOptions, Variables } from 'graphql-request';
import { z } from 'zod';
export { z } from 'zod';
/**
* Common types used throughout the MercNet ecosystem
*/
interface BaseEntity {
id: string;
createdAt: Date;
updatedAt: Date;
}
interface ApiResponse<T = unknown> {
data?: T;
error?: ApiError;
success: boolean;
message?: string;
}
interface ApiError {
code: string;
message: string;
details?: Record<string, unknown>;
}
interface PaginationParams {
page?: number;
limit?: number;
offset?: number;
}
interface PaginatedResponse<T> {
data: T[];
pagination: {
total: number;
page: number;
limit: number;
totalPages: number;
hasNext: boolean;
hasPrev: boolean;
};
}
interface GraphQLResponse<T = unknown> {
data?: T;
errors?: GraphQLError[];
}
interface GraphQLError {
message: string;
locations?: Array<{
line: number;
column: number;
}>;
path?: Array<string | number>;
extensions?: Record<string, unknown>;
}
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type RequiredKeys<T, K extends keyof T> = T & Required<Pick<T, K>>;
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
type Environment = 'development' | 'production' | 'test' | 'staging';
interface BaseConfig {
environment: Environment;
apiUrl: string;
graphqlUrl?: string;
debug?: boolean;
}
interface Market {
id: number;
name?: string | null;
short_name?: string | null;
ticker: string;
price?: string | null;
type?: string | null;
created_at?: string | null;
last_update_at?: string | null;
trend_status?: string | null;
sentiment?: string | null;
sentiment_update_at?: string | null;
market_activity_score_1h?: string | null;
market_activity_score_1d?: string | null;
data?: Record<string, unknown> | null;
status?: string | null;
}
/**
* Essential utilities for MercNet Core v1
*/
declare const capitalize: (str: string) => string;
declare const camelCase: (str: string) => string;
declare const pick: <T extends Record<string, any>, K extends keyof T>(obj: T, keys: K[]) => Pick<T, K>;
declare const isObject: (item: unknown) => item is Record<string, any>;
declare const isString: (value: unknown) => value is string;
declare const isNumber: (value: unknown) => value is number;
declare const isBoolean: (value: unknown) => value is boolean;
declare const isFunction: (value: unknown) => value is Function;
declare const isArray: <T>(value: unknown) => value is T[];
declare const unique: <T>(array: T[]) => T[];
declare const sleep: (ms: number) => Promise<void>;
declare const retry: <T>(fn: () => Promise<T>, options: {
retries: number;
delay?: number;
backoff?: number;
}) => Promise<T>;
declare const formatDate: (date: Date, format?: string) => string;
declare const isValidDate: (date: unknown) => date is Date;
declare const getEnv: (key: string, defaultValue?: string) => string;
declare const isDevelopment: () => boolean;
declare const isProduction: () => boolean;
declare class MercNetError extends Error {
code?: string | undefined;
details?: Record<string, unknown> | undefined;
constructor(message: string, code?: string | undefined, details?: Record<string, unknown> | undefined);
}
declare const createError: (message: string, code?: string, details?: Record<string, unknown>) => MercNetError;
type Exact<T extends {
[key: string]: unknown;
}> = {
[K in keyof T]: T[K];
};
type GraphQLClientRequestHeaders = RequestOptions['requestHeaders'];
/** All built-in and custom scalars, mapped to their actual values */
type Scalars = {
ID: {
input: string;
output: string;
};
String: {
input: string;
output: string;
};
Boolean: {
input: boolean;
output: boolean;
};
Int: {
input: number;
output: number;
};
Float: {
input: number;
output: number;
};
BigFloat: {
input: any;
output: any;
};
BigInt: {
input: string;
output: string;
};
Cursor: {
input: any;
output: any;
};
Date: {
input: string;
output: string;
};
Datetime: {
input: any;
output: any;
};
JSON: {
input: Record<string, any>;
output: Record<string, any>;
};
Opaque: {
input: any;
output: any;
};
Time: {
input: string;
output: string;
};
UUID: {
input: string;
output: string;
};
};
type GetAllMarketsQueryVariables = Exact<{
[key: string]: never;
}>;
type GetAllMarketsQuery = {
__typename?: 'Query';
marketCollection?: {
__typename?: 'marketConnection';
edges: Array<{
__typename?: 'marketEdge';
node: {
__typename?: 'market';
id: number;
name?: string | null;
short_name?: string | null;
ticker: string;
price?: any | null;
type?: string | null;
created_at?: any | null;
last_update_at?: any | null;
trend_status?: string | null;
sentiment?: string | null;
sentiment_update_at?: any | null;
market_activity_score_1h?: any | null;
market_activity_score_1d?: any | null;
data?: Record<string, any> | null;
status?: string | null;
};
}>;
} | null;
};
type GetMarketByIdQueryVariables = Exact<{
id: Scalars['Int']['input'];
}>;
type GetMarketByIdQuery = {
__typename?: 'Query';
marketCollection?: {
__typename?: 'marketConnection';
edges: Array<{
__typename?: 'marketEdge';
node: {
__typename?: 'market';
id: number;
name?: string | null;
short_name?: string | null;
ticker: string;
price?: any | null;
type?: string | null;
created_at?: any | null;
last_update_at?: any | null;
trend_status?: string | null;
sentiment?: string | null;
sentiment_update_at?: any | null;
market_activity_score_1h?: any | null;
market_activity_score_1d?: any | null;
data?: Record<string, any> | null;
status?: string | null;
};
}>;
} | null;
};
type GetMarketByTickerQueryVariables = Exact<{
ticker: Scalars['String']['input'];
}>;
type GetMarketByTickerQuery = {
__typename?: 'Query';
marketCollection?: {
__typename?: 'marketConnection';
edges: Array<{
__typename?: 'marketEdge';
node: {
__typename?: 'market';
id: number;
name?: string | null;
short_name?: string | null;
ticker: string;
price?: any | null;
type?: string | null;
created_at?: any | null;
last_update_at?: any | null;
trend_status?: string | null;
sentiment?: string | null;
sentiment_update_at?: any | null;
market_activity_score_1h?: any | null;
market_activity_score_1d?: any | null;
data?: Record<string, any> | null;
status?: string | null;
};
}>;
} | null;
};
type GetMarketsByStatusQueryVariables = Exact<{
status: Scalars['String']['input'];
}>;
type GetMarketsByStatusQuery = {
__typename?: 'Query';
marketCollection?: {
__typename?: 'marketConnection';
edges: Array<{
__typename?: 'marketEdge';
node: {
__typename?: 'market';
id: number;
name?: string | null;
short_name?: string | null;
ticker: string;
price?: any | null;
type?: string | null;
created_at?: any | null;
last_update_at?: any | null;
trend_status?: string | null;
sentiment?: string | null;
sentiment_update_at?: any | null;
market_activity_score_1h?: any | null;
market_activity_score_1d?: any | null;
data?: Record<string, any> | null;
status?: string | null;
};
}>;
} | null;
};
type SdkFunctionWrapper = <T>(action: (requestHeaders?: Record<string, string>) => Promise<T>, operationName: string, operationType?: string, variables?: any) => Promise<T>;
declare function getSdk(client: GraphQLClient, withWrapper?: SdkFunctionWrapper): {
GetAllMarkets(variables?: GetAllMarketsQueryVariables, requestHeaders?: GraphQLClientRequestHeaders, signal?: RequestInit["signal"]): Promise<GetAllMarketsQuery>;
GetMarketById(variables: GetMarketByIdQueryVariables, requestHeaders?: GraphQLClientRequestHeaders, signal?: RequestInit["signal"]): Promise<GetMarketByIdQuery>;
GetMarketByTicker(variables: GetMarketByTickerQueryVariables, requestHeaders?: GraphQLClientRequestHeaders, signal?: RequestInit["signal"]): Promise<GetMarketByTickerQuery>;
GetMarketsByStatus(variables: GetMarketsByStatusQueryVariables, requestHeaders?: GraphQLClientRequestHeaders, signal?: RequestInit["signal"]): Promise<GetMarketsByStatusQuery>;
};
type Sdk = ReturnType<typeof getSdk>;
/**
* GraphQL utilities and client configuration for MercNet ecosystem
* Updated to use GraphQL Code Generator with traditional SDK approach
*/
interface GraphQLClientConfig {
endpoint: string;
headers?: Record<string, string>;
retries?: number;
debug?: boolean;
}
declare class MercNetGraphQLClient {
private client;
private config;
private readonly sdk;
constructor(config: GraphQLClientConfig);
setHeaders(headers: Record<string, string>): void;
setHeader(key: string, value: string): void;
query<T = any, V extends Variables = Variables>(query: string, variables?: V, requestHeaders?: Record<string, string>): Promise<T>;
mutate<T = any, V extends Variables = Variables>(mutation: string, variables?: V, requestHeaders?: Record<string, string>): Promise<T>;
rawRequest<T = any, V extends Variables = Variables>(query: string, variables?: V, requestHeaders?: Record<string, string>): Promise<GraphQLResponse<T>>;
getAllMarkets(): Promise<Market[]>;
getMarketById(id: number): Promise<Market | null>;
getMarketByTicker(ticker: string): Promise<Market | null>;
getMarketsByStatus(status: string): Promise<Market[]>;
private transformMarketsResponse;
private handleGraphQLError;
}
declare const createGraphQLClient: (config: GraphQLClientConfig) => MercNetGraphQLClient;
declare const COMMON_FRAGMENTS: {
MARKET_FRAGMENT: string;
PAGINATION_INFO: string;
ERROR_INFO: string;
};
declare class QueryBuilder {
private fields;
private fragments;
private variables;
field(name: string, subFields?: string[]): this;
fragment(name: string, fragment: string): this;
variable(name: string, type: string): this;
build(operationType?: 'query' | 'mutation', operationName?: string): string;
}
declare const createQueryBuilder: () => QueryBuilder;
declare const gql: (strings: TemplateStringsArray, ...values: any[]) => string;
interface GraphQLSchemaInfo {
types: string[];
queries: string[];
mutations: string[];
subscriptions: string[];
}
declare const getSchemaInfo: (client: MercNetGraphQLClient) => Promise<GraphQLSchemaInfo>;
/**
* Validation utilities with Zod integration for MercNet ecosystem
*/
declare const baseEntitySchema: z.ZodObject<{
id: z.ZodString;
createdAt: z.ZodDate;
updatedAt: z.ZodDate;
}, "strip", z.ZodTypeAny, {
id: string;
createdAt: Date;
updatedAt: Date;
}, {
id: string;
createdAt: Date;
updatedAt: Date;
}>;
declare const paginationParamsSchema: z.ZodObject<{
page: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
limit: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
offset: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
page: number;
limit: number;
offset?: number | undefined;
}, {
page?: number | undefined;
limit?: number | undefined;
offset?: number | undefined;
}>;
declare const apiResponseSchema: <T extends z.ZodType>(dataSchema: T) => z.ZodObject<{
data: z.ZodOptional<T>;
error: z.ZodOptional<z.ZodObject<{
code: z.ZodString;
message: z.ZodString;
details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}>>;
success: z.ZodBoolean;
message: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
data: z.ZodOptional<T>;
error: z.ZodOptional<z.ZodObject<{
code: z.ZodString;
message: z.ZodString;
details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}>>;
success: z.ZodBoolean;
message: z.ZodOptional<z.ZodString>;
}>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
data: z.ZodOptional<T>;
error: z.ZodOptional<z.ZodObject<{
code: z.ZodString;
message: z.ZodString;
details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}>>;
success: z.ZodBoolean;
message: z.ZodOptional<z.ZodString>;
}>, any>[k]; } : never, z.baseObjectInputType<{
data: z.ZodOptional<T>;
error: z.ZodOptional<z.ZodObject<{
code: z.ZodString;
message: z.ZodString;
details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}>>;
success: z.ZodBoolean;
message: z.ZodOptional<z.ZodString>;
}> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<{
data: z.ZodOptional<T>;
error: z.ZodOptional<z.ZodObject<{
code: z.ZodString;
message: z.ZodString;
details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}, {
code: string;
message: string;
details?: Record<string, unknown> | undefined;
}>>;
success: z.ZodBoolean;
message: z.ZodOptional<z.ZodString>;
}>[k_1]; } : never>;
declare const validators: {
email: z.ZodString;
password: z.ZodString;
url: z.ZodString;
phone: z.ZodString;
uuid: z.ZodString;
slug: z.ZodString;
hex: z.ZodString;
dateString: z.ZodString;
dateRange: z.ZodEffects<z.ZodObject<{
start: z.ZodDate;
end: z.ZodDate;
}, "strip", z.ZodTypeAny, {
start: Date;
end: Date;
}, {
start: Date;
end: Date;
}>, {
start: Date;
end: Date;
}, {
start: Date;
end: Date;
}>;
positiveNumber: z.ZodNumber;
nonNegativeNumber: z.ZodNumber;
percentage: z.ZodNumber;
currency: z.ZodNumber;
nonEmptyString: z.ZodString;
alphanumeric: z.ZodString;
noWhitespace: z.ZodString;
};
declare const environmentSchema: z.ZodEnum<["development", "production", "test", "staging"]>;
declare const baseConfigSchema: z.ZodObject<{
environment: z.ZodEnum<["development", "production", "test", "staging"]>;
apiUrl: z.ZodString;
graphqlUrl: z.ZodOptional<z.ZodString>;
debug: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
}, "strip", z.ZodTypeAny, {
debug: boolean;
environment: "development" | "production" | "test" | "staging";
apiUrl: string;
graphqlUrl?: string | undefined;
}, {
environment: "development" | "production" | "test" | "staging";
apiUrl: string;
debug?: boolean | undefined;
graphqlUrl?: string | undefined;
}>;
declare class ValidationError extends MercNetError {
issues: z.ZodIssue[];
constructor(message: string, issues: z.ZodIssue[]);
}
declare const validate: <T>(schema: z.ZodSchema<T>, data: unknown, options?: {
throwOnError?: boolean;
errorMessage?: string;
}) => {
success: true;
data: T;
} | {
success: false;
error: ValidationError;
};
declare const validateAndThrow: <T>(schema: z.ZodSchema<T>, data: unknown, errorMessage?: string) => T;
declare const createArraySchema: <T extends z.ZodType>(itemSchema: T, options?: {
minLength?: number;
maxLength?: number;
unique?: boolean;
}) => z.ZodArray<T> | z.ZodEffects<z.ZodArray<T>, z.infer<T>[], z.infer<T>[]>;
declare const createOptionalWithDefault: <T extends z.ZodType>(schema: T, defaultValue: z.infer<T>) => z.ZodDefault<z.ZodOptional<T>>;
declare const transforms: {
stringToNumber: z.ZodEffects<z.ZodString, number, string>;
stringToBoolean: z.ZodEffects<z.ZodString, boolean, string>;
stringToDate: z.ZodEffects<z.ZodString, Date, string>;
trimString: z.ZodEffects<z.ZodString, string, string>;
toLowerCase: z.ZodEffects<z.ZodString, string, string>;
toUpperCase: z.ZodEffects<z.ZodString, string, string>;
};
declare const createConditionalSchema: <T extends z.ZodRawShape>(baseSchema: z.ZodObject<T>, conditions: Array<{
when: (data: z.infer<z.ZodObject<T>>) => boolean;
then: z.ZodSchema;
message?: string;
}>) => z.ZodEffects<z.ZodObject<T, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<T>[k_1]; } : never>, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_3 ? { [k in keyof T_3]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_4 ? { [k_1 in keyof T_4]: z.baseObjectInputType<T>[k_1]; } : never>;
declare const customValidators: {
strongPassword: z.ZodEffects<z.ZodString, string, string>;
uniqueArray: <T>(itemSchema: z.ZodSchema<T>, keyExtractor?: (item: T) => any) => z.ZodEffects<z.ZodArray<z.ZodType<T, z.ZodTypeDef, T>, "many">, T[], T[]>;
futureDate: z.ZodEffects<z.ZodDate, Date, Date>;
pastDate: z.ZodEffects<z.ZodDate, Date, Date>;
};
/**
* @mercnet/core - Core utilities and types for MercNet ecosystem
*
* This package provides foundational utilities, types, and GraphQL clients
* that are shared across the MercNet platform.
*/
declare const VERSION = "0.1.0";
export { type ApiError, type ApiResponse, apiResponseSchema as ApiResponseSchema, type BaseConfig, baseConfigSchema as BaseConfigSchema, type BaseEntity, baseEntitySchema as BaseEntitySchema, COMMON_FRAGMENTS, type DeepPartial, type Environment, environmentSchema as EnvironmentSchema, type GetAllMarketsQuery, type GetAllMarketsQueryVariables, type GetMarketByIdQuery, type GetMarketByIdQueryVariables, type GetMarketByTickerQuery, type GetMarketByTickerQueryVariables, type GetMarketsByStatusQuery, type GetMarketsByStatusQueryVariables, type GraphQLClientConfig, type GraphQLError, type GraphQLResponse, type GraphQLSchemaInfo, type Market, MercNetError, MercNetGraphQLClient, type Optional, type PaginatedResponse, type PaginationParams, paginationParamsSchema as PaginationParamsSchema, QueryBuilder, type RequiredKeys, type Sdk, VERSION, ValidationError, camelCase, capitalize, createArraySchema, createConditionalSchema, createError, createGraphQLClient, createOptionalWithDefault, createQueryBuilder, customValidators, formatDate, getEnv, getSchemaInfo, gql, isArray, isBoolean, isDevelopment, isFunction, isNumber, isObject, isProduction, isString, isValidDate, pick, retry, sleep, transforms, unique, validate, validateAndThrow, validators };