@syfthub/sdk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -3
- package/dist/index.cjs +219 -102
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +165 -40
- package/dist/index.d.ts +165 -40
- package/dist/index.js +219 -102
- package/dist/index.js.map +1 -1
- package/package.json +5 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/utils.ts","../src/client.ts","../src/resources/auth.ts","../src/resources/users.ts","../src/pagination.ts","../src/resources/my-endpoints.ts","../src/resources/hub.ts","../src/models/common.ts","../src/models/endpoint.ts","../src/models/accounting.ts","../src/resources/accounting.ts","../src/resources/chat.ts","../src/resources/syftai.ts","../src/index.ts"],"names":["NotFoundError","data"],"mappings":";;;;;;;;;;;AAAA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,4BAAA,EAAA,MAAA,4BAAA;AAAA,EAAA,iCAAA,EAAA,MAAA,iCAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,8BAAA,EAAA,MAAA,8BAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,aAAA,EAAA,MAAA,aAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,sBAAA,EAAA,MAAA,sBAAA;AAAA,EAAA,eAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAAA,IAGa,YAAA,CAAA,CAcA,QAAA,CAAA,CAeA,mBAAA,CAAA,CAWA,kBAAA,CAAA,CAUA,aAAA,CAAA,CAWA,iBAaA,YAAA,CAAA,CAaA,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IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,MAAA,CAAO,WAAA,EAAa,OAAO,YAAY,CAAA;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,eAAA,GAA2B;AAC7B,IAAA,OAAO,IAAA,CAAK,KAAK,SAAA,EAAU;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,IAAI,sBAAA,GAAkC;AACpC,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,OAAA,CAAQ,aAAA,IAAiB,OAAO,wBAAwB,CAAA;AACzE,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,OAAA,CAAQ,eAAA,IAAmB,OAAO,0BAA0B,CAAA;AAC/E,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,kBAAA,IAAsB,OAAO,6BAA6B,CAAA;AACxF,IAAA,OAAO,OAAA,CAAQ,GAAA,IAAO,KAAA,IAAS,QAAQ,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,GAAc;AAAA,EAGd;AACF;;;AYtWA,WAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Base error class for all SyftHub SDK errors.\n */\nexport class SyftHubError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SyftHubError';\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when an API request fails with an error status code.\n */\nexport class APIError extends SyftHubError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'APIError';\n }\n}\n\n/**\n * Error thrown when authentication is required but not provided,\n * or when credentials are invalid (HTTP 401).\n */\nexport class AuthenticationError extends SyftHubError {\n constructor(message: string = 'Authentication required') {\n super(message);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Error thrown when the user doesn't have permission to access\n * a resource (HTTP 403).\n */\nexport class AuthorizationError extends SyftHubError {\n constructor(message: string = 'Permission denied') {\n super(message);\n this.name = 'AuthorizationError';\n }\n}\n\n/**\n * Error thrown when a requested resource is not found (HTTP 404).\n */\nexport class NotFoundError extends SyftHubError {\n constructor(message: string = 'Resource not found') {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Error thrown when request validation fails (HTTP 422).\n * Contains field-level error details when available.\n */\nexport class ValidationError extends SyftHubError {\n constructor(\n message: string,\n public readonly errors?: Record<string, string[]>\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when a network request fails (connection errors, timeouts).\n */\nexport class NetworkError extends SyftHubError {\n constructor(\n message: string = 'Network request failed',\n public readonly cause?: Error\n ) {\n super(message);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Error thrown when SDK configuration is invalid.\n */\nexport class ConfigurationError extends SyftHubError {\n constructor(message: string = 'Invalid SDK configuration') {\n super(message);\n this.name = 'ConfigurationError';\n }\n}\n\n// =============================================================================\n// User Registration Errors\n// =============================================================================\n\n/**\n * Error thrown when username or email already exists in SyftHub (HTTP 409).\n *\n * This error indicates a duplicate user registration attempt.\n * The `field` property indicates which field caused the conflict.\n *\n * @example\n * ```typescript\n * try {\n * await client.auth.register({ username: \"john\", email: \"john@example.com\", ... });\n * } catch (error) {\n * if (error instanceof UserAlreadyExistsError) {\n * console.log(`${error.field} is already taken`);\n * }\n * }\n * ```\n */\nexport class UserAlreadyExistsError extends SyftHubError {\n /** The field that caused the conflict (\"username\" or \"email\") */\n public readonly field?: string;\n\n constructor(\n message: string = 'Username or email already exists',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'UserAlreadyExistsError';\n // Extract field from detail if available\n if (detail && typeof detail === 'object' && 'field' in detail) {\n this.field = (detail as { field?: string }).field;\n }\n }\n}\n\n// =============================================================================\n// Accounting-related Errors\n// =============================================================================\n\n/**\n * Error thrown when email already exists in the accounting service during registration.\n *\n * This error indicates that the user needs to provide their existing\n * accounting password to link their SyftHub account with their existing\n * accounting account.\n *\n * @example\n * ```typescript\n * try {\n * await client.auth.register({ username: \"john\", email: \"john@example.com\", ... });\n * } catch (error) {\n * if (error instanceof AccountingAccountExistsError) {\n * // Prompt user for their existing accounting password\n * const accountingPassword = prompt(\"Enter your existing accounting password:\");\n * // Retry registration with the password\n * await client.auth.register({\n * username: \"john\",\n * email: \"john@example.com\",\n * ...,\n * accountingPassword\n * });\n * }\n * }\n * ```\n */\nexport class AccountingAccountExistsError extends SyftHubError {\n /** Indicates that the user needs to provide their existing accounting password */\n public readonly requiresAccountingPassword = true;\n\n constructor(\n message: string = 'This email already has an account in the accounting service',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AccountingAccountExistsError';\n }\n}\n\n/**\n * Error thrown when the provided accounting password is invalid.\n */\nexport class InvalidAccountingPasswordError extends SyftHubError {\n constructor(\n message: string = 'The provided accounting password is invalid',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'InvalidAccountingPasswordError';\n }\n}\n\n/**\n * Error thrown when the accounting service is unavailable or returns an error.\n */\nexport class AccountingServiceUnavailableError extends SyftHubError {\n constructor(\n message: string = 'Accounting service is unavailable',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AccountingServiceUnavailableError';\n }\n}\n","import {\n AccountingAccountExistsError,\n AccountingServiceUnavailableError,\n APIError,\n AuthenticationError,\n AuthorizationError,\n InvalidAccountingPasswordError,\n NetworkError,\n NotFoundError,\n UserAlreadyExistsError,\n ValidationError,\n} from './errors.js';\nimport { toCamelCase, toSnakeCase, buildSearchParams } from './utils.js';\n\n/**\n * Options for HTTP requests.\n */\nexport interface RequestOptions {\n /** Whether to include the Authorization header (default: true) */\n includeAuth?: boolean;\n /** Whether to send body as form-urlencoded instead of JSON */\n isFormData?: boolean;\n /** Request-specific timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Internal request options including body and params.\n */\ninterface InternalRequestOptions extends RequestOptions {\n body?: unknown;\n params?: Record<string, unknown>;\n}\n\n/**\n * Auth tokens returned from login/refresh.\n */\nexport interface AuthTokens {\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n}\n\n/**\n * Internal HTTP client for making API requests.\n *\n * Handles:\n * - Bearer token authentication\n * - Automatic token refresh on 401 responses\n * - JSON serialization/deserialization\n * - snake_case <-> camelCase conversion\n * - Error handling and exception mapping\n */\nexport class HTTPClient {\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n\n /**\n * Create a new HTTP client.\n *\n * @param baseUrl - Base URL for all API requests (without trailing slash)\n * @param timeout - Default timeout in milliseconds (default: 30000)\n */\n constructor(\n private readonly baseUrl: string,\n private readonly timeout: number = 30000\n ) {}\n\n /**\n * Set authentication tokens.\n */\n setTokens(access: string, refresh: string): void {\n this.accessToken = access;\n this.refreshToken = refresh;\n }\n\n /**\n * Get current authentication tokens.\n */\n getTokens(): AuthTokens | null {\n if (!this.accessToken || !this.refreshToken) {\n return null;\n }\n return {\n accessToken: this.accessToken,\n refreshToken: this.refreshToken,\n tokenType: 'bearer',\n };\n }\n\n /**\n * Clear authentication tokens.\n */\n clearTokens(): void {\n this.accessToken = null;\n this.refreshToken = null;\n }\n\n /**\n * Check if the client has valid tokens.\n */\n hasTokens(): boolean {\n return this.accessToken !== null;\n }\n\n /**\n * Make a GET request.\n */\n async get<T>(\n path: string,\n params?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<T> {\n return this.request<T>('GET', path, { ...options, params });\n }\n\n /**\n * Make a POST request.\n */\n async post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, { ...options, body });\n }\n\n /**\n * Make a PUT request.\n */\n async put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, { ...options, body });\n }\n\n /**\n * Make a PATCH request.\n */\n async patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('PATCH', path, { ...options, body });\n }\n\n /**\n * Make a DELETE request.\n */\n async delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /**\n * Make an HTTP request with automatic retry on 401.\n */\n private async request<T>(\n method: string,\n path: string,\n options: InternalRequestOptions = {}\n ): Promise<T> {\n const { includeAuth = true, isFormData = false, timeout, body, params } = options;\n\n // Build URL with query params\n let url = `${this.baseUrl}${path}`;\n if (params) {\n const searchParams = buildSearchParams(params);\n const queryString = searchParams.toString();\n if (queryString) {\n url += `?${queryString}`;\n }\n }\n\n // Build headers\n const headers: Record<string, string> = {};\n\n if (includeAuth && this.accessToken) {\n headers['Authorization'] = `Bearer ${this.accessToken}`;\n }\n\n // Build body\n let requestBody: string | undefined;\n if (body !== undefined) {\n if (isFormData) {\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n // For form data, convert to URLSearchParams\n const formData = new URLSearchParams();\n for (const [key, value] of Object.entries(body as Record<string, unknown>)) {\n if (value !== undefined && value !== null) {\n formData.append(key, String(value));\n }\n }\n requestBody = formData.toString();\n } else {\n headers['Content-Type'] = 'application/json';\n // Convert camelCase to snake_case for JSON bodies\n requestBody = JSON.stringify(toSnakeCase(body));\n }\n }\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout ?? this.timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: requestBody,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Handle 401 with automatic token refresh\n if (response.status === 401 && includeAuth && this.refreshToken) {\n // Attempt to refresh the token\n await this.attemptTokenRefresh();\n\n // Retry the original request with new token\n return this.request<T>(method, path, {\n ...options,\n // Mark that we shouldn't retry again to prevent infinite loops\n includeAuth: true,\n });\n }\n\n return await this.handleResponse<T>(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof SyftHubError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new NetworkError('Request timed out', error);\n }\n throw new NetworkError(error.message, error);\n }\n\n throw new NetworkError('Unknown network error');\n }\n }\n\n /**\n * Handle the HTTP response and convert to the expected type.\n */\n private async handleResponse<T>(response: Response): Promise<T> {\n // Try to parse response as JSON\n let data: unknown;\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json')) {\n try {\n data = await response.json();\n } catch {\n data = null;\n }\n } else {\n // For non-JSON responses, use text\n const text = await response.text();\n data = text || null;\n }\n\n // Handle error responses\n if (!response.ok) {\n this.handleErrorResponse(response.status, data);\n }\n\n // Convert snake_case to camelCase and parse dates\n return toCamelCase<T>(data);\n }\n\n /**\n * Handle error responses by throwing appropriate exceptions.\n */\n private handleErrorResponse(status: number, data: unknown): never {\n const message = this.extractErrorMessage(data);\n const { code, detail } = this.extractErrorCodeAndDetail(data);\n\n // Check for domain-specific errors based on error code first\n if (code) {\n switch (code) {\n // User registration errors\n case 'USER_ALREADY_EXISTS':\n throw new UserAlreadyExistsError(message, detail);\n // Accounting-related errors\n case 'ACCOUNTING_ACCOUNT_EXISTS':\n throw new AccountingAccountExistsError(message, detail);\n case 'INVALID_ACCOUNTING_PASSWORD':\n throw new InvalidAccountingPasswordError(message, detail);\n case 'ACCOUNTING_SERVICE_UNAVAILABLE':\n throw new AccountingServiceUnavailableError(message, detail);\n }\n }\n\n // Standard status code handling\n switch (status) {\n case 401:\n throw new AuthenticationError(message);\n case 403:\n throw new AuthorizationError(message);\n case 404:\n throw new NotFoundError(message);\n case 422:\n throw new ValidationError(message, this.extractValidationErrors(data));\n default:\n throw new APIError(message, status, data);\n }\n }\n\n /**\n * Extract error code and detail from API response.\n * Used for accounting-specific error handling.\n */\n private extractErrorCodeAndDetail(\n data: unknown\n ): { code?: string; detail?: unknown } {\n if (!data || typeof data !== 'object') {\n return {};\n }\n\n // FastAPI returns { detail: { code: \"...\", message: \"...\", ... } }\n if ('detail' in data) {\n const detail = (data as { detail: unknown }).detail;\n if (detail && typeof detail === 'object' && 'code' in detail) {\n const innerDetail = detail as { code?: string };\n return {\n code: innerDetail.code,\n detail: detail,\n };\n }\n }\n\n return {};\n }\n\n /**\n * Extract error message from API response.\n */\n private extractErrorMessage(data: unknown): string {\n if (typeof data === 'string') {\n return data;\n }\n\n if (data && typeof data === 'object') {\n // FastAPI style: { detail: \"message\" }\n if ('detail' in data) {\n const detail = (data as { detail: unknown }).detail;\n if (typeof detail === 'string') {\n return detail;\n }\n // FastAPI validation errors: { detail: [{ msg: \"...\", loc: [...] }] }\n if (Array.isArray(detail) && detail.length > 0) {\n const firstError = detail[0] as { msg?: string };\n if (firstError?.msg) {\n return firstError.msg;\n }\n }\n }\n\n // Generic: { message: \"...\" } or { error: \"...\" }\n if ('message' in data && typeof (data as { message: unknown }).message === 'string') {\n return (data as { message: string }).message;\n }\n if ('error' in data && typeof (data as { error: unknown }).error === 'string') {\n return (data as { error: string }).error;\n }\n }\n\n return 'An error occurred';\n }\n\n /**\n * Extract field-level validation errors from API response.\n */\n private extractValidationErrors(data: unknown): Record<string, string[]> | undefined {\n if (!data || typeof data !== 'object' || !('detail' in data)) {\n return undefined;\n }\n\n const detail = (data as { detail: unknown }).detail;\n if (!Array.isArray(detail)) {\n return undefined;\n }\n\n const errors: Record<string, string[]> = {};\n\n for (const error of detail) {\n if (typeof error === 'object' && error !== null && 'loc' in error && 'msg' in error) {\n const { loc, msg } = error as { loc: unknown[]; msg: string };\n // loc is typically ['body', 'field_name']\n const field = String(loc[loc.length - 1] ?? 'unknown');\n if (!errors[field]) {\n errors[field] = [];\n }\n errors[field].push(msg);\n }\n }\n\n return Object.keys(errors).length > 0 ? errors : undefined;\n }\n\n /**\n * Attempt to refresh the access token using the refresh token.\n */\n private async attemptTokenRefresh(): Promise<void> {\n // If already refreshing, wait for the existing refresh to complete\n if (this.isRefreshing && this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.isRefreshing = true;\n\n this.refreshPromise = (async () => {\n try {\n const response = await fetch(`${this.baseUrl}/api/v1/auth/refresh`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ refresh_token: this.refreshToken }),\n });\n\n if (!response.ok) {\n // Refresh failed, clear tokens\n this.clearTokens();\n throw new AuthenticationError('Token refresh failed');\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n };\n\n this.accessToken = data.access_token;\n this.refreshToken = data.refresh_token;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n await this.refreshPromise;\n }\n}\n\n// Import SyftHubError for type checking\nimport { SyftHubError } from './errors.js';\n","/**\n * Convert a snake_case string to camelCase.\n *\n * @example\n * snakeToCamel('created_at') // 'createdAt'\n * snakeToCamel('full_name') // 'fullName'\n */\nexport function snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/**\n * Convert a camelCase string to snake_case.\n *\n * @example\n * camelToSnake('createdAt') // 'created_at'\n * camelToSnake('fullName') // 'full_name'\n */\nexport function camelToSnake(str: string): string {\n return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n/**\n * Regular expression to match ISO 8601 date strings.\n */\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n/**\n * Check if a value looks like an ISO date string.\n */\nfunction isISODateString(value: unknown): value is string {\n return typeof value === 'string' && ISO_DATE_REGEX.test(value);\n}\n\n/**\n * Recursively transform object keys using the provided transformer function.\n * Optionally parses ISO date strings to Date objects.\n *\n * @param obj - The object to transform\n * @param keyTransformer - Function to transform each key\n * @param parseDates - Whether to parse ISO date strings to Date objects\n */\nexport function transformKeys<T>(\n obj: unknown,\n keyTransformer: (key: string) => string,\n parseDates = true\n): T {\n // Handle null and undefined\n if (obj === null || obj === undefined) {\n return obj as T;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => transformKeys(item, keyTransformer, parseDates)) as T;\n }\n\n // Handle date strings\n if (parseDates && isISODateString(obj)) {\n return new Date(obj) as T;\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const transformed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n transformed[keyTransformer(key)] = transformKeys(value, keyTransformer, parseDates);\n }\n return transformed as T;\n }\n\n // Return primitives as-is\n return obj as T;\n}\n\n/**\n * Convert all keys in an object from camelCase to snake_case.\n * Does not parse dates (for request bodies).\n */\nexport function toSnakeCase<T>(obj: unknown): T {\n return transformKeys<T>(obj, camelToSnake, false);\n}\n\n/**\n * Convert all keys in an object from snake_case to camelCase.\n * Parses ISO date strings to Date objects (for response bodies).\n */\nexport function toCamelCase<T>(obj: unknown): T {\n return transformKeys<T>(obj, snakeToCamel, true);\n}\n\n/**\n * Build URL search params from an object, filtering out undefined values.\n */\nexport function buildSearchParams(params: Record<string, unknown>): URLSearchParams {\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(camelToSnake(key), String(value));\n }\n }\n\n return searchParams;\n}\n","import { HTTPClient, type AuthTokens } from './http.js';\nimport { ConfigurationError, SyftHubError } from './errors.js';\nimport { AuthResource } from './resources/auth.js';\nimport { UsersResource } from './resources/users.js';\nimport { MyEndpointsResource } from './resources/my-endpoints.js';\nimport { HubResource } from './resources/hub.js';\nimport { AccountingResource } from './resources/accounting.js';\nimport { ChatResource } from './resources/chat.js';\nimport { SyftAIResource } from './resources/syftai.js';\n\n/**\n * Configuration options for SyftHubClient.\n */\nexport interface SyftHubClientOptions {\n /**\n * Base URL for the SyftHub API.\n * Falls back to SYFTHUB_URL environment variable.\n * @example 'https://hub.syft.com'\n */\n baseUrl?: string;\n\n /**\n * Request timeout in milliseconds.\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Base URL for the aggregator service (optional).\n * Falls back to SYFTHUB_AGGREGATOR_URL environment variable.\n * Defaults to {baseUrl}/aggregator/api/v1\n */\n aggregatorUrl?: string;\n\n /**\n * Base URL for the accounting service (optional).\n * Falls back to SYFTHUB_ACCOUNTING_URL environment variable.\n */\n accountingUrl?: string;\n\n /**\n * Email for accounting service authentication (optional).\n * Falls back to SYFTHUB_ACCOUNTING_EMAIL environment variable.\n */\n accountingEmail?: string;\n\n /**\n * Password for accounting service authentication (optional).\n * Falls back to SYFTHUB_ACCOUNTING_PASSWORD environment variable.\n */\n accountingPassword?: string;\n}\n\n/**\n * Get environment variable, handling both Node.js and browser environments.\n */\nfunction getEnv(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n/**\n * Check if running in a browser environment.\n */\nfunction isBrowser(): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return typeof globalThis !== 'undefined' &&\n typeof (globalThis as { window?: unknown }).window !== 'undefined' &&\n typeof (globalThis as { document?: unknown }).document !== 'undefined';\n}\n\n/**\n * SyftHub SDK client for interacting with the SyftHub API.\n *\n * @example\n * // Basic usage\n * import { SyftHubClient } from '@syfthub/sdk';\n *\n * const client = new SyftHubClient({ baseUrl: 'https://hub.syft.com' });\n *\n * // Or use environment variable\n * // Set SYFTHUB_URL=https://hub.syft.com\n * const client = new SyftHubClient();\n *\n * @example\n * // Authentication\n * const user = await client.auth.login('alice', 'password123');\n * console.log(`Logged in as ${user.username}`);\n *\n * // Get current user\n * const me = await client.auth.me();\n *\n * @example\n * // Browse endpoints\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Manage your endpoints\n * const endpoint = await client.myEndpoints.create({\n * name: 'My Model',\n * type: 'model',\n * visibility: 'public',\n * });\n *\n * @example\n * // Token persistence\n * const tokens = client.getTokens();\n * // Save tokens to storage...\n *\n * // Later, restore tokens\n * client.setTokens(savedTokens);\n */\nexport class SyftHubClient {\n private readonly http: HTTPClient;\n private readonly options: SyftHubClientOptions;\n private readonly aggregatorUrl: string;\n\n // Lazy-initialized resources\n private _auth?: AuthResource;\n private _users?: UsersResource;\n private _myEndpoints?: MyEndpointsResource;\n private _hub?: HubResource;\n private _accounting?: AccountingResource;\n private _chat?: ChatResource;\n private _syftai?: SyftAIResource;\n\n /**\n * Create a new SyftHub client.\n *\n * @param options - Configuration options\n * @throws {SyftHubError} If baseUrl is not provided and SYFTHUB_URL is not set (in non-browser environments)\n */\n constructor(options: SyftHubClientOptions = {}) {\n this.options = options;\n let baseUrl = options.baseUrl ?? getEnv('SYFTHUB_URL');\n\n // In browser environments, empty baseUrl means same-origin requests\n // This is valid and commonly used when the API is served from the same domain\n if (!baseUrl && !isBrowser()) {\n throw new SyftHubError(\n 'baseUrl is required. Provide it in options or set the SYFTHUB_URL environment variable.'\n );\n }\n\n // Default to empty string for same-origin browser requests\n baseUrl = baseUrl ?? '';\n\n // Remove trailing slash from base URL (only if not empty)\n const normalizedUrl = baseUrl ? baseUrl.replace(/\\/+$/, '') : '';\n\n this.http = new HTTPClient(normalizedUrl, options.timeout ?? 30000);\n\n // Resolve aggregator URL (default to {baseUrl}/aggregator/api/v1)\n this.aggregatorUrl =\n options.aggregatorUrl ??\n getEnv('SYFTHUB_AGGREGATOR_URL') ??\n `${normalizedUrl}/aggregator/api/v1`;\n }\n\n /**\n * Authentication resource for login, register, and session management.\n *\n * @example\n * const user = await client.auth.login('alice', 'password');\n * await client.auth.logout();\n */\n get auth(): AuthResource {\n if (!this._auth) {\n this._auth = new AuthResource(this.http);\n }\n return this._auth;\n }\n\n /**\n * Users resource for profile management.\n *\n * @example\n * const user = await client.users.update({ fullName: 'Alice Smith' });\n * const available = await client.users.checkUsername('newname');\n */\n get users(): UsersResource {\n if (!this._users) {\n this._users = new UsersResource(this.http);\n }\n return this._users;\n }\n\n /**\n * My Endpoints resource for managing your own endpoints.\n *\n * @example\n * const endpoints = await client.myEndpoints.list().all();\n * const endpoint = await client.myEndpoints.create({ name: 'My API', type: 'model' });\n */\n get myEndpoints(): MyEndpointsResource {\n if (!this._myEndpoints) {\n this._myEndpoints = new MyEndpointsResource(this.http);\n }\n return this._myEndpoints;\n }\n\n /**\n * Hub resource for browsing public endpoints.\n *\n * @example\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n */\n get hub(): HubResource {\n if (!this._hub) {\n this._hub = new HubResource(this.http);\n }\n return this._hub;\n }\n\n /**\n * Accounting resource for billing and transactions.\n *\n * The accounting service is external and uses separate credentials\n * (email/password Basic auth) from SyftHub's JWT authentication.\n *\n * Credentials can be provided via:\n * - Constructor options: accountingUrl, accountingEmail, accountingPassword\n * - Environment variables: SYFTHUB_ACCOUNTING_URL, SYFTHUB_ACCOUNTING_EMAIL, SYFTHUB_ACCOUNTING_PASSWORD\n *\n * @throws {SyftHubError} If accounting credentials are not configured\n *\n * @example\n * const user = await client.accounting.getUser();\n * console.log(`Balance: ${user.balance}`);\n *\n * // Create a transaction\n * const tx = await client.accounting.createTransaction({\n * recipientEmail: 'bob@example.com',\n * amount: 10.0\n * });\n */\n get accounting(): AccountingResource {\n if (!this._accounting) {\n const url = this.options.accountingUrl ?? getEnv('SYFTHUB_ACCOUNTING_URL');\n const email = this.options.accountingEmail ?? getEnv('SYFTHUB_ACCOUNTING_EMAIL');\n const password = this.options.accountingPassword ?? getEnv('SYFTHUB_ACCOUNTING_PASSWORD');\n\n if (!url || !email || !password) {\n const missing: string[] = [];\n if (!url) missing.push('SYFTHUB_ACCOUNTING_URL');\n if (!email) missing.push('SYFTHUB_ACCOUNTING_EMAIL');\n if (!password) missing.push('SYFTHUB_ACCOUNTING_PASSWORD');\n throw new ConfigurationError(\n `Accounting not configured. Missing: ${missing.join(', ')}. ` +\n 'Set environment variables or pass credentials to SyftHubClient.'\n );\n }\n\n this._accounting = new AccountingResource({\n url,\n email,\n password,\n timeout: this.options.timeout,\n });\n }\n return this._accounting;\n }\n\n /**\n * Chat resource for RAG-augmented conversations via the Aggregator.\n *\n * This resource provides high-level chat functionality that integrates\n * with the SyftHub Aggregator service for RAG workflows.\n *\n * @example\n * // Simple chat completion\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n *\n * // Get available endpoints\n * const models = await client.chat.getAvailableModels();\n * const sources = await client.chat.getAvailableDataSources();\n */\n get chat(): ChatResource {\n if (!this._chat) {\n this._chat = new ChatResource(\n this.hub,\n this.auth,\n this.aggregatorUrl\n );\n }\n return this._chat;\n }\n\n /**\n * SyftAI-Space resource for direct endpoint queries (low-level API).\n *\n * This resource provides direct access to SyftAI-Space endpoints without\n * going through the aggregator. Use this when you need custom RAG pipelines\n * or fine-grained control over queries.\n *\n * For most use cases, prefer the higher-level `client.chat` API instead.\n *\n * @example\n * // Query a data source directly\n * const docs = await client.syftai.queryDataSource({\n * endpoint: { url: 'http://syftai:8080', slug: 'docs' },\n * query: 'What is Python?',\n * userEmail: 'alice@example.com',\n * });\n *\n * // Query a model directly\n * const response = await client.syftai.queryModel({\n * endpoint: { url: 'http://syftai:8080', slug: 'gpt-model' },\n * messages: [{ role: 'user', content: 'Hello!' }],\n * userEmail: 'alice@example.com',\n * });\n */\n get syftai(): SyftAIResource {\n if (!this._syftai) {\n this._syftai = new SyftAIResource();\n }\n return this._syftai;\n }\n\n /**\n * Get current authentication tokens.\n *\n * Use this to persist tokens for later sessions.\n *\n * @returns Current tokens or null if not authenticated\n *\n * @example\n * const tokens = client.getTokens();\n * if (tokens) {\n * localStorage.setItem('tokens', JSON.stringify(tokens));\n * }\n */\n getTokens(): AuthTokens | null {\n return this.http.getTokens();\n }\n\n /**\n * Set authentication tokens.\n *\n * Use this to restore a session from previously saved tokens.\n *\n * @param tokens - Tokens to set\n *\n * @example\n * const saved = JSON.parse(localStorage.getItem('tokens'));\n * if (saved) {\n * client.setTokens(saved);\n * }\n */\n setTokens(tokens: AuthTokens): void {\n this.http.setTokens(tokens.accessToken, tokens.refreshToken);\n }\n\n /**\n * Check if the client is currently authenticated.\n *\n * @returns True if tokens are present\n */\n get isAuthenticated(): boolean {\n return this.http.hasTokens();\n }\n\n /**\n * Check if accounting service is configured.\n *\n * Use this to check if accounting credentials are available before\n * accessing the `accounting` property, which will throw if not configured.\n *\n * @returns True if accounting url, email, and password are all configured\n *\n * @example\n * if (client.isAccountingConfigured) {\n * const user = await client.accounting.getUser();\n * }\n */\n get isAccountingConfigured(): boolean {\n const url = this.options.accountingUrl ?? getEnv('SYFTHUB_ACCOUNTING_URL');\n const email = this.options.accountingEmail ?? getEnv('SYFTHUB_ACCOUNTING_EMAIL');\n const password = this.options.accountingPassword ?? getEnv('SYFTHUB_ACCOUNTING_PASSWORD');\n return Boolean(url && email && password);\n }\n\n /**\n * Close the client and clean up resources.\n *\n * Currently a no-op, but may be used in future for connection pooling.\n */\n close(): void {\n // Currently a no-op\n // Could be used for cleanup in future (e.g., connection pools)\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type { User, UserRegisterInput } from '../models/index.js';\nimport { AuthenticationError } from '../errors.js';\n\n/**\n * Response from login/register endpoints.\n */\ninterface AuthResponse {\n user: User;\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n}\n\n/**\n * Authentication resource for login, register, and session management.\n *\n * @example\n * // Register a new user\n * const user = await client.auth.register({\n * username: 'alice',\n * email: 'alice@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Alice'\n * });\n *\n * @example\n * // Login\n * const user = await client.auth.login('alice', 'SecurePass123!');\n *\n * @example\n * // Get current user\n * const me = await client.auth.me();\n *\n * @example\n * // Logout\n * await client.auth.logout();\n */\nexport class AuthResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Register a new user account.\n *\n * If an accounting service URL is configured (via `accountingServiceUrl` or server default),\n * the backend will handle accounting integration using a \"try-create-first\" approach:\n *\n * **Accounting Password Behavior:**\n * - **Not provided**: A secure password is auto-generated and a new accounting account is created.\n * - **Provided (new user)**: The account is created with your chosen password.\n * - **Provided (existing user)**: Your password is validated and accounts are linked.\n *\n * This means you can set your own accounting password during registration even if you're\n * a new user - you don't need an existing accounting account first.\n *\n * @param input - Registration details (username, email, password, fullName)\n * @returns The created User\n * @throws {ValidationError} If input validation fails\n * @throws {UserAlreadyExistsError} If username or email already exists in SyftHub\n * @throws {AccountingAccountExistsError} If email already exists in accounting service\n * and no `accountingPassword` was provided. Retry with the password.\n * @throws {InvalidAccountingPasswordError} If the provided accounting password doesn't\n * match an existing accounting account\n * @throws {AccountingServiceUnavailableError} If the accounting service is unreachable\n *\n * @example\n * // Basic registration (auto-generated accounting password)\n * const user = await client.auth.register({\n * username: 'alice',\n * email: 'alice@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Alice'\n * });\n *\n * @example\n * // Registration with custom accounting password (NEW user)\n * const user = await client.auth.register({\n * username: 'bob',\n * email: 'bob@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Bob',\n * accountingPassword: 'MyChosenAccountingPass!' // Creates account with this password\n * });\n *\n * @example\n * // Handle existing accounting account\n * try {\n * await client.auth.register({ username, email, password, fullName });\n * } catch (error) {\n * if (error instanceof AccountingAccountExistsError) {\n * // Prompt user for their existing accounting password\n * const accountingPassword = await promptUser('Enter your existing accounting password:');\n * await client.auth.register({ username, email, password, fullName, accountingPassword });\n * } else {\n * throw error;\n * }\n * }\n */\n async register(input: UserRegisterInput): Promise<User> {\n const response = await this.http.post<AuthResponse>('/api/v1/auth/register', input, {\n includeAuth: false,\n });\n\n // Store tokens in HTTP client\n this.http.setTokens(response.accessToken, response.refreshToken);\n\n return response.user;\n }\n\n /**\n * Login with username/email and password.\n *\n * Uses OAuth2 password flow (form-urlencoded body).\n *\n * @param username - Username or email\n * @param password - Password\n * @returns The authenticated User\n * @throws {AuthenticationError} If credentials are invalid\n */\n async login(username: string, password: string): Promise<User> {\n const response = await this.http.post<AuthResponse>(\n '/api/v1/auth/login',\n { username, password },\n {\n includeAuth: false,\n isFormData: true,\n }\n );\n\n // Store tokens in HTTP client\n this.http.setTokens(response.accessToken, response.refreshToken);\n\n return response.user;\n }\n\n /**\n * Logout the current user.\n *\n * Invalidates tokens on the server and clears local token storage.\n */\n async logout(): Promise<void> {\n try {\n await this.http.post<void>('/api/v1/auth/logout');\n } finally {\n // Always clear tokens, even if the API call fails\n this.http.clearTokens();\n }\n }\n\n /**\n * Get the current authenticated user.\n *\n * @returns The current User\n * @throws {AuthenticationError} If not authenticated\n */\n async me(): Promise<User> {\n return this.http.get<User>('/api/v1/auth/me');\n }\n\n /**\n * Manually refresh the access token.\n *\n * This is normally handled automatically when a request returns 401.\n *\n * @throws {AuthenticationError} If refresh token is invalid or expired\n */\n async refresh(): Promise<void> {\n const tokens = this.http.getTokens();\n if (!tokens) {\n throw new AuthenticationError('No refresh token available');\n }\n\n const response = await this.http.post<{\n accessToken: string;\n refreshToken: string;\n }>(\n '/api/v1/auth/refresh',\n { refreshToken: tokens.refreshToken },\n { includeAuth: false }\n );\n\n this.http.setTokens(response.accessToken, response.refreshToken);\n }\n\n /**\n * Change the current user's password.\n *\n * @param currentPassword - Current password for verification\n * @param newPassword - New password to set\n * @throws {AuthenticationError} If current password is incorrect\n * @throws {ValidationError} If new password doesn't meet requirements\n */\n async changePassword(currentPassword: string, newPassword: string): Promise<void> {\n await this.http.put<void>('/api/v1/auth/me/password', {\n currentPassword,\n newPassword,\n });\n }\n\n /**\n * Get a satellite token for a specific audience (target service).\n *\n * Satellite tokens are short-lived, RS256-signed JWTs that allow satellite\n * services (like SyftAI-Space) to verify user identity without calling\n * SyftHub for every request.\n *\n * @param audience - Target service identifier (username of the service owner)\n * @returns Satellite token response with token and expiry\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If audience is invalid or inactive\n *\n * @example\n * // Get a token for querying alice's SyftAI-Space endpoints\n * const tokenResponse = await client.auth.getSatelliteToken('alice');\n * console.log(`Token expires in ${tokenResponse.expiresIn} seconds`);\n */\n async getSatelliteToken(audience: string): Promise<SatelliteTokenResponse> {\n return this.http.get<SatelliteTokenResponse>('/api/v1/token', { aud: audience });\n }\n\n /**\n * Get satellite tokens for multiple audiences in parallel.\n *\n * This is useful when making requests to endpoints owned by different users.\n * Tokens are cached and reused where possible.\n *\n * @param audiences - Array of unique audience identifiers (usernames)\n * @returns Map of audience to satellite token\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * // Get tokens for multiple endpoint owners\n * const tokens = await client.auth.getSatelliteTokens(['alice', 'bob']);\n * console.log(`Got ${tokens.size} tokens`);\n */\n async getSatelliteTokens(audiences: string[]): Promise<Map<string, string>> {\n const uniqueAudiences = [...new Set(audiences)];\n const tokenMap = new Map<string, string>();\n\n // Fetch tokens in parallel\n const results = await Promise.allSettled(\n uniqueAudiences.map(async (aud) => {\n const response = await this.getSatelliteToken(aud);\n return { audience: aud, token: response.targetToken };\n })\n );\n\n // Collect successful results\n for (const result of results) {\n if (result.status === 'fulfilled') {\n tokenMap.set(result.value.audience, result.value.token);\n }\n // Failed tokens are silently skipped - the aggregator will handle missing tokens\n }\n\n return tokenMap;\n }\n\n /**\n * Get transaction tokens for multiple endpoint owners.\n *\n * Transaction tokens are short-lived JWTs that pre-authorize the endpoint owner\n * (recipient) to charge the current user (sender) for usage. These tokens are\n * created via the accounting service and passed to the aggregator.\n *\n * This is used by the chat flow to enable billing for endpoint usage.\n *\n * @param ownerUsernames - Array of endpoint owner usernames\n * @returns TransactionTokensResponse with tokens map and any errors\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * // Get transaction tokens for endpoint owners\n * const response = await client.auth.getTransactionTokens(['alice', 'bob']);\n * console.log(`Got ${Object.keys(response.tokens).length} tokens`);\n * if (Object.keys(response.errors).length > 0) {\n * console.log('Some tokens failed:', response.errors);\n * }\n */\n async getTransactionTokens(ownerUsernames: string[]): Promise<TransactionTokensResponse> {\n const uniqueOwners = [...new Set(ownerUsernames)];\n\n if (uniqueOwners.length === 0) {\n return { tokens: {}, errors: {} };\n }\n\n try {\n return await this.http.post<TransactionTokensResponse>(\n '/api/v1/accounting/transaction-tokens',\n { owner_usernames: uniqueOwners }\n );\n } catch (error) {\n // If accounting is not configured or fails, return empty tokens\n // The chat can proceed without transaction tokens (billing will fail later)\n console.warn('Failed to get transaction tokens:', error);\n return { tokens: {}, errors: {} };\n }\n }\n}\n\n/**\n * Response from satellite token endpoint.\n */\nexport interface SatelliteTokenResponse {\n /** RS256-signed JWT for the target service */\n targetToken: string;\n /** Seconds until the token expires */\n expiresIn: number;\n}\n\n/**\n * Response from transaction tokens endpoint.\n */\nexport interface TransactionTokensResponse {\n /** Mapping of owner_username to transaction token */\n tokens: Record<string, string>;\n /** Mapping of owner_username to error message (for failed tokens) */\n errors: Record<string, string>;\n}\n","import type { HTTPClient } from '../http.js';\nimport type { AccountingCredentials, User, UserUpdateInput } from '../models/index.js';\n\n/**\n * Users resource for profile management and availability checks.\n *\n * @example\n * // Update your profile\n * const user = await client.users.update({\n * fullName: 'Alice Smith',\n * avatarUrl: 'https://example.com/avatar.jpg'\n * });\n *\n * @example\n * // Check if username is available\n * const available = await client.users.checkUsername('newusername');\n *\n * @example\n * // Check if email is available\n * const available = await client.users.checkEmail('new@example.com');\n */\nexport class UsersResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Update the current user's profile.\n *\n * Only provided fields will be updated.\n *\n * @param input - Fields to update\n * @returns The updated User\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If input validation fails\n */\n async update(input: UserUpdateInput): Promise<User> {\n return this.http.put<User>('/api/v1/users/me', input);\n }\n\n /**\n * Check if a username is available.\n *\n * @param username - Username to check\n * @returns True if the username is available\n */\n async checkUsername(username: string): Promise<boolean> {\n const response = await this.http.get<{ available: boolean }>(\n `/api/v1/users/check-username/${encodeURIComponent(username)}`,\n undefined,\n { includeAuth: false }\n );\n return response.available;\n }\n\n /**\n * Check if an email is available.\n *\n * @param email - Email to check\n * @returns True if the email is available\n */\n async checkEmail(email: string): Promise<boolean> {\n const response = await this.http.get<{ available: boolean }>(\n `/api/v1/users/check-email/${encodeURIComponent(email)}`,\n undefined,\n { includeAuth: false }\n );\n return response.available;\n }\n\n /**\n * Get the current user's accounting service credentials.\n *\n * Returns credentials stored in SyftHub for connecting to an external\n * accounting service. The email is always the same as the user's SyftHub email.\n *\n * @returns Accounting credentials (url and password may be null if not configured)\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * const credentials = await client.users.getAccountingCredentials();\n * if (credentials.url && credentials.password) {\n * // Use credentials to connect to accounting service\n * }\n */\n async getAccountingCredentials(): Promise<AccountingCredentials> {\n return this.http.get<AccountingCredentials>('/api/v1/users/me/accounting');\n }\n}\n","/**\n * Function type for fetching a page of items.\n */\nexport type PageFetcher<T> = (skip: number, limit: number) => Promise<T[]>;\n\n/**\n * Lazy async iterator for paginated API responses.\n *\n * Fetches pages on demand as you iterate, minimizing API calls\n * and memory usage for large datasets.\n *\n * @example\n * // Iterate through all items\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Get just the first page\n * const firstPage = await client.hub.browse().firstPage();\n *\n * @example\n * // Get first 10 items\n * const top10 = await client.hub.browse().take(10);\n */\nexport class PageIterator<T> implements AsyncIterable<T> {\n private items: T[] = [];\n private index = 0;\n private skip = 0;\n private exhausted = false;\n private initialized = false;\n\n /**\n * Create a new PageIterator.\n *\n * @param fetcher - Function that fetches a page of items given skip and limit\n * @param pageSize - Number of items to fetch per page (default: 20)\n */\n constructor(\n private readonly fetcher: PageFetcher<T>,\n private readonly pageSize: number = 20\n ) {}\n\n /**\n * Async iterator implementation for `for await...of` loops.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n // If we've consumed all items in the current page\n if (this.index >= this.items.length) {\n if (this.exhausted) break;\n await this.fetchNextPage();\n if (this.items.length === 0) break;\n }\n\n const item = this.items[this.index];\n if (item === undefined) break;\n\n this.index++;\n yield item;\n }\n }\n\n /**\n * Get just the first page of results.\n *\n * @returns Promise resolving to the first page of items\n */\n async firstPage(): Promise<T[]> {\n if (!this.initialized) {\n await this.fetchNextPage();\n }\n return [...this.items];\n }\n\n /**\n * Get all items across all pages.\n *\n * Warning: This loads all items into memory. For large datasets,\n * consider iterating with `for await...of` instead.\n *\n * @returns Promise resolving to all items\n */\n async all(): Promise<T[]> {\n const results: T[] = [];\n for await (const item of this) {\n results.push(item);\n }\n return results;\n }\n\n /**\n * Get the first N items.\n *\n * @param n - Maximum number of items to return\n * @returns Promise resolving to up to N items\n */\n async take(n: number): Promise<T[]> {\n const results: T[] = [];\n for await (const item of this) {\n results.push(item);\n if (results.length >= n) break;\n }\n return results;\n }\n\n /**\n * Fetch the next page of items from the API.\n */\n private async fetchNextPage(): Promise<void> {\n const page = await this.fetcher(this.skip, this.pageSize);\n this.items = page;\n this.index = 0;\n this.skip += this.pageSize;\n this.exhausted = page.length < this.pageSize;\n this.initialized = true;\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type {\n Endpoint,\n EndpointCreateInput,\n EndpointUpdateInput,\n Visibility,\n} from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\n\n/**\n * Options for listing endpoints.\n */\nexport interface ListEndpointsOptions {\n /** Filter by visibility level */\n visibility?: Visibility;\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * My Endpoints resource for CRUD operations on user's own endpoints.\n *\n * For browsing public endpoints from other users, see the Hub resource.\n *\n * @example\n * // List your endpoints\n * for await (const endpoint of client.myEndpoints.list()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Create a new endpoint\n * const endpoint = await client.myEndpoints.create({\n * name: 'My API',\n * type: 'model',\n * visibility: 'public',\n * description: 'A cool API'\n * });\n *\n * @example\n * // Get a specific endpoint\n * const endpoint = await client.myEndpoints.get('alice/my-api');\n *\n * @example\n * // Update an endpoint\n * const updated = await client.myEndpoints.update('alice/my-api', {\n * description: 'Updated description'\n * });\n *\n * @example\n * // Delete an endpoint\n * await client.myEndpoints.delete('alice/my-api');\n */\nexport class MyEndpointsResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Parse an endpoint path into owner and slug.\n *\n * @param path - Path in \"owner/slug\" format\n * @returns Tuple of [owner, slug]\n * @throws {Error} If path format is invalid\n */\n private parsePath(path: string): [string, string] {\n const parts = path.replace(/^\\/|\\/$/g, '').split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid endpoint path: '${path}'. Expected format: 'owner/slug'`);\n }\n return [parts[0], parts[1]];\n }\n\n /**\n * Resolve an endpoint path to its ID.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @returns The endpoint ID\n */\n private async resolveEndpointId(path: string): Promise<number> {\n const [owner, slug] = this.parsePath(path);\n\n // Get the endpoint via the public route (returns full details for owners)\n const response = await this.http.get<{ id?: number }>(`/${owner}/${slug}`);\n\n if (response.id === undefined) {\n throw new Error(\n `Could not resolve endpoint ID for '${path}'. Make sure you own this endpoint.`\n );\n }\n\n return response.id;\n }\n\n /**\n * List the current user's endpoints.\n *\n * @param options - Filtering and pagination options\n * @returns PageIterator that lazily fetches endpoints\n * @throws {AuthenticationError} If not authenticated\n */\n list(options?: ListEndpointsOptions): PageIterator<Endpoint> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<Endpoint>(async (skip, limit) => {\n const params: Record<string, unknown> = { skip, limit };\n if (options?.visibility) {\n params['visibility'] = options.visibility;\n }\n return this.http.get<Endpoint[]>('/api/v1/endpoints', params);\n }, pageSize);\n }\n\n /**\n * Create a new endpoint.\n *\n * @param input - Endpoint creation details\n * @param organizationId - Optional organization ID (for org-owned endpoints)\n * @returns The created Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If input validation fails\n */\n async create(input: EndpointCreateInput, organizationId?: number): Promise<Endpoint> {\n const body = organizationId !== undefined ? { ...input, organizationId } : input;\n return this.http.post<Endpoint>('/api/v1/endpoints', body);\n }\n\n /**\n * Get a specific endpoint by path.\n *\n * @param path - Endpoint path in \"owner/slug\" format (e.g., \"alice/my-api\")\n * @returns The Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not authorized to view\n */\n async get(path: string): Promise<Endpoint> {\n const [owner, slug] = this.parsePath(path);\n return this.http.get<Endpoint>(`/${owner}/${slug}`);\n }\n\n /**\n * Update an endpoint.\n *\n * Only provided fields will be updated.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @param input - Fields to update\n * @returns The updated Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not owner/admin\n */\n async update(path: string, input: EndpointUpdateInput): Promise<Endpoint> {\n const endpointId = await this.resolveEndpointId(path);\n return this.http.patch<Endpoint>(`/api/v1/endpoints/${endpointId}`, input);\n }\n\n /**\n * Delete an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not owner/admin\n */\n async delete(path: string): Promise<void> {\n const endpointId = await this.resolveEndpointId(path);\n await this.http.delete<void>(`/api/v1/endpoints/${endpointId}`);\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type { EndpointPublic } from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\n\n/**\n * Options for browsing endpoints.\n */\nexport interface BrowseOptions {\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * Options for trending endpoints.\n */\nexport interface TrendingOptions {\n /** Minimum number of stars */\n minStars?: number;\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * Hub resource for browsing and discovering public endpoints.\n *\n * For managing your own endpoints, see the MyEndpoints resource.\n *\n * @example\n * // Browse all public endpoints\n * for await (const endpoint of client.hub.browse()) {\n * console.log(`${endpoint.ownerUsername}/${endpoint.slug}: ${endpoint.name}`);\n * }\n *\n * @example\n * // Get trending endpoints\n * for await (const endpoint of client.hub.trending({ minStars: 10 })) {\n * console.log(`${endpoint.name} - ${endpoint.starsCount} stars`);\n * }\n *\n * @example\n * // Get a specific endpoint\n * const endpoint = await client.hub.get('alice/cool-api');\n * console.log(endpoint.readme);\n *\n * @example\n * // Star an endpoint (requires auth)\n * await client.hub.star('alice/cool-api');\n *\n * @example\n * // Check if you've starred an endpoint\n * const starred = await client.hub.isStarred('alice/cool-api');\n */\nexport class HubResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Parse an endpoint path into owner and slug.\n *\n * @param path - Path in \"owner/slug\" format\n * @returns Tuple of [owner, slug]\n */\n private parsePath(path: string): [string, string] {\n const parts = path.replace(/^\\/|\\/$/g, '').split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid endpoint path: '${path}'. Expected format: 'owner/slug'`);\n }\n return [parts[0], parts[1]];\n }\n\n /**\n * Resolve an endpoint path to its ID.\n *\n * This searches the user's own endpoints to find the ID.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @returns The endpoint ID\n */\n private async resolveEndpointId(path: string): Promise<number> {\n const [, slug] = this.parsePath(path);\n\n // Search the user's endpoints to find the ID\n // This uses /api/v1/endpoints which returns full details including ID\n const endpoints = await this.http.get<Array<{ id?: number; slug?: string }>>(\n '/api/v1/endpoints',\n { limit: 100 }\n );\n\n for (const ep of endpoints) {\n if (ep.slug === slug && ep.id !== undefined) {\n return ep.id;\n }\n }\n\n // Import NotFoundError here to avoid circular dependency\n const { NotFoundError } = await import('../errors.js');\n throw new NotFoundError(\n `Could not resolve endpoint ID for '${path}'. ` +\n 'Endpoint not found or you don\\'t have access to get its ID.'\n );\n }\n\n /**\n * Browse all public endpoints.\n *\n * @param options - Pagination options\n * @returns PageIterator that lazily fetches endpoints\n */\n browse(options?: BrowseOptions): PageIterator<EndpointPublic> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<EndpointPublic>(async (skip, limit) => {\n return this.http.get<EndpointPublic[]>(\n '/api/v1/endpoints/public',\n { skip, limit },\n { includeAuth: false }\n );\n }, pageSize);\n }\n\n /**\n * Get trending endpoints sorted by stars.\n *\n * @param options - Filter and pagination options\n * @returns PageIterator that lazily fetches endpoints\n */\n trending(options?: TrendingOptions): PageIterator<EndpointPublic> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<EndpointPublic>(async (skip, limit) => {\n const params: Record<string, unknown> = { skip, limit };\n if (options?.minStars !== undefined) {\n params['minStars'] = options.minStars;\n }\n return this.http.get<EndpointPublic[]>(\n '/api/v1/endpoints/trending',\n params,\n { includeAuth: false }\n );\n }, pageSize);\n }\n\n /**\n * Get an endpoint by its path.\n *\n * This method searches the public endpoints API to find the endpoint,\n * which works reliably across all deployment configurations.\n *\n * @param path - Endpoint path in \"owner/slug\" format (e.g., \"alice/cool-api\")\n * @returns The EndpointPublic\n * @throws {NotFoundError} If endpoint not found\n */\n async get(path: string): Promise<EndpointPublic> {\n const [owner, slug] = this.parsePath(path);\n\n // Search public endpoints to find the matching one\n // This approach works because /api/v1/endpoints/public is reliably\n // served by the backend API, unlike /{owner}/{slug} which may be\n // intercepted by frontend routing in some deployments.\n for await (const endpoint of this.browse({ pageSize: 100 })) {\n if (endpoint.ownerUsername === owner && endpoint.slug === slug) {\n return endpoint;\n }\n }\n\n // Import NotFoundError here to avoid circular dependency\n const { NotFoundError } = await import('../errors.js');\n throw new NotFoundError(\n `Endpoint not found: '${path}'. No public endpoint found with owner '${owner}' and slug '${slug}'.`\n );\n }\n\n /**\n * Star an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async star(path: string): Promise<void> {\n const endpointId = await this.resolveEndpointId(path);\n await this.http.patch<void>(`/api/v1/endpoints/${endpointId}/star`);\n }\n\n /**\n * Unstar an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async unstar(path: string): Promise<void> {\n const endpointId = await this.resolveEndpointId(path);\n await this.http.patch<void>(`/api/v1/endpoints/${endpointId}/unstar`);\n }\n\n /**\n * Check if you have starred an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @returns True if starred, False otherwise\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async isStarred(path: string): Promise<boolean> {\n const endpointId = await this.resolveEndpointId(path);\n const response = await this.http.get<{ starred: boolean }>(\n `/api/v1/endpoints/${endpointId}/starred`\n );\n return response.starred ?? false;\n }\n}\n","/**\n * Visibility levels for endpoints.\n */\nexport const Visibility = {\n /** Visible to everyone, no authentication required */\n PUBLIC: 'public',\n /** Only visible to the owner and collaborators */\n PRIVATE: 'private',\n /** Visible to authenticated users within the organization */\n INTERNAL: 'internal',\n} as const;\n\nexport type Visibility = (typeof Visibility)[keyof typeof Visibility];\n\n/**\n * Types of endpoints.\n */\nexport const EndpointType = {\n /** Machine learning model endpoint */\n MODEL: 'model',\n /** Data source endpoint */\n DATA_SOURCE: 'data_source',\n} as const;\n\nexport type EndpointType = (typeof EndpointType)[keyof typeof EndpointType];\n\n/**\n * User roles in the system.\n */\nexport const UserRole = {\n /** Administrator with full access */\n ADMIN: 'admin',\n /** Regular user */\n USER: 'user',\n /** Guest user with limited access */\n GUEST: 'guest',\n} as const;\n\nexport type UserRole = (typeof UserRole)[keyof typeof UserRole];\n\n/**\n * Organization member roles.\n */\nexport const OrganizationRole = {\n /** Organization owner with full control */\n OWNER: 'owner',\n /** Administrator with management privileges */\n ADMIN: 'admin',\n /** Regular member */\n MEMBER: 'member',\n} as const;\n\nexport type OrganizationRole = (typeof OrganizationRole)[keyof typeof OrganizationRole];\n","import type { EndpointType, Visibility } from './common.js';\n\n/**\n * Policy configuration for an endpoint.\n */\nexport interface Policy {\n readonly type: string;\n readonly version: string;\n readonly enabled: boolean;\n readonly description: string;\n readonly config: Record<string, unknown>;\n}\n\n/**\n * Connection configuration for an endpoint.\n */\nexport interface Connection {\n readonly type: string;\n readonly enabled: boolean;\n readonly description: string;\n readonly config: Record<string, unknown>;\n}\n\n/**\n * Full endpoint model (for authenticated users viewing their own endpoints).\n */\nexport interface Endpoint {\n readonly id: number;\n readonly userId: number | null;\n readonly organizationId: number | null;\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly type: EndpointType;\n readonly visibility: Visibility;\n readonly isActive: boolean;\n readonly contributors: readonly number[];\n readonly version: string;\n readonly readme: string;\n readonly tags: readonly string[];\n readonly starsCount: number;\n readonly policies: readonly Policy[];\n readonly connect: readonly Connection[];\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\n/**\n * Public endpoint model (for browsing the hub).\n */\nexport interface EndpointPublic {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly type: EndpointType;\n readonly ownerUsername: string;\n /** Number of contributors (user IDs not exposed for privacy) */\n readonly contributorsCount: number;\n readonly version: string;\n readonly readme: string;\n readonly tags: readonly string[];\n readonly starsCount: number;\n readonly policies: readonly Policy[];\n readonly connect: readonly Connection[];\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\n/**\n * Input for creating a new endpoint.\n */\nexport interface EndpointCreateInput {\n name: string;\n type: EndpointType;\n visibility?: Visibility;\n description?: string;\n slug?: string;\n version?: string;\n readme?: string;\n tags?: string[];\n policies?: Policy[];\n connect?: Connection[];\n contributors?: number[];\n}\n\n/**\n * Input for updating an existing endpoint.\n */\nexport interface EndpointUpdateInput {\n name?: string;\n description?: string;\n visibility?: Visibility;\n version?: string;\n readme?: string;\n tags?: string[];\n policies?: Policy[];\n connect?: Connection[];\n contributors?: number[];\n}\n\n/**\n * Get the owner type for an endpoint.\n *\n * @param endpoint - The endpoint to check\n * @returns 'user' if user-owned, 'organization' if org-owned\n */\nexport function getEndpointOwnerType(endpoint: Endpoint): 'user' | 'organization' {\n return endpoint.organizationId !== null ? 'organization' : 'user';\n}\n\n/**\n * Get the full path for a public endpoint (owner/slug format).\n *\n * @param endpoint - The public endpoint\n * @returns The path in \"owner/slug\" format\n */\nexport function getEndpointPublicPath(endpoint: EndpointPublic): string {\n return `${endpoint.ownerUsername}/${endpoint.slug}`;\n}\n","/**\n * Accounting Models\n *\n * Models for the external accounting service. The accounting service manages\n * user balances and transactions, and uses its own authentication separate\n * from SyftHub.\n */\n\n// =============================================================================\n// Enums\n// =============================================================================\n\n/**\n * Transaction status in the accounting service.\n */\nexport const TransactionStatus = {\n /** Transaction created, awaiting confirmation */\n PENDING: 'pending',\n /** Transaction confirmed, funds transferred */\n COMPLETED: 'completed',\n /** Transaction cancelled, no funds transferred */\n CANCELLED: 'cancelled',\n} as const;\n\nexport type TransactionStatus = (typeof TransactionStatus)[keyof typeof TransactionStatus];\n\n/**\n * Who created or resolved a transaction.\n */\nexport const CreatorType = {\n /** System-initiated transaction */\n SYSTEM: 'system',\n /** Sender-initiated transaction */\n SENDER: 'sender',\n /** Recipient-initiated transaction (delegated) */\n RECIPIENT: 'recipient',\n} as const;\n\nexport type CreatorType = (typeof CreatorType)[keyof typeof CreatorType];\n\n// =============================================================================\n// Core Models\n// =============================================================================\n\n/**\n * User from accounting service with balance.\n *\n * This represents the user's account in the external accounting service,\n * which is separate from the SyftHub user account.\n */\nexport interface AccountingUser {\n readonly id: string;\n readonly email: string;\n readonly balance: number;\n readonly organization: string | null;\n}\n\n/**\n * Transaction record from accounting service.\n *\n * Transactions go through a lifecycle:\n * 1. Created (status=PENDING)\n * 2. Confirmed or Cancelled (status=COMPLETED or CANCELLED)\n *\n * The createdBy field indicates who initiated the transaction:\n * - SENDER: Direct transaction by the payer\n * - RECIPIENT: Delegated transaction using a token\n * - SYSTEM: System-initiated transaction\n *\n * The resolvedBy field indicates who confirmed/cancelled.\n */\nexport interface Transaction {\n readonly id: string;\n readonly senderEmail: string;\n readonly recipientEmail: string;\n readonly amount: number;\n readonly status: TransactionStatus;\n readonly createdBy: CreatorType;\n readonly resolvedBy: CreatorType | null;\n readonly createdAt: Date;\n readonly resolvedAt: Date | null;\n readonly appName: string | null;\n readonly appEpPath: string | null;\n}\n\n// =============================================================================\n// Input Types\n// =============================================================================\n\n/**\n * Input for creating a direct transaction.\n */\nexport interface CreateTransactionInput {\n /** Email of the recipient */\n recipientEmail: string;\n /** Amount to transfer (must be > 0) */\n amount: number;\n /** Optional app name for context (e.g., \"syftai-space\") */\n appName?: string;\n /** Optional endpoint path for context (e.g., \"alice/model\") */\n appEpPath?: string;\n}\n\n/**\n * Input for creating a delegated transaction.\n */\nexport interface CreateDelegatedTransactionInput {\n /** Email of the sender who created the token */\n senderEmail: string;\n /** Amount to transfer (must be > 0) */\n amount: number;\n /** JWT token from sender's createTransactionToken() */\n token: string;\n}\n\n/**\n * Input for updating password.\n */\nexport interface UpdatePasswordInput {\n /** Current password for verification */\n currentPassword: string;\n /** New password to set */\n newPassword: string;\n}\n\n// =============================================================================\n// Response Types (from API)\n// =============================================================================\n\n/**\n * Raw transaction response from API (before date parsing).\n */\nexport interface TransactionResponse {\n id: string;\n senderEmail: string;\n recipientEmail: string;\n amount: number;\n status: TransactionStatus;\n createdBy: CreatorType;\n resolvedBy: CreatorType | null;\n createdAt: string;\n resolvedAt: string | null;\n appName: string | null;\n appEpPath: string | null;\n}\n\n/**\n * Token response from createTransactionToken.\n */\nexport interface TransactionTokenResponse {\n token: string;\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Parse a transaction response into a Transaction object.\n */\nexport function parseTransaction(response: TransactionResponse): Transaction {\n return {\n ...response,\n createdAt: new Date(response.createdAt),\n resolvedAt: response.resolvedAt ? new Date(response.resolvedAt) : null,\n };\n}\n\n/**\n * Check if a transaction is pending.\n */\nexport function isTransactionPending(tx: Transaction): boolean {\n return tx.status === TransactionStatus.PENDING;\n}\n\n/**\n * Check if a transaction is completed.\n */\nexport function isTransactionCompleted(tx: Transaction): boolean {\n return tx.status === TransactionStatus.COMPLETED;\n}\n\n/**\n * Check if a transaction is cancelled.\n */\nexport function isTransactionCancelled(tx: Transaction): boolean {\n return tx.status === TransactionStatus.CANCELLED;\n}\n","/**\n * Accounting Resource for SyftHub SDK\n *\n * This module connects to an external accounting/billing service for managing\n * user balances and transactions. The accounting service is separate from SyftHub\n * and uses its own authentication (Basic auth with email/password).\n *\n * @example\n * ```typescript\n * // Create accounting client\n * const accounting = new AccountingResource({\n * url: 'https://accounting.example.com',\n * email: 'user@example.com',\n * password: 'secret'\n * });\n *\n * // Get user balance\n * const user = await accounting.getUser();\n * console.log(`Balance: ${user.balance}`);\n *\n * // Create a transaction\n * const tx = await accounting.createTransaction({\n * recipientEmail: 'recipient@example.com',\n * amount: 10.0,\n * appName: 'syftai-space',\n * appEpPath: 'alice/my-model'\n * });\n *\n * // Confirm the transaction\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n\nimport {\n type AccountingUser,\n type Transaction,\n type TransactionResponse,\n type CreateTransactionInput,\n parseTransaction,\n} from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\nimport {\n AuthenticationError,\n AuthorizationError,\n NotFoundError,\n ValidationError,\n APIError,\n SyftHubError,\n} from '../errors.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for creating an AccountingResource.\n */\nexport interface AccountingResourceOptions {\n /** Accounting service URL */\n url: string;\n /** Email for Basic auth */\n email: string;\n /** Password for Basic auth */\n password: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Options for listing transactions.\n */\nexport interface TransactionsOptions {\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n// =============================================================================\n// Error Handling\n// =============================================================================\n\n/**\n * Handle HTTP error responses from accounting service.\n */\nasync function handleResponseError(response: Response): Promise<void> {\n if (response.ok) return;\n\n let detail: string;\n try {\n const body = await response.json() as { detail?: string; message?: string };\n detail = body.detail ?? body.message ?? JSON.stringify(body);\n } catch {\n detail = (await response.text()) || `HTTP ${response.status}`;\n }\n\n switch (response.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 403:\n throw new AuthorizationError(`Permission denied: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 422:\n throw new ValidationError(`Validation error: ${detail}`);\n default:\n throw new APIError(`Accounting API error: ${detail}`, response.status);\n }\n}\n\n/**\n * Create Basic auth header value.\n */\nfunction createBasicAuth(email: string, password: string): string {\n const credentials = `${email}:${password}`;\n // Use btoa for browser, Buffer for Node.js\n const encoded = typeof btoa !== 'undefined'\n ? btoa(credentials)\n : Buffer.from(credentials).toString('base64');\n return `Basic ${encoded}`;\n}\n\n// =============================================================================\n// AccountingResource\n// =============================================================================\n\n/**\n * Handle accounting/billing operations with external service.\n *\n * The accounting service manages user balances and transactions. It uses\n * Basic auth (email/password) for authentication, which is separate from\n * SyftHub's JWT-based authentication.\n *\n * Transaction Workflow:\n * 1. Sender creates transaction (status=PENDING)\n * 2. Either party confirms (status=COMPLETED) or cancels (status=CANCELLED)\n *\n * Delegated Transaction Workflow:\n * 1. Sender creates a transaction token for recipient\n * 2. Recipient uses token to create delegated transaction\n * 3. Recipient confirms the transaction\n */\nexport class AccountingResource {\n private readonly baseUrl: string;\n private readonly email: string;\n private readonly password: string;\n private readonly timeout: number;\n private readonly authHeader: string;\n\n constructor(options: AccountingResourceOptions) {\n this.baseUrl = options.url.replace(/\\/$/, ''); // Remove trailing slash\n this.email = options.email;\n this.password = options.password;\n this.timeout = options.timeout ?? 30000;\n this.authHeader = createBasicAuth(this.email, this.password);\n }\n\n // ===========================================================================\n // Private HTTP Methods\n // ===========================================================================\n\n /**\n * Make an authenticated request to the accounting service.\n */\n private async request<T>(\n method: string,\n path: string,\n options?: {\n body?: Record<string, unknown>;\n params?: Record<string, string | number>;\n }\n ): Promise<T> {\n const url = new URL(path, this.baseUrl);\n\n if (options?.params) {\n for (const [key, value] of Object.entries(options.params)) {\n url.searchParams.set(key, String(value));\n }\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'Authorization': this.authHeader,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n await handleResponseError(response);\n\n if (response.status === 204) {\n return {} as T;\n }\n\n return await response.json() as T;\n } catch (error) {\n if (error instanceof SyftHubError) {\n throw error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n throw new APIError('Request timeout', 408);\n }\n throw new APIError(`Accounting request failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 0);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Make a request using Bearer token auth (for delegated transactions).\n */\n private async requestWithToken<T>(\n method: string,\n path: string,\n token: string,\n options?: {\n body?: Record<string, unknown>;\n }\n ): Promise<T> {\n const url = new URL(path, this.baseUrl);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n await handleResponseError(response);\n\n if (response.status === 204) {\n return {} as T;\n }\n\n return await response.json() as T;\n } catch (error) {\n if (error instanceof SyftHubError) {\n throw error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n throw new APIError('Request timeout', 408);\n }\n throw new APIError(`Accounting request failed: ${error instanceof Error ? error.message : 'Unknown error'}`, 0);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n // ===========================================================================\n // User Operations\n // ===========================================================================\n\n /**\n * Get the current user's account information including balance.\n *\n * @returns AccountingUser with id, email, balance, and organization\n * @throws {AuthenticationError} If authentication fails\n * @throws {APIError} On other errors\n *\n * @example\n * ```typescript\n * const user = await accounting.getUser();\n * console.log(`Balance: ${user.balance}`);\n * console.log(`Organization: ${user.organization}`);\n * ```\n */\n async getUser(): Promise<AccountingUser> {\n return this.request<AccountingUser>('GET', '/user');\n }\n\n /**\n * Update the user's password.\n *\n * @param currentPassword - Current password for verification\n * @param newPassword - New password to set\n * @throws {AuthenticationError} If current password is wrong\n * @throws {ValidationError} If new password doesn't meet requirements\n *\n * @example\n * ```typescript\n * await accounting.updatePassword('old_secret', 'new_secret');\n * ```\n */\n async updatePassword(currentPassword: string, newPassword: string): Promise<void> {\n await this.request<void>('PUT', '/user/password', {\n body: {\n oldPassword: currentPassword,\n newPassword: newPassword,\n },\n });\n }\n\n /**\n * Update the user's organization.\n *\n * @param organization - New organization name\n * @throws {AuthenticationError} If authentication fails\n *\n * @example\n * ```typescript\n * await accounting.updateOrganization('OpenMined');\n * ```\n */\n async updateOrganization(organization: string): Promise<void> {\n await this.request<void>('PUT', '/user/organization', {\n body: { organization },\n });\n }\n\n // ===========================================================================\n // Transaction Listing\n // ===========================================================================\n\n /**\n * List account transactions with pagination.\n *\n * Returns a lazy iterator that fetches pages on demand.\n *\n * @param options - Pagination options\n * @returns PageIterator that yields Transaction objects\n *\n * @example\n * ```typescript\n * // Iterate through all transactions\n * for await (const tx of accounting.getTransactions()) {\n * console.log(`${tx.createdAt}: ${tx.amount} from ${tx.senderEmail}`);\n * }\n *\n * // Get first page only\n * const firstPage = await accounting.getTransactions().firstPage();\n *\n * // Get all transactions\n * const allTxs = await accounting.getTransactions().all();\n * ```\n */\n getTransactions(options?: TransactionsOptions): PageIterator<Transaction> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<Transaction>(\n async (skip, limit) => {\n const response = await this.request<TransactionResponse[]>('GET', '/transactions', {\n params: { skip, limit },\n });\n return response.map(parseTransaction);\n },\n pageSize\n );\n }\n\n /**\n * Get a specific transaction by ID.\n *\n * @param transactionId - The transaction ID\n * @returns Transaction object\n * @throws {NotFoundError} If transaction not found\n *\n * @example\n * ```typescript\n * const tx = await accounting.getTransaction('tx_123');\n * console.log(`Status: ${tx.status}`);\n * ```\n */\n async getTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'GET',\n `/transactions/${transactionId}`\n );\n return parseTransaction(response);\n }\n\n // ===========================================================================\n // Direct Transaction Operations\n // ===========================================================================\n\n /**\n * Create a new transaction (direct transfer).\n *\n * Creates a PENDING transaction that must be confirmed or cancelled.\n * The transaction is created by the sender (current user).\n *\n * @param input - Transaction details\n * @returns Transaction in PENDING status\n * @throws {ValidationError} If amount <= 0 or insufficient balance\n *\n * @example\n * ```typescript\n * const tx = await accounting.createTransaction({\n * recipientEmail: 'bob@example.com',\n * amount: 10.0,\n * appName: 'syftai-space',\n * appEpPath: 'alice/my-model'\n * });\n * console.log(`Created transaction ${tx.id}: ${tx.status}`);\n *\n * // Later, confirm or cancel\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n async createTransaction(input: CreateTransactionInput): Promise<Transaction> {\n if (input.amount <= 0) {\n throw new ValidationError('Amount must be greater than 0');\n }\n\n const response = await this.request<TransactionResponse>('POST', '/transactions', {\n body: {\n recipientEmail: input.recipientEmail,\n amount: input.amount,\n ...(input.appName && { appName: input.appName }),\n ...(input.appEpPath && { appEpPath: input.appEpPath }),\n },\n });\n\n return parseTransaction(response);\n }\n\n /**\n * Confirm a pending transaction.\n *\n * Confirms the transaction, transferring funds from sender to recipient.\n * Can be called by either the sender or recipient.\n *\n * @param transactionId - The transaction ID to confirm\n * @returns Transaction in COMPLETED status\n * @throws {NotFoundError} If transaction not found\n * @throws {ValidationError} If transaction is not in PENDING status\n *\n * @example\n * ```typescript\n * const tx = await accounting.confirmTransaction('tx_123');\n * console.log(`Confirmed: ${tx.status}`); // \"completed\"\n * ```\n */\n async confirmTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'POST',\n `/transactions/${transactionId}/confirm`\n );\n return parseTransaction(response);\n }\n\n /**\n * Cancel a pending transaction.\n *\n * Cancels the transaction without transferring funds.\n * Can be called by either the sender or recipient.\n *\n * @param transactionId - The transaction ID to cancel\n * @returns Transaction in CANCELLED status\n * @throws {NotFoundError} If transaction not found\n * @throws {ValidationError} If transaction is not in PENDING status\n *\n * @example\n * ```typescript\n * const tx = await accounting.cancelTransaction('tx_123');\n * console.log(`Cancelled: ${tx.status}`); // \"cancelled\"\n * ```\n */\n async cancelTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'POST',\n `/transactions/${transactionId}/cancel`\n );\n return parseTransaction(response);\n }\n\n // ===========================================================================\n // Delegated Transaction Operations\n // ===========================================================================\n\n /**\n * Create a transaction token for delegated transfers.\n *\n * Creates a JWT token that authorizes the recipient to create a\n * transaction on behalf of the sender (current user). The token\n * is short-lived (typically ~5 minutes).\n *\n * Use this when you want to pre-authorize a payment that will be\n * initiated by the recipient (e.g., a service charging for usage).\n *\n * @param recipientEmail - Email of the authorized recipient\n * @returns JWT token string to share with recipient\n *\n * @example\n * ```typescript\n * // Sender creates token\n * const token = await accounting.createTransactionToken('service@example.com');\n *\n * // Share token with recipient out-of-band\n * // Recipient uses token to create delegated transaction\n * ```\n */\n async createTransactionToken(recipientEmail: string): Promise<string> {\n const response = await this.request<{ token: string }>('POST', '/token/create', {\n body: { recipientEmail },\n });\n return response.token;\n }\n\n /**\n * Create a delegated transaction using a pre-authorized token.\n *\n * Creates a transaction on behalf of the sender using their token.\n * This is typically used by services to charge users for usage.\n *\n * The token authenticates the request instead of Basic auth.\n *\n * @param senderEmail - Email of the sender who created the token\n * @param amount - Amount to transfer (must be > 0)\n * @param token - JWT token from sender's createTransactionToken()\n * @returns Transaction in PENDING status (createdBy=RECIPIENT)\n * @throws {AuthenticationError} If token is invalid or expired\n * @throws {ValidationError} If amount <= 0\n *\n * @example\n * ```typescript\n * // Recipient creates transaction using sender's token\n * const tx = await accounting.createDelegatedTransaction(\n * 'alice@example.com',\n * 5.0,\n * aliceToken\n * );\n *\n * // Recipient confirms the transaction\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n async createDelegatedTransaction(\n senderEmail: string,\n amount: number,\n token: string\n ): Promise<Transaction> {\n if (amount <= 0) {\n throw new ValidationError('Amount must be greater than 0');\n }\n\n const response = await this.requestWithToken<TransactionResponse>(\n 'POST',\n '/transactions',\n token,\n {\n body: {\n senderEmail,\n amount,\n },\n }\n );\n\n return parseTransaction(response);\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a new AccountingResource instance.\n *\n * @param options - Configuration options\n * @returns AccountingResource instance\n *\n * @example\n * ```typescript\n * const accounting = createAccountingResource({\n * url: process.env.ACCOUNTING_URL!,\n * email: process.env.ACCOUNTING_EMAIL!,\n * password: process.env.ACCOUNTING_PASSWORD!\n * });\n * ```\n */\nexport function createAccountingResource(\n options: AccountingResourceOptions\n): AccountingResource {\n return new AccountingResource(options);\n}\n","/**\n * Chat resource for RAG-augmented conversations via the Aggregator service.\n *\n * This resource handles satellite token authentication automatically:\n * - Resolves endpoints and extracts owner information\n * - Exchanges Hub access tokens for satellite tokens (one per unique owner)\n * - Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @example\n * // Simple chat completion\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n */\n\nimport type { EndpointPublic } from '../models/index.js';\nimport type {\n ChatMetadata,\n ChatOptions,\n ChatResponse,\n ChatStreamEvent,\n DocumentSource,\n EndpointRef,\n SourceInfo,\n SourceStatus,\n TokenUsage,\n} from '../models/chat.js';\nimport { SyftHubError } from '../errors.js';\nimport type { HubResource } from './hub.js';\nimport type { AuthResource } from './auth.js';\nimport { EndpointType } from '../models/index.js';\n\n/**\n * Error thrown when the aggregator service is unavailable or returns an error.\n */\nexport class AggregatorError extends SyftHubError {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AggregatorError';\n }\n}\n\n/**\n * Error thrown when an endpoint cannot be resolved.\n */\nexport class EndpointResolutionError extends SyftHubError {\n constructor(\n message: string,\n public readonly endpointPath?: string\n ) {\n super(message);\n this.name = 'EndpointResolutionError';\n }\n}\n\n/**\n * Chat resource for RAG-augmented conversations via the Aggregator.\n *\n * This resource provides high-level chat functionality that:\n * - Queries data sources for relevant context (retrieval)\n * - Sends prompts with context to model endpoints (generation)\n * - Supports both synchronous and streaming responses\n */\nexport class ChatResource {\n constructor(\n private readonly hub: HubResource,\n private readonly auth: AuthResource,\n private readonly aggregatorUrl: string\n ) {}\n\n /**\n * Convert any endpoint format to EndpointRef with URL and owner info.\n * The ownerUsername is critical for satellite token authentication.\n */\n private async resolveEndpointRef(\n endpoint: string | EndpointRef | EndpointPublic,\n expectedType?: 'model' | 'data_source'\n ): Promise<EndpointRef> {\n // Already an EndpointRef\n if (this.isEndpointRef(endpoint)) {\n return endpoint;\n }\n\n // EndpointPublic object\n if (this.isEndpointPublic(endpoint)) {\n // Validate type if expected\n if (expectedType && endpoint.type !== expectedType) {\n throw new Error(\n `Expected endpoint type '${expectedType}', got '${endpoint.type}' for '${endpoint.slug}'`\n );\n }\n\n // Find first enabled connection with URL\n for (const conn of endpoint.connect) {\n if (conn.enabled && conn.config['url']) {\n return {\n url: String(conn.config['url']),\n slug: endpoint.slug,\n name: endpoint.name,\n tenantName: conn.config['tenant_name'] as string | undefined,\n ownerUsername: endpoint.ownerUsername, // Capture owner for satellite token\n };\n }\n }\n\n throw new EndpointResolutionError(\n `Endpoint '${endpoint.slug}' has no connection with URL configured`,\n `${endpoint.ownerUsername}/${endpoint.slug}`\n );\n }\n\n // String path format \"owner/slug\"\n if (typeof endpoint === 'string') {\n let ep: EndpointPublic;\n try {\n ep = await this.hub.get(endpoint);\n } catch (error) {\n throw new EndpointResolutionError(\n `Failed to fetch endpoint '${endpoint}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint\n );\n }\n return this.resolveEndpointRef(ep, expectedType);\n }\n\n throw new TypeError(`Cannot resolve endpoint from type: ${typeof endpoint}`);\n }\n\n /**\n * Collect unique owner usernames from all endpoints.\n * Used to determine which satellite tokens need to be fetched.\n */\n private collectUniqueOwners(\n modelRef: EndpointRef,\n dataSourceRefs: EndpointRef[]\n ): string[] {\n const owners = new Set<string>();\n\n if (modelRef.ownerUsername) {\n owners.add(modelRef.ownerUsername);\n }\n\n for (const ds of dataSourceRefs) {\n if (ds.ownerUsername) {\n owners.add(ds.ownerUsername);\n }\n }\n\n return [...owners];\n }\n\n /**\n * Get satellite tokens for all unique endpoint owners.\n * Returns a map of owner username to satellite token.\n */\n private async getSatelliteTokensForOwners(\n owners: string[]\n ): Promise<Record<string, string>> {\n if (owners.length === 0) {\n return {};\n }\n\n const tokenMap = await this.auth.getSatelliteTokens(owners);\n const result: Record<string, string> = {};\n\n for (const [owner, token] of tokenMap) {\n result[owner] = token;\n }\n\n return result;\n }\n\n /**\n * Get transaction tokens for all unique endpoint owners.\n * Returns a map of owner username to transaction token.\n *\n * Transaction tokens are used for billing - they authorize the endpoint\n * owner to charge the current user for usage.\n */\n private async getTransactionTokensForOwners(\n owners: string[]\n ): Promise<Record<string, string>> {\n if (owners.length === 0) {\n return {};\n }\n\n const response = await this.auth.getTransactionTokens(owners);\n return response.tokens;\n }\n\n /**\n * Type guard for EndpointRef.\n */\n private isEndpointRef(value: unknown): value is EndpointRef {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'url' in value &&\n 'slug' in value &&\n typeof (value as EndpointRef).url === 'string' &&\n typeof (value as EndpointRef).slug === 'string'\n );\n }\n\n /**\n * Type guard for EndpointPublic.\n */\n private isEndpointPublic(value: unknown): value is EndpointPublic {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'connect' in value &&\n 'ownerUsername' in value &&\n Array.isArray((value as EndpointPublic).connect)\n );\n }\n\n /**\n * Build the request body for the aggregator.\n * Includes endpoint_tokens mapping for satellite token authentication.\n * Includes transaction_tokens mapping for billing authorization.\n * User identity is derived from satellite tokens, not passed in request body.\n */\n private buildRequestBody(\n prompt: string,\n modelRef: EndpointRef,\n dataSourceRefs: EndpointRef[],\n endpointTokens: Record<string, string>,\n transactionTokens: Record<string, string>,\n options: {\n topK?: number;\n maxTokens?: number;\n temperature?: number;\n similarityThreshold?: number;\n stream?: boolean;\n }\n ): Record<string, unknown> {\n return {\n prompt,\n model: {\n url: modelRef.url,\n slug: modelRef.slug,\n name: modelRef.name ?? '',\n tenant_name: modelRef.tenantName ?? null,\n owner_username: modelRef.ownerUsername ?? null,\n },\n data_sources: dataSourceRefs.map((ds) => ({\n url: ds.url,\n slug: ds.slug,\n name: ds.name ?? '',\n tenant_name: ds.tenantName ?? null,\n owner_username: ds.ownerUsername ?? null,\n })),\n endpoint_tokens: endpointTokens,\n transaction_tokens: transactionTokens,\n top_k: options.topK ?? 5,\n max_tokens: options.maxTokens ?? 1024,\n temperature: options.temperature ?? 0.7,\n similarity_threshold: options.similarityThreshold ?? 0.5,\n stream: options.stream ?? false,\n };\n }\n\n /**\n * Parse a SourceInfo from raw data.\n */\n private parseSourceInfo(data: Record<string, unknown>): SourceInfo {\n return {\n path: String(data['path'] ?? ''),\n documentsRetrieved: Number(data['documents_retrieved'] ?? 0),\n status: (data['status'] as SourceStatus) ?? 'success',\n errorMessage: data['error_message'] as string | undefined,\n };\n }\n\n /**\n * Parse ChatMetadata from raw data.\n */\n private parseMetadata(data: Record<string, unknown>): ChatMetadata {\n return {\n retrievalTimeMs: Number(data['retrieval_time_ms'] ?? 0),\n generationTimeMs: Number(data['generation_time_ms'] ?? 0),\n totalTimeMs: Number(data['total_time_ms'] ?? 0),\n };\n }\n\n /**\n * Parse TokenUsage from raw data.\n */\n private parseUsage(data: Record<string, unknown>): TokenUsage {\n return {\n promptTokens: Number(data['prompt_tokens'] ?? 0),\n completionTokens: Number(data['completion_tokens'] ?? 0),\n totalTokens: Number(data['total_tokens'] ?? 0),\n };\n }\n\n /**\n * Parse document sources from raw data.\n * The new format is a dict mapping document title to {slug, content}.\n */\n private parseDocumentSources(\n data: Record<string, unknown> | undefined\n ): Record<string, DocumentSource> {\n const sources: Record<string, DocumentSource> = {};\n if (!data || typeof data !== 'object') {\n return sources;\n }\n\n for (const [title, value] of Object.entries(data)) {\n if (value && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n sources[title] = {\n slug: String(source['slug'] ?? ''),\n content: String(source['content'] ?? ''),\n };\n }\n }\n return sources;\n }\n\n /**\n * Parse retrieval info (SourceInfo array) from raw data.\n */\n private parseRetrievalInfo(\n data: Record<string, unknown>[] | undefined\n ): SourceInfo[] {\n const retrievalInfo: SourceInfo[] = [];\n if (!Array.isArray(data)) {\n return retrievalInfo;\n }\n\n for (const item of data) {\n retrievalInfo.push(this.parseSourceInfo(item));\n }\n return retrievalInfo;\n }\n\n /**\n * Send a chat request and get the complete response.\n *\n * This method automatically:\n * 1. Resolves endpoints and extracts owner information\n * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)\n * 3. Fetches transaction tokens for billing authorization\n * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @param options - Chat completion options\n * @returns ChatResponse with response text, sources, and metadata\n * @throws {EndpointResolutionError} If endpoint cannot be resolved\n * @throws {AggregatorError} If aggregator service fails\n */\n async complete(options: ChatOptions): Promise<ChatResponse> {\n const modelRef = await this.resolveEndpointRef(options.model, 'model');\n\n const dsRefs: EndpointRef[] = [];\n for (const ds of options.dataSources ?? []) {\n dsRefs.push(await this.resolveEndpointRef(ds, 'data_source'));\n }\n\n // Get satellite tokens for all unique endpoint owners\n const uniqueOwners = this.collectUniqueOwners(modelRef, dsRefs);\n const endpointTokens = await this.getSatelliteTokensForOwners(uniqueOwners);\n\n // Get transaction tokens for billing authorization\n const transactionTokens = await this.getTransactionTokensForOwners(uniqueOwners);\n\n const requestBody = this.buildRequestBody(\n options.prompt,\n modelRef,\n dsRefs,\n endpointTokens,\n transactionTokens,\n {\n topK: options.topK,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n similarityThreshold: options.similarityThreshold,\n stream: false,\n }\n );\n\n const url = `${this.aggregatorUrl}/chat`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['message'] ?? data['error'] ?? message);\n } catch {\n // Use default message\n }\n throw new AggregatorError(`Aggregator error: ${message}`, response.status);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n // Parse document sources (new format: dict of title -> {slug, content})\n const sourcesData = data['sources'] as Record<string, unknown> | undefined;\n const sources = this.parseDocumentSources(sourcesData);\n\n // Parse retrieval info (metadata about each data source retrieval)\n const retrievalInfoData = data['retrieval_info'] as Record<string, unknown>[] | undefined;\n const retrievalInfo = this.parseRetrievalInfo(retrievalInfoData);\n\n const metadataData = data['metadata'] as Record<string, unknown> | undefined;\n const metadata = this.parseMetadata(metadataData ?? {});\n\n // Parse usage if available\n const usageData = data['usage'] as Record<string, unknown> | undefined;\n const usage = usageData ? this.parseUsage(usageData) : undefined;\n\n return {\n response: String(data['response'] ?? ''),\n sources,\n retrievalInfo,\n metadata,\n usage,\n };\n }\n\n /**\n * Send a chat request and stream response events.\n *\n * This method automatically:\n * 1. Resolves endpoints and extracts owner information\n * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)\n * 3. Fetches transaction tokens for billing authorization\n * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @param options - Chat completion options\n * @yields ChatStreamEvent objects as they arrive\n */\n async *stream(options: ChatOptions): AsyncGenerator<ChatStreamEvent, void, unknown> {\n const modelRef = await this.resolveEndpointRef(options.model, 'model');\n\n const dsRefs: EndpointRef[] = [];\n for (const ds of options.dataSources ?? []) {\n dsRefs.push(await this.resolveEndpointRef(ds, 'data_source'));\n }\n\n // Get satellite tokens for all unique endpoint owners\n const uniqueOwners = this.collectUniqueOwners(modelRef, dsRefs);\n const endpointTokens = await this.getSatelliteTokensForOwners(uniqueOwners);\n\n // Get transaction tokens for billing authorization\n const transactionTokens = await this.getTransactionTokensForOwners(uniqueOwners);\n\n const requestBody = this.buildRequestBody(\n options.prompt,\n modelRef,\n dsRefs,\n endpointTokens,\n transactionTokens,\n {\n topK: options.topK,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n similarityThreshold: options.similarityThreshold,\n stream: true,\n }\n );\n\n const url = `${this.aggregatorUrl}/chat/stream`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n },\n body: JSON.stringify(requestBody),\n signal: options.signal,\n });\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['message'] ?? data['error'] ?? message);\n } catch {\n // Use default message\n }\n throw new AggregatorError(`Aggregator error: ${message}`, response.status);\n }\n\n if (!response.body) {\n throw new AggregatorError('No response body from aggregator');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let currentEvent: string | null = null;\n let currentData = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (!trimmedLine) {\n // Empty line = end of event\n if (currentEvent && currentData) {\n try {\n const data = JSON.parse(currentData) as Record<string, unknown>;\n const event = this.parseSSEEvent(currentEvent, data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed data\n }\n }\n currentEvent = null;\n currentData = '';\n continue;\n }\n\n if (trimmedLine.startsWith('event:')) {\n currentEvent = trimmedLine.slice(6).trim();\n } else if (trimmedLine.startsWith('data:')) {\n currentData = trimmedLine.slice(5).trim();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n /**\n * Parse an SSE event into a typed event object.\n */\n private parseSSEEvent(\n eventType: string,\n data: Record<string, unknown>\n ): ChatStreamEvent | null {\n switch (eventType) {\n case 'retrieval_start':\n return {\n type: 'retrieval_start',\n sourceCount: Number(data['sources'] ?? 0),\n };\n\n case 'source_complete':\n return {\n type: 'source_complete',\n path: String(data['path'] ?? ''),\n status: String(data['status'] ?? ''),\n documentsRetrieved: Number(data['documents'] ?? 0),\n };\n\n case 'retrieval_complete':\n return {\n type: 'retrieval_complete',\n totalDocuments: Number(data['total_documents'] ?? 0),\n timeMs: Number(data['time_ms'] ?? 0),\n };\n\n case 'generation_start':\n return { type: 'generation_start' };\n\n case 'token':\n return {\n type: 'token',\n content: String(data['content'] ?? ''),\n };\n\n case 'done': {\n // Parse document sources (new format: dict of title -> {slug, content})\n const sourcesData = data['sources'] as Record<string, unknown> | undefined;\n const sources = this.parseDocumentSources(sourcesData);\n\n // Parse retrieval info (metadata about each data source retrieval)\n const retrievalInfoData = data['retrieval_info'] as Record<string, unknown>[] | undefined;\n const retrievalInfo = this.parseRetrievalInfo(retrievalInfoData);\n\n const metadataData = data['metadata'] as Record<string, unknown> | undefined;\n const metadata = this.parseMetadata(metadataData ?? {});\n\n // Parse usage if available (only from non-streaming mode)\n const usageData = data['usage'] as Record<string, unknown> | undefined;\n const usage = usageData ? this.parseUsage(usageData) : undefined;\n\n return { type: 'done', sources, retrievalInfo, metadata, usage };\n }\n\n case 'error':\n return {\n type: 'error',\n message: String(data['message'] ?? 'Unknown error'),\n };\n\n default:\n return {\n type: 'error',\n message: `Unknown event type: ${eventType}`,\n };\n }\n }\n\n /**\n * Get model endpoints that have connection URLs configured.\n *\n * @param limit - Maximum number of results (default: 20)\n * @returns Array of EndpointPublic objects for models with URLs\n */\n async getAvailableModels(limit = 20): Promise<EndpointPublic[]> {\n const results: EndpointPublic[] = [];\n\n for await (const endpoint of this.hub.browse()) {\n if (results.length >= limit) break;\n\n if (endpoint.type !== EndpointType.MODEL) continue;\n\n const hasUrl = endpoint.connect.some(\n (conn) => conn.enabled && conn.config['url']\n );\n\n if (hasUrl) {\n results.push(endpoint);\n }\n }\n\n return results;\n }\n\n /**\n * Get data source endpoints that have connection URLs configured.\n *\n * @param limit - Maximum number of results (default: 20)\n * @returns Array of EndpointPublic objects for data sources with URLs\n */\n async getAvailableDataSources(limit = 20): Promise<EndpointPublic[]> {\n const results: EndpointPublic[] = [];\n\n for await (const endpoint of this.hub.browse()) {\n if (results.length >= limit) break;\n\n if (endpoint.type !== EndpointType.DATA_SOURCE) continue;\n\n const hasUrl = endpoint.connect.some(\n (conn) => conn.enabled && conn.config['url']\n );\n\n if (hasUrl) {\n results.push(endpoint);\n }\n }\n\n return results;\n }\n}\n","/**\n * SyftAI-Space resource for direct endpoint queries.\n *\n * This module provides low-level access to SyftAI-Space endpoints, allowing\n * users to build custom RAG pipelines or bypass the aggregator service.\n *\n * @example\n * // Query a data source directly\n * const docs = await client.syftai.queryDataSource({\n * endpoint: { url: 'http://syftai:8080', slug: 'docs' },\n * query: 'What is machine learning?',\n * userEmail: 'alice@example.com',\n * });\n *\n * // Query a model directly\n * const response = await client.syftai.queryModel({\n * endpoint: { url: 'http://syftai:8080', slug: 'gpt-model' },\n * messages: [\n * { role: 'system', content: 'You are a helpful assistant.' },\n * { role: 'user', content: 'Hello!' },\n * ],\n * userEmail: 'alice@example.com',\n * });\n */\n\nimport type {\n Document,\n QueryDataSourceOptions,\n QueryModelOptions,\n} from '../models/chat.js';\nimport { SyftHubError } from '../errors.js';\n\n/**\n * Error thrown when data source retrieval fails.\n */\nexport class RetrievalError extends SyftHubError {\n constructor(\n message: string,\n public readonly sourcePath?: string,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'RetrievalError';\n }\n}\n\n/**\n * Error thrown when model generation fails.\n */\nexport class GenerationError extends SyftHubError {\n constructor(\n message: string,\n public readonly modelSlug?: string,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'GenerationError';\n }\n}\n\n/**\n * Low-level resource for direct SyftAI-Space endpoint queries.\n *\n * This resource provides direct access to SyftAI-Space endpoints without\n * going through the aggregator. Use this when you need:\n * - Custom RAG pipelines with specific retrieval strategies\n * - Direct model queries without data source context\n * - Fine-grained control over the query process\n *\n * For most use cases, prefer the higher-level `client.chat` API instead.\n */\nexport class SyftAIResource {\n // No dependencies - uses direct fetch to SyftAI-Space endpoints\n\n /**\n * Build headers for SyftAI-Space request.\n */\n private buildHeaders(tenantName?: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n if (tenantName) {\n headers['X-Tenant-Name'] = tenantName;\n }\n return headers;\n }\n\n /**\n * Query a data source endpoint directly.\n *\n * @param options - Query options\n * @returns Array of Document objects\n * @throws {RetrievalError} If the query fails\n */\n async queryDataSource(options: QueryDataSourceOptions): Promise<Document[]> {\n const { endpoint, query, userEmail, topK = 5, similarityThreshold = 0.5 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: query, // SyftAI-Space expects \"messages\" for query text\n limit: topK,\n similarity_threshold: similarityThreshold,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: this.buildHeaders(endpoint.tenantName),\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new RetrievalError(\n `Failed to connect to data source '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new RetrievalError(`Data source query failed: ${message}`, endpoint.slug);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const documents: Document[] = [];\n\n const docsData = data['documents'] as Record<string, unknown>[] | undefined;\n if (Array.isArray(docsData)) {\n for (const doc of docsData) {\n documents.push({\n content: String(doc['content'] ?? ''),\n score: Number(doc['score'] ?? 0),\n metadata: (doc['metadata'] as Record<string, unknown>) ?? {},\n });\n }\n }\n\n return documents;\n }\n\n /**\n * Query a model endpoint directly.\n *\n * @param options - Query options\n * @returns Generated response text\n * @throws {GenerationError} If generation fails\n */\n async queryModel(options: QueryModelOptions): Promise<string> {\n const { endpoint, messages, userEmail, maxTokens = 1024, temperature = 0.7 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n })),\n max_tokens: maxTokens,\n temperature,\n stream: false,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: this.buildHeaders(endpoint.tenantName),\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new GenerationError(\n `Failed to connect to model '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new GenerationError(`Model query failed: ${message}`, endpoint.slug);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const messageData = data['message'] as Record<string, unknown> | undefined;\n return String(messageData?.['content'] ?? '');\n }\n\n /**\n * Stream a model response directly.\n *\n * @param options - Query options\n * @yields Response text chunks as they arrive\n * @throws {GenerationError} If generation fails\n */\n async *queryModelStream(options: QueryModelOptions): AsyncGenerator<string, void, unknown> {\n const { endpoint, messages, userEmail, maxTokens = 1024, temperature = 0.7 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n })),\n max_tokens: maxTokens,\n temperature,\n stream: true,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n ...this.buildHeaders(endpoint.tenantName),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new GenerationError(\n `Failed to connect to model '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new GenerationError(`Model stream failed: ${message}`, endpoint.slug);\n }\n\n if (!response.body) {\n throw new GenerationError('No response body from model', endpoint.slug);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (!trimmedLine || trimmedLine.startsWith('event:')) {\n continue;\n }\n\n if (trimmedLine.startsWith('data:')) {\n const dataStr = trimmedLine.slice(5).trim();\n if (dataStr === '[DONE]') {\n return;\n }\n\n try {\n const data = JSON.parse(dataStr) as Record<string, unknown>;\n\n // Extract content from various response formats\n if (typeof data['content'] === 'string') {\n yield data['content'];\n } else if (Array.isArray(data['choices'])) {\n // OpenAI-style response\n for (const choice of data['choices'] as Record<string, unknown>[]) {\n const delta = choice['delta'] as Record<string, unknown> | undefined;\n if (delta && typeof delta['content'] === 'string') {\n yield delta['content'];\n }\n }\n }\n } catch {\n // Skip malformed data\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","/**\n * SyftHub TypeScript SDK\n *\n * A TypeScript client library for the SyftHub API.\n *\n * @example\n * import { SyftHubClient, EndpointType, Visibility } from '@syfthub/sdk';\n *\n * const client = new SyftHubClient({ baseUrl: 'https://hub.syft.com' });\n *\n * // Login\n * const user = await client.auth.login('alice', 'password');\n *\n * // Create an endpoint\n * const endpoint = await client.myEndpoints.create({\n * name: 'My Model',\n * type: EndpointType.MODEL,\n * visibility: Visibility.PUBLIC,\n * });\n *\n * // Browse the hub\n * for await (const ep of client.hub.browse()) {\n * console.log(ep.name);\n * }\n *\n * // Chat with RAG via aggregator\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n *\n * @packageDocumentation\n */\n\n// Main client\nexport { SyftHubClient } from './client.js';\nexport type { SyftHubClientOptions } from './client.js';\n\n// HTTP types (for advanced usage)\nexport type { AuthTokens } from './http.js';\n\n// Errors\nexport {\n SyftHubError,\n APIError,\n AuthenticationError,\n AuthorizationError,\n NotFoundError,\n ValidationError,\n NetworkError,\n ConfigurationError,\n // User registration errors\n UserAlreadyExistsError,\n // Accounting-related errors\n AccountingAccountExistsError,\n InvalidAccountingPasswordError,\n AccountingServiceUnavailableError,\n} from './errors.js';\n\n// Chat-specific errors\nexport {\n AggregatorError,\n EndpointResolutionError,\n} from './resources/chat.js';\nexport {\n RetrievalError,\n GenerationError,\n} from './resources/syftai.js';\n\n// Pagination\nexport { PageIterator } from './pagination.js';\nexport type { PageFetcher } from './pagination.js';\n\n// Models - Enums and constants\nexport {\n Visibility,\n EndpointType,\n UserRole,\n OrganizationRole,\n // Accounting enums\n TransactionStatus,\n CreatorType,\n} from './models/index.js';\n\n// Models - Types\nexport type {\n // User types\n User,\n UserRegisterInput,\n UserUpdateInput,\n PasswordChangeInput,\n AccountingCredentials,\n // Endpoint types\n Policy,\n Connection,\n Endpoint,\n EndpointPublic,\n EndpointCreateInput,\n EndpointUpdateInput,\n // Accounting types\n AccountingUser,\n Transaction,\n CreateTransactionInput,\n CreateDelegatedTransactionInput,\n UpdatePasswordInput,\n TransactionResponse,\n TransactionTokenResponse,\n // Chat types\n EndpointRef,\n Document,\n SourceStatus,\n SourceInfo,\n ChatMetadata,\n ChatResponse,\n Message,\n ChatOptions,\n QueryDataSourceOptions,\n QueryModelOptions,\n // Chat streaming events\n ChatStreamEvent,\n RetrievalStartEvent,\n SourceCompleteEvent,\n RetrievalCompleteEvent,\n GenerationStartEvent,\n TokenEvent,\n DoneEvent,\n ErrorEvent,\n} from './models/index.js';\n\n// Model helpers\nexport {\n getEndpointOwnerType,\n getEndpointPublicPath,\n // Accounting helpers\n parseTransaction,\n isTransactionPending,\n isTransactionCompleted,\n isTransactionCancelled,\n} from './models/index.js';\n\n// Accounting Resource (standalone client for external accounting service)\nexport {\n AccountingResource,\n createAccountingResource,\n} from './resources/accounting.js';\nexport type {\n AccountingResourceOptions,\n TransactionsOptions,\n} from './resources/accounting.js';\n\n// Chat Resource (for type hints)\nexport { ChatResource } from './resources/chat.js';\n\n// SyftAI Resource (for type hints)\nexport { SyftAIResource } from './resources/syftai.js';\n\n// Resource option types (for type-safe usage)\nexport type { ListEndpointsOptions } from './resources/my-endpoints.js';\nexport type { BrowseOptions, TrendingOptions } from './resources/hub.js';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/utils.ts","../src/client.ts","../src/resources/auth.ts","../src/resources/users.ts","../src/pagination.ts","../src/resources/my-endpoints.ts","../src/resources/hub.ts","../src/models/common.ts","../src/models/endpoint.ts","../src/models/accounting.ts","../src/resources/accounting.ts","../src/resources/chat.ts","../src/resources/syftai.ts","../src/index.ts"],"names":["NotFoundError","data"],"mappings":";;;;;;;;;;;AAAA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,4BAAA,EAAA,MAAA,4BAAA;AAAA,EAAA,iCAAA,EAAA,MAAA,iCAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,kBAA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,eAAA,GAA2B;AAC7B,IAAA,OAAO,IAAA,CAAK,KAAK,SAAA,EAAU;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,IAAI,uBAAA,GAAmC;AACrC,IAAA,OAAO,IAAA,CAAK,WAAA,KAAgB,MAAA,IAAa,IAAA,CAAK,WAAA,KAAgB,IAAA;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,GAAc;AAAA,EAGd;AACF;;;AYrYA,WAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Base error class for all SyftHub SDK errors.\n */\nexport class SyftHubError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SyftHubError';\n // Maintains proper stack trace for where error was thrown (V8 engines)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when an API request fails with an error status code.\n */\nexport class APIError extends SyftHubError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'APIError';\n }\n}\n\n/**\n * Error thrown when authentication is required but not provided,\n * or when credentials are invalid (HTTP 401).\n */\nexport class AuthenticationError extends SyftHubError {\n constructor(message: string = 'Authentication required') {\n super(message);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Error thrown when the user doesn't have permission to access\n * a resource (HTTP 403).\n */\nexport class AuthorizationError extends SyftHubError {\n constructor(message: string = 'Permission denied') {\n super(message);\n this.name = 'AuthorizationError';\n }\n}\n\n/**\n * Error thrown when a requested resource is not found (HTTP 404).\n */\nexport class NotFoundError extends SyftHubError {\n constructor(message: string = 'Resource not found') {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Error thrown when request validation fails (HTTP 422).\n * Contains field-level error details when available.\n */\nexport class ValidationError extends SyftHubError {\n constructor(\n message: string,\n public readonly errors?: Record<string, string[]>\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when a network request fails (connection errors, timeouts).\n */\nexport class NetworkError extends SyftHubError {\n constructor(\n message: string = 'Network request failed',\n public readonly cause?: Error\n ) {\n super(message);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Error thrown when SDK configuration is invalid.\n */\nexport class ConfigurationError extends SyftHubError {\n constructor(message: string = 'Invalid SDK configuration') {\n super(message);\n this.name = 'ConfigurationError';\n }\n}\n\n// =============================================================================\n// User Registration Errors\n// =============================================================================\n\n/**\n * Error thrown when username or email already exists in SyftHub (HTTP 409).\n *\n * This error indicates a duplicate user registration attempt.\n * The `field` property indicates which field caused the conflict.\n *\n * @example\n * ```typescript\n * try {\n * await client.auth.register({ username: \"john\", email: \"john@example.com\", ... });\n * } catch (error) {\n * if (error instanceof UserAlreadyExistsError) {\n * console.log(`${error.field} is already taken`);\n * }\n * }\n * ```\n */\nexport class UserAlreadyExistsError extends SyftHubError {\n /** The field that caused the conflict (\"username\" or \"email\") */\n public readonly field?: string;\n\n constructor(\n message: string = 'Username or email already exists',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'UserAlreadyExistsError';\n // Extract field from detail if available\n if (detail && typeof detail === 'object' && 'field' in detail) {\n this.field = (detail as { field?: string }).field;\n }\n }\n}\n\n// =============================================================================\n// Accounting-related Errors\n// =============================================================================\n\n/**\n * Error thrown when email already exists in the accounting service during registration.\n *\n * This error indicates that the user needs to provide their existing\n * accounting password to link their SyftHub account with their existing\n * accounting account.\n *\n * @example\n * ```typescript\n * try {\n * await client.auth.register({ username: \"john\", email: \"john@example.com\", ... });\n * } catch (error) {\n * if (error instanceof AccountingAccountExistsError) {\n * // Prompt user for their existing accounting password\n * const accountingPassword = prompt(\"Enter your existing accounting password:\");\n * // Retry registration with the password\n * await client.auth.register({\n * username: \"john\",\n * email: \"john@example.com\",\n * ...,\n * accountingPassword\n * });\n * }\n * }\n * ```\n */\nexport class AccountingAccountExistsError extends SyftHubError {\n /** Indicates that the user needs to provide their existing accounting password */\n public readonly requiresAccountingPassword = true;\n\n constructor(\n message: string = 'This email already has an account in the accounting service',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AccountingAccountExistsError';\n }\n}\n\n/**\n * Error thrown when the provided accounting password is invalid.\n */\nexport class InvalidAccountingPasswordError extends SyftHubError {\n constructor(\n message: string = 'The provided accounting password is invalid',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'InvalidAccountingPasswordError';\n }\n}\n\n/**\n * Error thrown when the accounting service is unavailable or returns an error.\n */\nexport class AccountingServiceUnavailableError extends SyftHubError {\n constructor(\n message: string = 'Accounting service is unavailable',\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AccountingServiceUnavailableError';\n }\n}\n","import {\n AccountingAccountExistsError,\n AccountingServiceUnavailableError,\n APIError,\n AuthenticationError,\n AuthorizationError,\n InvalidAccountingPasswordError,\n NetworkError,\n NotFoundError,\n UserAlreadyExistsError,\n ValidationError,\n} from './errors.js';\nimport { toCamelCase, toSnakeCase, buildSearchParams } from './utils.js';\n\n/**\n * Options for HTTP requests.\n */\nexport interface RequestOptions {\n /** Whether to include the Authorization header (default: true) */\n includeAuth?: boolean;\n /** Whether to send body as form-urlencoded instead of JSON */\n isFormData?: boolean;\n /** Request-specific timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Internal request options including body and params.\n */\ninterface InternalRequestOptions extends RequestOptions {\n body?: unknown;\n params?: Record<string, unknown>;\n}\n\n/**\n * Auth tokens returned from login/refresh.\n */\nexport interface AuthTokens {\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n}\n\n/**\n * Internal HTTP client for making API requests.\n *\n * Handles:\n * - Bearer token authentication\n * - Automatic token refresh on 401 responses\n * - JSON serialization/deserialization\n * - snake_case <-> camelCase conversion\n * - Error handling and exception mapping\n */\nexport class HTTPClient {\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n\n /**\n * Create a new HTTP client.\n *\n * @param baseUrl - Base URL for all API requests (without trailing slash)\n * @param timeout - Default timeout in milliseconds (default: 30000)\n */\n constructor(\n private readonly baseUrl: string,\n private readonly timeout: number = 30000\n ) {}\n\n /**\n * Set authentication tokens.\n */\n setTokens(access: string, refresh: string): void {\n this.accessToken = access;\n this.refreshToken = refresh;\n }\n\n /**\n * Get current authentication tokens.\n */\n getTokens(): AuthTokens | null {\n if (!this.accessToken || !this.refreshToken) {\n return null;\n }\n return {\n accessToken: this.accessToken,\n refreshToken: this.refreshToken,\n tokenType: 'bearer',\n };\n }\n\n /**\n * Clear authentication tokens.\n */\n clearTokens(): void {\n this.accessToken = null;\n this.refreshToken = null;\n }\n\n /**\n * Check if the client has valid tokens.\n */\n hasTokens(): boolean {\n return this.accessToken !== null;\n }\n\n /**\n * Make a GET request.\n */\n async get<T>(\n path: string,\n params?: Record<string, unknown>,\n options?: RequestOptions\n ): Promise<T> {\n return this.request<T>('GET', path, { ...options, params });\n }\n\n /**\n * Make a POST request.\n */\n async post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, { ...options, body });\n }\n\n /**\n * Make a PUT request.\n */\n async put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, { ...options, body });\n }\n\n /**\n * Make a PATCH request.\n */\n async patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>('PATCH', path, { ...options, body });\n }\n\n /**\n * Make a DELETE request.\n */\n async delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /**\n * Make an HTTP request with automatic retry on 401.\n */\n private async request<T>(\n method: string,\n path: string,\n options: InternalRequestOptions = {}\n ): Promise<T> {\n const { includeAuth = true, isFormData = false, timeout, body, params } = options;\n\n // Build URL with query params\n let url = `${this.baseUrl}${path}`;\n if (params) {\n const searchParams = buildSearchParams(params);\n const queryString = searchParams.toString();\n if (queryString) {\n url += `?${queryString}`;\n }\n }\n\n // Build headers\n const headers: Record<string, string> = {};\n\n if (includeAuth && this.accessToken) {\n headers['Authorization'] = `Bearer ${this.accessToken}`;\n }\n\n // Build body\n let requestBody: string | undefined;\n if (body !== undefined) {\n if (isFormData) {\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n // For form data, convert to URLSearchParams\n const formData = new URLSearchParams();\n for (const [key, value] of Object.entries(body as Record<string, unknown>)) {\n if (value !== undefined && value !== null) {\n formData.append(key, String(value));\n }\n }\n requestBody = formData.toString();\n } else {\n headers['Content-Type'] = 'application/json';\n // Convert camelCase to snake_case for JSON bodies\n requestBody = JSON.stringify(toSnakeCase(body));\n }\n }\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout ?? this.timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: requestBody,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Handle 401 with automatic token refresh\n if (response.status === 401 && includeAuth && this.refreshToken) {\n // Attempt to refresh the token\n await this.attemptTokenRefresh();\n\n // Retry the original request with new token\n return this.request<T>(method, path, {\n ...options,\n // Mark that we shouldn't retry again to prevent infinite loops\n includeAuth: true,\n });\n }\n\n return await this.handleResponse<T>(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof SyftHubError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new NetworkError('Request timed out', error);\n }\n throw new NetworkError(error.message, error);\n }\n\n throw new NetworkError('Unknown network error');\n }\n }\n\n /**\n * Handle the HTTP response and convert to the expected type.\n */\n private async handleResponse<T>(response: Response): Promise<T> {\n // Try to parse response as JSON\n let data: unknown;\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json')) {\n try {\n data = await response.json();\n } catch {\n data = null;\n }\n } else {\n // For non-JSON responses, use text\n const text = await response.text();\n data = text || null;\n }\n\n // Handle error responses\n if (!response.ok) {\n this.handleErrorResponse(response.status, data);\n }\n\n // Convert snake_case to camelCase and parse dates\n return toCamelCase<T>(data);\n }\n\n /**\n * Handle error responses by throwing appropriate exceptions.\n */\n private handleErrorResponse(status: number, data: unknown): never {\n const message = this.extractErrorMessage(data);\n const { code, detail } = this.extractErrorCodeAndDetail(data);\n\n // Check for domain-specific errors based on error code first\n if (code) {\n switch (code) {\n // User registration errors\n case 'USER_ALREADY_EXISTS':\n throw new UserAlreadyExistsError(message, detail);\n // Accounting-related errors\n case 'ACCOUNTING_ACCOUNT_EXISTS':\n throw new AccountingAccountExistsError(message, detail);\n case 'INVALID_ACCOUNTING_PASSWORD':\n throw new InvalidAccountingPasswordError(message, detail);\n case 'ACCOUNTING_SERVICE_UNAVAILABLE':\n throw new AccountingServiceUnavailableError(message, detail);\n }\n }\n\n // Standard status code handling\n switch (status) {\n case 401:\n throw new AuthenticationError(message);\n case 403:\n throw new AuthorizationError(message);\n case 404:\n throw new NotFoundError(message);\n case 422:\n throw new ValidationError(message, this.extractValidationErrors(data));\n default:\n throw new APIError(message, status, data);\n }\n }\n\n /**\n * Extract error code and detail from API response.\n * Used for accounting-specific error handling.\n */\n private extractErrorCodeAndDetail(data: unknown): { code?: string; detail?: unknown } {\n if (!data || typeof data !== 'object') {\n return {};\n }\n\n // FastAPI returns { detail: { code: \"...\", message: \"...\", ... } }\n if ('detail' in data) {\n const detail = (data as { detail: unknown }).detail;\n if (detail && typeof detail === 'object' && 'code' in detail) {\n const innerDetail = detail as { code?: string };\n return {\n code: innerDetail.code,\n detail: detail,\n };\n }\n }\n\n return {};\n }\n\n /**\n * Extract error message from API response.\n */\n private extractErrorMessage(data: unknown): string {\n if (typeof data === 'string') {\n return data;\n }\n\n if (data && typeof data === 'object') {\n // FastAPI style: { detail: \"message\" }\n if ('detail' in data) {\n const detail = (data as { detail: unknown }).detail;\n if (typeof detail === 'string') {\n return detail;\n }\n // FastAPI validation errors: { detail: [{ msg: \"...\", loc: [...] }] }\n if (Array.isArray(detail) && detail.length > 0) {\n const firstError = detail[0] as { msg?: string };\n if (firstError?.msg) {\n return firstError.msg;\n }\n }\n }\n\n // Generic: { message: \"...\" } or { error: \"...\" }\n if ('message' in data && typeof (data as { message: unknown }).message === 'string') {\n return (data as { message: string }).message;\n }\n if ('error' in data && typeof (data as { error: unknown }).error === 'string') {\n return (data as { error: string }).error;\n }\n }\n\n return 'An error occurred';\n }\n\n /**\n * Extract field-level validation errors from API response.\n */\n private extractValidationErrors(data: unknown): Record<string, string[]> | undefined {\n if (!data || typeof data !== 'object' || !('detail' in data)) {\n return undefined;\n }\n\n const detail = (data as { detail: unknown }).detail;\n if (!Array.isArray(detail)) {\n return undefined;\n }\n\n const errors: Record<string, string[]> = {};\n\n for (const error of detail) {\n if (typeof error === 'object' && error !== null && 'loc' in error && 'msg' in error) {\n const { loc, msg } = error as { loc: unknown[]; msg: string };\n // loc is typically ['body', 'field_name']\n const field = String(loc[loc.length - 1] ?? 'unknown');\n if (!errors[field]) {\n errors[field] = [];\n }\n errors[field].push(msg);\n }\n }\n\n return Object.keys(errors).length > 0 ? errors : undefined;\n }\n\n /**\n * Attempt to refresh the access token using the refresh token.\n */\n private async attemptTokenRefresh(): Promise<void> {\n // If already refreshing, wait for the existing refresh to complete\n if (this.isRefreshing && this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.isRefreshing = true;\n\n this.refreshPromise = (async () => {\n try {\n const response = await fetch(`${this.baseUrl}/api/v1/auth/refresh`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ refresh_token: this.refreshToken }),\n });\n\n if (!response.ok) {\n // Refresh failed, clear tokens\n this.clearTokens();\n throw new AuthenticationError('Token refresh failed');\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n };\n\n this.accessToken = data.access_token;\n this.refreshToken = data.refresh_token;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n await this.refreshPromise;\n }\n}\n\n// Import SyftHubError for type checking\nimport { SyftHubError } from './errors.js';\n","/**\n * Convert a snake_case string to camelCase.\n *\n * @example\n * snakeToCamel('created_at') // 'createdAt'\n * snakeToCamel('full_name') // 'fullName'\n */\nexport function snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/**\n * Convert a camelCase string to snake_case.\n *\n * @example\n * camelToSnake('createdAt') // 'created_at'\n * camelToSnake('fullName') // 'full_name'\n */\nexport function camelToSnake(str: string): string {\n return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n}\n\n/**\n * Regular expression to match ISO 8601 date strings.\n */\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n/**\n * Check if a value looks like an ISO date string.\n */\nfunction isISODateString(value: unknown): value is string {\n return typeof value === 'string' && ISO_DATE_REGEX.test(value);\n}\n\n/**\n * Recursively transform object keys using the provided transformer function.\n * Optionally parses ISO date strings to Date objects.\n *\n * @param obj - The object to transform\n * @param keyTransformer - Function to transform each key\n * @param parseDates - Whether to parse ISO date strings to Date objects\n */\nexport function transformKeys<T>(\n obj: unknown,\n keyTransformer: (key: string) => string,\n parseDates = true\n): T {\n // Handle null and undefined\n if (obj === null || obj === undefined) {\n return obj as T;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => transformKeys(item, keyTransformer, parseDates)) as T;\n }\n\n // Handle date strings\n if (parseDates && isISODateString(obj)) {\n return new Date(obj) as T;\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const transformed: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n transformed[keyTransformer(key)] = transformKeys(value, keyTransformer, parseDates);\n }\n return transformed as T;\n }\n\n // Return primitives as-is\n return obj as T;\n}\n\n/**\n * Convert all keys in an object from camelCase to snake_case.\n * Does not parse dates (for request bodies).\n */\nexport function toSnakeCase<T>(obj: unknown): T {\n return transformKeys<T>(obj, camelToSnake, false);\n}\n\n/**\n * Convert all keys in an object from snake_case to camelCase.\n * Parses ISO date strings to Date objects (for response bodies).\n */\nexport function toCamelCase<T>(obj: unknown): T {\n return transformKeys<T>(obj, snakeToCamel, true);\n}\n\n/**\n * Build URL search params from an object, filtering out undefined values.\n */\nexport function buildSearchParams(params: Record<string, unknown>): URLSearchParams {\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(camelToSnake(key), String(value));\n }\n }\n\n return searchParams;\n}\n","import { HTTPClient, type AuthTokens } from './http.js';\nimport { AuthenticationError, ConfigurationError, SyftHubError } from './errors.js';\nimport { AuthResource } from './resources/auth.js';\nimport { UsersResource } from './resources/users.js';\nimport { MyEndpointsResource } from './resources/my-endpoints.js';\nimport { HubResource } from './resources/hub.js';\nimport { AccountingResource } from './resources/accounting.js';\nimport { ChatResource } from './resources/chat.js';\nimport { SyftAIResource } from './resources/syftai.js';\n\n/**\n * Configuration options for SyftHubClient.\n */\nexport interface SyftHubClientOptions {\n /**\n * Base URL for the SyftHub API.\n * Falls back to SYFTHUB_URL environment variable.\n * @example 'https://hub.syft.com'\n */\n baseUrl?: string;\n\n /**\n * Request timeout in milliseconds.\n * @default 30000\n */\n timeout?: number;\n\n /**\n * Base URL for the aggregator service (optional).\n * Falls back to SYFTHUB_AGGREGATOR_URL environment variable.\n * Defaults to {baseUrl}/aggregator/api/v1\n */\n aggregatorUrl?: string;\n}\n\n/**\n * Get environment variable, handling both Node.js and browser environments.\n */\nfunction getEnv(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n/**\n * Check if running in a browser environment.\n */\nfunction isBrowser(): boolean {\n return (\n typeof globalThis !== 'undefined' &&\n typeof (globalThis as { window?: unknown }).window !== 'undefined' &&\n typeof (globalThis as { document?: unknown }).document !== 'undefined'\n );\n}\n\n/**\n * SyftHub SDK client for interacting with the SyftHub API.\n *\n * @example\n * // Basic usage\n * import { SyftHubClient } from '@syfthub/sdk';\n *\n * const client = new SyftHubClient({ baseUrl: 'https://hub.syft.com' });\n *\n * // Or use environment variable\n * // Set SYFTHUB_URL=https://hub.syft.com\n * const client = new SyftHubClient();\n *\n * @example\n * // Authentication\n * const user = await client.auth.login('alice', 'password123');\n * console.log(`Logged in as ${user.username}`);\n *\n * // Get current user\n * const me = await client.auth.me();\n *\n * @example\n * // Browse endpoints\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Manage your endpoints\n * const endpoint = await client.myEndpoints.create({\n * name: 'My Model',\n * type: 'model',\n * visibility: 'public',\n * });\n *\n * @example\n * // Token persistence\n * const tokens = client.getTokens();\n * // Save tokens to storage...\n *\n * // Later, restore tokens\n * client.setTokens(savedTokens);\n */\nexport class SyftHubClient {\n private readonly http: HTTPClient;\n private readonly options: SyftHubClientOptions;\n private readonly aggregatorUrl: string;\n\n // Lazy-initialized resources\n private _auth?: AuthResource;\n private _users?: UsersResource;\n private _myEndpoints?: MyEndpointsResource;\n private _hub?: HubResource;\n private _accounting?: AccountingResource;\n private _accountingInitPromise: Promise<AccountingResource> | null = null;\n private _chat?: ChatResource;\n private _syftai?: SyftAIResource;\n\n /**\n * Create a new SyftHub client.\n *\n * @param options - Configuration options\n * @throws {SyftHubError} If baseUrl is not provided and SYFTHUB_URL is not set (in non-browser environments)\n */\n constructor(options: SyftHubClientOptions = {}) {\n this.options = options;\n let baseUrl = options.baseUrl ?? getEnv('SYFTHUB_URL');\n\n // In browser environments, empty baseUrl means same-origin requests\n // This is valid and commonly used when the API is served from the same domain\n if (!baseUrl && !isBrowser()) {\n throw new SyftHubError(\n 'baseUrl is required. Provide it in options or set the SYFTHUB_URL environment variable.'\n );\n }\n\n // Default to empty string for same-origin browser requests\n baseUrl = baseUrl ?? '';\n\n // Remove trailing slash from base URL (only if not empty)\n const normalizedUrl = baseUrl ? baseUrl.replace(/\\/+$/, '') : '';\n\n this.http = new HTTPClient(normalizedUrl, options.timeout ?? 30000);\n\n // Resolve aggregator URL (default to {baseUrl}/aggregator/api/v1)\n this.aggregatorUrl =\n options.aggregatorUrl ??\n getEnv('SYFTHUB_AGGREGATOR_URL') ??\n `${normalizedUrl}/aggregator/api/v1`;\n }\n\n /**\n * Authentication resource for login, register, and session management.\n *\n * @example\n * const user = await client.auth.login('alice', 'password');\n * await client.auth.logout();\n */\n get auth(): AuthResource {\n if (!this._auth) {\n this._auth = new AuthResource(this.http);\n }\n return this._auth;\n }\n\n /**\n * Users resource for profile management.\n *\n * @example\n * const user = await client.users.update({ fullName: 'Alice Smith' });\n * const available = await client.users.checkUsername('newname');\n */\n get users(): UsersResource {\n if (!this._users) {\n this._users = new UsersResource(this.http);\n }\n return this._users;\n }\n\n /**\n * My Endpoints resource for managing your own endpoints.\n *\n * @example\n * const endpoints = await client.myEndpoints.list().all();\n * const endpoint = await client.myEndpoints.create({ name: 'My API', type: 'model' });\n */\n get myEndpoints(): MyEndpointsResource {\n if (!this._myEndpoints) {\n this._myEndpoints = new MyEndpointsResource(this.http);\n }\n return this._myEndpoints;\n }\n\n /**\n * Hub resource for browsing public endpoints.\n *\n * @example\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n */\n get hub(): HubResource {\n if (!this._hub) {\n this._hub = new HubResource(this.http);\n }\n return this._hub;\n }\n\n /**\n * Accounting resource for billing and transactions.\n *\n * The accounting service is external and uses separate credentials\n * (email/password Basic auth) from SyftHub's JWT authentication.\n *\n * Credentials are automatically retrieved from the backend after login.\n * You must call `initAccounting()` after login to initialize this resource.\n *\n * @throws {AuthenticationError} If not initialized\n *\n * @example\n * // Login first, then initialize accounting\n * await client.auth.login('alice', 'password');\n * await client.initAccounting();\n *\n * // Now accounting is available\n * const user = await client.accounting.getUser();\n */\n get accounting(): AccountingResource {\n if (this._accounting) {\n return this._accounting;\n }\n\n throw new AuthenticationError(\n 'Accounting not initialized. ' + 'Call `await client.initAccounting()` after login.'\n );\n }\n\n /**\n * Initialize accounting resource by fetching credentials from the backend.\n *\n * This method retrieves accounting credentials from the SyftHub backend\n * and initializes the accounting resource. Requires authentication.\n *\n * @returns The initialized AccountingResource\n * @throws {AuthenticationError} If not authenticated\n * @throws {ConfigurationError} If user has no accounting service configured\n *\n * @example\n * // Login first, then initialize accounting\n * await client.auth.login('alice', 'password');\n * await client.initAccounting();\n *\n * // Now accounting is available\n * const user = await client.accounting.getUser();\n */\n async initAccounting(): Promise<AccountingResource> {\n // Return cached instance\n if (this._accounting) {\n return this._accounting;\n }\n\n // Prevent concurrent initialization\n if (this._accountingInitPromise) {\n return this._accountingInitPromise;\n }\n\n this._accountingInitPromise = this._doInitAccounting();\n\n try {\n this._accounting = await this._accountingInitPromise;\n return this._accounting;\n } finally {\n this._accountingInitPromise = null;\n }\n }\n\n /**\n * Internal method to perform accounting initialization.\n */\n private async _doInitAccounting(): Promise<AccountingResource> {\n if (!this.isAuthenticated) {\n throw new AuthenticationError(\n 'Must be logged in to use accounting. ' + 'Call client.auth.login() first.'\n );\n }\n\n // Fetch credentials from backend\n const creds = await this.users.getAccountingCredentials();\n\n if (!creds.url) {\n throw new ConfigurationError(\n 'No accounting service configured for this user. ' +\n 'Contact your administrator to set up accounting.'\n );\n }\n\n if (!creds.password) {\n throw new ConfigurationError(\n 'Accounting password not available. ' +\n 'This may indicate an issue with your account setup.'\n );\n }\n\n return new AccountingResource({\n url: creds.url,\n email: creds.email,\n password: creds.password,\n timeout: this.options.timeout,\n });\n }\n\n /**\n * Chat resource for RAG-augmented conversations via the Aggregator.\n *\n * This resource provides high-level chat functionality that integrates\n * with the SyftHub Aggregator service for RAG workflows.\n *\n * @example\n * // Simple chat completion\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n *\n * // Get available endpoints\n * const models = await client.chat.getAvailableModels();\n * const sources = await client.chat.getAvailableDataSources();\n */\n get chat(): ChatResource {\n if (!this._chat) {\n this._chat = new ChatResource(this.hub, this.auth, this.aggregatorUrl);\n }\n return this._chat;\n }\n\n /**\n * SyftAI-Space resource for direct endpoint queries (low-level API).\n *\n * This resource provides direct access to SyftAI-Space endpoints without\n * going through the aggregator. Use this when you need custom RAG pipelines\n * or fine-grained control over queries.\n *\n * For most use cases, prefer the higher-level `client.chat` API instead.\n *\n * @example\n * // Query a data source directly\n * const docs = await client.syftai.queryDataSource({\n * endpoint: { url: 'http://syftai:8080', slug: 'docs' },\n * query: 'What is Python?',\n * userEmail: 'alice@example.com',\n * });\n *\n * // Query a model directly\n * const response = await client.syftai.queryModel({\n * endpoint: { url: 'http://syftai:8080', slug: 'gpt-model' },\n * messages: [{ role: 'user', content: 'Hello!' }],\n * userEmail: 'alice@example.com',\n * });\n */\n get syftai(): SyftAIResource {\n if (!this._syftai) {\n this._syftai = new SyftAIResource();\n }\n return this._syftai;\n }\n\n /**\n * Get current authentication tokens.\n *\n * Use this to persist tokens for later sessions.\n *\n * @returns Current tokens or null if not authenticated\n *\n * @example\n * const tokens = client.getTokens();\n * if (tokens) {\n * localStorage.setItem('tokens', JSON.stringify(tokens));\n * }\n */\n getTokens(): AuthTokens | null {\n return this.http.getTokens();\n }\n\n /**\n * Set authentication tokens.\n *\n * Use this to restore a session from previously saved tokens.\n *\n * @param tokens - Tokens to set\n *\n * @example\n * const saved = JSON.parse(localStorage.getItem('tokens'));\n * if (saved) {\n * client.setTokens(saved);\n * }\n */\n setTokens(tokens: AuthTokens): void {\n this.http.setTokens(tokens.accessToken, tokens.refreshToken);\n }\n\n /**\n * Check if the client is currently authenticated.\n *\n * @returns True if tokens are present\n */\n get isAuthenticated(): boolean {\n return this.http.hasTokens();\n }\n\n /**\n * Check if accounting has been initialized.\n *\n * Use this to check if accounting is available before accessing\n * the `accounting` property, which will throw if not initialized.\n *\n * @returns True if accounting has been initialized via `initAccounting()`\n *\n * @example\n * if (client.isAccountingInitialized) {\n * const user = await client.accounting.getUser();\n * }\n */\n get isAccountingInitialized(): boolean {\n return this._accounting !== undefined && this._accounting !== null;\n }\n\n /**\n * Close the client and clean up resources.\n *\n * Currently a no-op, but may be used in future for connection pooling.\n */\n close(): void {\n // Currently a no-op\n // Could be used for cleanup in future (e.g., connection pools)\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type { User, UserRegisterInput } from '../models/index.js';\nimport { AuthenticationError } from '../errors.js';\n\n/**\n * Response from login/register endpoints.\n */\ninterface AuthResponse {\n user: User;\n accessToken: string;\n refreshToken: string;\n tokenType: string;\n}\n\n/**\n * Authentication resource for login, register, and session management.\n *\n * @example\n * // Register a new user\n * const user = await client.auth.register({\n * username: 'alice',\n * email: 'alice@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Alice'\n * });\n *\n * @example\n * // Login\n * const user = await client.auth.login('alice', 'SecurePass123!');\n *\n * @example\n * // Get current user\n * const me = await client.auth.me();\n *\n * @example\n * // Logout\n * await client.auth.logout();\n */\nexport class AuthResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Register a new user account.\n *\n * If an accounting service URL is configured (via `accountingServiceUrl` or server default),\n * the backend will handle accounting integration using a \"try-create-first\" approach:\n *\n * **Accounting Password Behavior:**\n * - **Not provided**: A secure password is auto-generated and a new accounting account is created.\n * - **Provided (new user)**: The account is created with your chosen password.\n * - **Provided (existing user)**: Your password is validated and accounts are linked.\n *\n * This means you can set your own accounting password during registration even if you're\n * a new user - you don't need an existing accounting account first.\n *\n * @param input - Registration details (username, email, password, fullName)\n * @returns The created User\n * @throws {ValidationError} If input validation fails\n * @throws {UserAlreadyExistsError} If username or email already exists in SyftHub\n * @throws {AccountingAccountExistsError} If email already exists in accounting service\n * and no `accountingPassword` was provided. Retry with the password.\n * @throws {InvalidAccountingPasswordError} If the provided accounting password doesn't\n * match an existing accounting account\n * @throws {AccountingServiceUnavailableError} If the accounting service is unreachable\n *\n * @example\n * // Basic registration (auto-generated accounting password)\n * const user = await client.auth.register({\n * username: 'alice',\n * email: 'alice@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Alice'\n * });\n *\n * @example\n * // Registration with custom accounting password (NEW user)\n * const user = await client.auth.register({\n * username: 'bob',\n * email: 'bob@example.com',\n * password: 'SecurePass123!',\n * fullName: 'Bob',\n * accountingPassword: 'MyChosenAccountingPass!' // Creates account with this password\n * });\n *\n * @example\n * // Handle existing accounting account\n * try {\n * await client.auth.register({ username, email, password, fullName });\n * } catch (error) {\n * if (error instanceof AccountingAccountExistsError) {\n * // Prompt user for their existing accounting password\n * const accountingPassword = await promptUser('Enter your existing accounting password:');\n * await client.auth.register({ username, email, password, fullName, accountingPassword });\n * } else {\n * throw error;\n * }\n * }\n */\n async register(input: UserRegisterInput): Promise<User> {\n const response = await this.http.post<AuthResponse>('/api/v1/auth/register', input, {\n includeAuth: false,\n });\n\n // Store tokens in HTTP client\n this.http.setTokens(response.accessToken, response.refreshToken);\n\n return response.user;\n }\n\n /**\n * Login with username/email and password.\n *\n * Uses OAuth2 password flow (form-urlencoded body).\n *\n * @param username - Username or email\n * @param password - Password\n * @returns The authenticated User\n * @throws {AuthenticationError} If credentials are invalid\n */\n async login(username: string, password: string): Promise<User> {\n const response = await this.http.post<AuthResponse>(\n '/api/v1/auth/login',\n { username, password },\n {\n includeAuth: false,\n isFormData: true,\n }\n );\n\n // Store tokens in HTTP client\n this.http.setTokens(response.accessToken, response.refreshToken);\n\n return response.user;\n }\n\n /**\n * Logout the current user.\n *\n * Invalidates tokens on the server and clears local token storage.\n */\n async logout(): Promise<void> {\n try {\n await this.http.post<void>('/api/v1/auth/logout');\n } finally {\n // Always clear tokens, even if the API call fails\n this.http.clearTokens();\n }\n }\n\n /**\n * Get the current authenticated user.\n *\n * @returns The current User\n * @throws {AuthenticationError} If not authenticated\n */\n async me(): Promise<User> {\n return this.http.get<User>('/api/v1/auth/me');\n }\n\n /**\n * Manually refresh the access token.\n *\n * This is normally handled automatically when a request returns 401.\n *\n * @throws {AuthenticationError} If refresh token is invalid or expired\n */\n async refresh(): Promise<void> {\n const tokens = this.http.getTokens();\n if (!tokens) {\n throw new AuthenticationError('No refresh token available');\n }\n\n const response = await this.http.post<{\n accessToken: string;\n refreshToken: string;\n }>('/api/v1/auth/refresh', { refreshToken: tokens.refreshToken }, { includeAuth: false });\n\n this.http.setTokens(response.accessToken, response.refreshToken);\n }\n\n /**\n * Change the current user's password.\n *\n * @param currentPassword - Current password for verification\n * @param newPassword - New password to set\n * @throws {AuthenticationError} If current password is incorrect\n * @throws {ValidationError} If new password doesn't meet requirements\n */\n async changePassword(currentPassword: string, newPassword: string): Promise<void> {\n await this.http.put<void>('/api/v1/auth/me/password', {\n currentPassword,\n newPassword,\n });\n }\n\n /**\n * Get a satellite token for a specific audience (target service).\n *\n * Satellite tokens are short-lived, RS256-signed JWTs that allow satellite\n * services (like SyftAI-Space) to verify user identity without calling\n * SyftHub for every request.\n *\n * @param audience - Target service identifier (username of the service owner)\n * @returns Satellite token response with token and expiry\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If audience is invalid or inactive\n *\n * @example\n * // Get a token for querying alice's SyftAI-Space endpoints\n * const tokenResponse = await client.auth.getSatelliteToken('alice');\n * console.log(`Token expires in ${tokenResponse.expiresIn} seconds`);\n */\n async getSatelliteToken(audience: string): Promise<SatelliteTokenResponse> {\n return this.http.get<SatelliteTokenResponse>('/api/v1/token', { aud: audience });\n }\n\n /**\n * Get satellite tokens for multiple audiences in parallel.\n *\n * This is useful when making requests to endpoints owned by different users.\n * Tokens are cached and reused where possible.\n *\n * @param audiences - Array of unique audience identifiers (usernames)\n * @returns Map of audience to satellite token\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * // Get tokens for multiple endpoint owners\n * const tokens = await client.auth.getSatelliteTokens(['alice', 'bob']);\n * console.log(`Got ${tokens.size} tokens`);\n */\n async getSatelliteTokens(audiences: string[]): Promise<Map<string, string>> {\n const uniqueAudiences = [...new Set(audiences)];\n const tokenMap = new Map<string, string>();\n\n // Fetch tokens in parallel\n const results = await Promise.allSettled(\n uniqueAudiences.map(async (aud) => {\n const response = await this.getSatelliteToken(aud);\n return { audience: aud, token: response.targetToken };\n })\n );\n\n // Collect successful results\n for (const result of results) {\n if (result.status === 'fulfilled') {\n tokenMap.set(result.value.audience, result.value.token);\n }\n // Failed tokens are silently skipped - the aggregator will handle missing tokens\n }\n\n return tokenMap;\n }\n\n /**\n * Get transaction tokens for multiple endpoint owners.\n *\n * Transaction tokens are short-lived JWTs that pre-authorize the endpoint owner\n * (recipient) to charge the current user (sender) for usage. These tokens are\n * created via the accounting service and passed to the aggregator.\n *\n * This is used by the chat flow to enable billing for endpoint usage.\n *\n * @param ownerUsernames - Array of endpoint owner usernames\n * @returns TransactionTokensResponse with tokens map and any errors\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * // Get transaction tokens for endpoint owners\n * const response = await client.auth.getTransactionTokens(['alice', 'bob']);\n * console.log(`Got ${Object.keys(response.tokens).length} tokens`);\n * if (Object.keys(response.errors).length > 0) {\n * console.log('Some tokens failed:', response.errors);\n * }\n */\n async getTransactionTokens(ownerUsernames: string[]): Promise<TransactionTokensResponse> {\n const uniqueOwners = [...new Set(ownerUsernames)];\n\n if (uniqueOwners.length === 0) {\n return { tokens: {}, errors: {} };\n }\n\n try {\n return await this.http.post<TransactionTokensResponse>(\n '/api/v1/accounting/transaction-tokens',\n { owner_usernames: uniqueOwners }\n );\n } catch (error) {\n // If accounting is not configured or fails, return empty tokens\n // The chat can proceed without transaction tokens (billing will fail later)\n console.warn('Failed to get transaction tokens:', error);\n return { tokens: {}, errors: {} };\n }\n }\n}\n\n/**\n * Response from satellite token endpoint.\n */\nexport interface SatelliteTokenResponse {\n /** RS256-signed JWT for the target service */\n targetToken: string;\n /** Seconds until the token expires */\n expiresIn: number;\n}\n\n/**\n * Response from transaction tokens endpoint.\n */\nexport interface TransactionTokensResponse {\n /** Mapping of owner_username to transaction token */\n tokens: Record<string, string>;\n /** Mapping of owner_username to error message (for failed tokens) */\n errors: Record<string, string>;\n}\n","import type { HTTPClient } from '../http.js';\nimport type { AccountingCredentials, User, UserUpdateInput } from '../models/index.js';\n\n/**\n * Users resource for profile management and availability checks.\n *\n * @example\n * // Update your profile\n * const user = await client.users.update({\n * fullName: 'Alice Smith',\n * avatarUrl: 'https://example.com/avatar.jpg'\n * });\n *\n * @example\n * // Check if username is available\n * const available = await client.users.checkUsername('newusername');\n *\n * @example\n * // Check if email is available\n * const available = await client.users.checkEmail('new@example.com');\n */\nexport class UsersResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Update the current user's profile.\n *\n * Only provided fields will be updated.\n *\n * @param input - Fields to update\n * @returns The updated User\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If input validation fails\n */\n async update(input: UserUpdateInput): Promise<User> {\n return this.http.put<User>('/api/v1/users/me', input);\n }\n\n /**\n * Check if a username is available.\n *\n * @param username - Username to check\n * @returns True if the username is available\n */\n async checkUsername(username: string): Promise<boolean> {\n const response = await this.http.get<{ available: boolean }>(\n `/api/v1/users/check-username/${encodeURIComponent(username)}`,\n undefined,\n { includeAuth: false }\n );\n return response.available;\n }\n\n /**\n * Check if an email is available.\n *\n * @param email - Email to check\n * @returns True if the email is available\n */\n async checkEmail(email: string): Promise<boolean> {\n const response = await this.http.get<{ available: boolean }>(\n `/api/v1/users/check-email/${encodeURIComponent(email)}`,\n undefined,\n { includeAuth: false }\n );\n return response.available;\n }\n\n /**\n * Get the current user's accounting service credentials.\n *\n * Returns credentials stored in SyftHub for connecting to an external\n * accounting service. The email is always the same as the user's SyftHub email.\n *\n * @returns Accounting credentials (url and password may be null if not configured)\n * @throws {AuthenticationError} If not authenticated\n *\n * @example\n * const credentials = await client.users.getAccountingCredentials();\n * if (credentials.url && credentials.password) {\n * // Use credentials to connect to accounting service\n * }\n */\n async getAccountingCredentials(): Promise<AccountingCredentials> {\n return this.http.get<AccountingCredentials>('/api/v1/users/me/accounting');\n }\n}\n","/**\n * Function type for fetching a page of items.\n */\nexport type PageFetcher<T> = (skip: number, limit: number) => Promise<T[]>;\n\n/**\n * Lazy async iterator for paginated API responses.\n *\n * Fetches pages on demand as you iterate, minimizing API calls\n * and memory usage for large datasets.\n *\n * @example\n * // Iterate through all items\n * for await (const endpoint of client.hub.browse()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Get just the first page\n * const firstPage = await client.hub.browse().firstPage();\n *\n * @example\n * // Get first 10 items\n * const top10 = await client.hub.browse().take(10);\n */\nexport class PageIterator<T> implements AsyncIterable<T> {\n private items: T[] = [];\n private index = 0;\n private skip = 0;\n private exhausted = false;\n private initialized = false;\n\n /**\n * Create a new PageIterator.\n *\n * @param fetcher - Function that fetches a page of items given skip and limit\n * @param pageSize - Number of items to fetch per page (default: 20)\n */\n constructor(\n private readonly fetcher: PageFetcher<T>,\n private readonly pageSize: number = 20\n ) {}\n\n /**\n * Async iterator implementation for `for await...of` loops.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n while (true) {\n // If we've consumed all items in the current page\n if (this.index >= this.items.length) {\n if (this.exhausted) break;\n await this.fetchNextPage();\n if (this.items.length === 0) break;\n }\n\n const item = this.items[this.index];\n if (item === undefined) break;\n\n this.index++;\n yield item;\n }\n }\n\n /**\n * Get just the first page of results.\n *\n * @returns Promise resolving to the first page of items\n */\n async firstPage(): Promise<T[]> {\n if (!this.initialized) {\n await this.fetchNextPage();\n }\n return [...this.items];\n }\n\n /**\n * Get all items across all pages.\n *\n * Warning: This loads all items into memory. For large datasets,\n * consider iterating with `for await...of` instead.\n *\n * @returns Promise resolving to all items\n */\n async all(): Promise<T[]> {\n const results: T[] = [];\n for await (const item of this) {\n results.push(item);\n }\n return results;\n }\n\n /**\n * Get the first N items.\n *\n * @param n - Maximum number of items to return\n * @returns Promise resolving to up to N items\n */\n async take(n: number): Promise<T[]> {\n const results: T[] = [];\n for await (const item of this) {\n results.push(item);\n if (results.length >= n) break;\n }\n return results;\n }\n\n /**\n * Fetch the next page of items from the API.\n */\n private async fetchNextPage(): Promise<void> {\n const page = await this.fetcher(this.skip, this.pageSize);\n this.items = page;\n this.index = 0;\n this.skip += this.pageSize;\n this.exhausted = page.length < this.pageSize;\n this.initialized = true;\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type {\n Endpoint,\n EndpointCreateInput,\n EndpointUpdateInput,\n SyncEndpointsResponse,\n Visibility,\n} from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\n\n/**\n * Options for listing endpoints.\n */\nexport interface ListEndpointsOptions {\n /** Filter by visibility level */\n visibility?: Visibility;\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * My Endpoints resource for CRUD operations on user's own endpoints.\n *\n * For browsing public endpoints from other users, see the Hub resource.\n *\n * @example\n * // List your endpoints\n * for await (const endpoint of client.myEndpoints.list()) {\n * console.log(endpoint.name);\n * }\n *\n * @example\n * // Create a new endpoint\n * const endpoint = await client.myEndpoints.create({\n * name: 'My API',\n * type: 'model',\n * visibility: 'public',\n * description: 'A cool API'\n * });\n *\n * @example\n * // Get a specific endpoint\n * const endpoint = await client.myEndpoints.get('alice/my-api');\n *\n * @example\n * // Update an endpoint\n * const updated = await client.myEndpoints.update('alice/my-api', {\n * description: 'Updated description'\n * });\n *\n * @example\n * // Delete an endpoint\n * await client.myEndpoints.delete('alice/my-api');\n */\nexport class MyEndpointsResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Parse an endpoint path into owner and slug.\n *\n * @param path - Path in \"owner/slug\" format\n * @returns Tuple of [owner, slug]\n * @throws {Error} If path format is invalid\n */\n private parsePath(path: string): [string, string] {\n const parts = path.replace(/^\\/|\\/$/g, '').split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid endpoint path: '${path}'. Expected format: 'owner/slug'`);\n }\n return [parts[0], parts[1]];\n }\n\n /**\n * List the current user's endpoints.\n *\n * @param options - Filtering and pagination options\n * @returns PageIterator that lazily fetches endpoints\n * @throws {AuthenticationError} If not authenticated\n */\n list(options?: ListEndpointsOptions): PageIterator<Endpoint> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<Endpoint>(async (skip, limit) => {\n const params: Record<string, unknown> = { skip, limit };\n if (options?.visibility) {\n params['visibility'] = options.visibility;\n }\n return this.http.get<Endpoint[]>('/api/v1/endpoints', params);\n }, pageSize);\n }\n\n /**\n * Create a new endpoint.\n *\n * @param input - Endpoint creation details\n * @param organizationId - Optional organization ID (for org-owned endpoints)\n * @returns The created Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If input validation fails\n */\n async create(input: EndpointCreateInput, organizationId?: number): Promise<Endpoint> {\n const body = organizationId !== undefined ? { ...input, organizationId } : input;\n return this.http.post<Endpoint>('/api/v1/endpoints', body);\n }\n\n /**\n * Get a specific endpoint by path.\n *\n * @param path - Endpoint path in \"owner/slug\" format (e.g., \"alice/my-api\")\n * @returns The Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not authorized to view\n */\n async get(path: string): Promise<Endpoint> {\n const [, slug] = this.parsePath(path);\n\n // Search user's own endpoints by slug\n // /api/v1/endpoints returns EndpointResponse with full details including id\n const endpoints = await this.http.get<Endpoint[]>('/api/v1/endpoints', { limit: 100 });\n\n for (const ep of endpoints) {\n if (ep.slug === slug) {\n return ep;\n }\n }\n\n // Import NotFoundError here to avoid circular dependency\n const { NotFoundError } = await import('../errors.js');\n throw new NotFoundError(\n `Endpoint not found: '${path}'. No endpoint found with slug '${slug}' in your endpoints.`\n );\n }\n\n /**\n * Update an endpoint.\n *\n * Only provided fields will be updated.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @param input - Fields to update\n * @returns The updated Endpoint\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not owner/admin\n */\n async update(path: string, input: EndpointUpdateInput): Promise<Endpoint> {\n const [, slug] = this.parsePath(path);\n // Use slug-based endpoint directly instead of resolving ID\n return this.http.patch<Endpoint>(`/api/v1/endpoints/slug/${slug}`, input);\n }\n\n /**\n * Delete an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n * @throws {AuthorizationError} If not owner/admin\n */\n async delete(path: string): Promise<void> {\n const [, slug] = this.parsePath(path);\n // Use slug-based endpoint directly instead of resolving ID\n await this.http.delete<void>(`/api/v1/endpoints/slug/${slug}`);\n }\n\n /**\n * Synchronize user's endpoints with provided list.\n *\n * This is a DESTRUCTIVE operation that:\n * 1. Deletes ALL existing endpoints owned by the current user\n * 2. Creates ALL endpoints from the provided list\n * 3. Is ATOMIC: either all endpoints sync successfully, or none do\n *\n * Important Notes:\n * - Organization endpoints are NOT affected\n * - Stars on existing endpoints will be lost (reset to 0)\n * - Endpoint IDs will change (new IDs assigned)\n * - Maximum 100 endpoints per sync request\n *\n * @param endpoints - List of endpoint specifications to sync.\n * Pass an empty array to delete ALL user endpoints.\n * @returns SyncEndpointsResponse with synced count, deleted count, and created endpoints\n * @throws {AuthenticationError} If not authenticated\n * @throws {ValidationError} If any endpoint fails validation (entire batch rejected)\n *\n * @example\n * // Sync with new endpoints\n * const result = await client.myEndpoints.sync([\n * { name: 'Model A', type: 'model', visibility: 'public' },\n * { name: 'Data Source B', type: 'data_source', visibility: 'private' },\n * ]);\n * console.log(`Deleted ${result.deleted}, created ${result.synced} endpoints`);\n *\n * @example\n * // Clear all endpoints\n * const result = await client.myEndpoints.sync([]);\n * console.log(`Deleted ${result.deleted} endpoints`);\n */\n async sync(endpoints: EndpointCreateInput[] = []): Promise<SyncEndpointsResponse> {\n return this.http.post<SyncEndpointsResponse>('/api/v1/endpoints/sync', { endpoints });\n }\n}\n","import type { HTTPClient } from '../http.js';\nimport type {\n EndpointPublic,\n EndpointSearchResult,\n EndpointSearchResponse,\n SearchOptions,\n} from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\n\n/**\n * Options for browsing endpoints.\n */\nexport interface BrowseOptions {\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * Options for trending endpoints.\n */\nexport interface TrendingOptions {\n /** Minimum number of stars */\n minStars?: number;\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n/**\n * Hub resource for browsing and discovering public endpoints.\n *\n * For managing your own endpoints, see the MyEndpoints resource.\n *\n * @example\n * // Browse all public endpoints\n * for await (const endpoint of client.hub.browse()) {\n * console.log(`${endpoint.ownerUsername}/${endpoint.slug}: ${endpoint.name}`);\n * }\n *\n * @example\n * // Get trending endpoints\n * for await (const endpoint of client.hub.trending({ minStars: 10 })) {\n * console.log(`${endpoint.name} - ${endpoint.starsCount} stars`);\n * }\n *\n * @example\n * // Semantic search for endpoints\n * const results = await client.hub.search('machine learning for images');\n * for (const result of results) {\n * console.log(`${result.ownerUsername}/${result.slug}: ${result.relevanceScore.toFixed(2)}`);\n * }\n *\n * @example\n * // Get a specific endpoint\n * const endpoint = await client.hub.get('alice/cool-api');\n * console.log(endpoint.readme);\n *\n * @example\n * // Star an endpoint (requires auth)\n * await client.hub.star('alice/cool-api');\n *\n * @example\n * // Check if you've starred an endpoint\n * const starred = await client.hub.isStarred('alice/cool-api');\n */\nexport class HubResource {\n constructor(private readonly http: HTTPClient) {}\n\n /**\n * Parse an endpoint path into owner and slug.\n *\n * @param path - Path in \"owner/slug\" format\n * @returns Tuple of [owner, slug]\n */\n private parsePath(path: string): [string, string] {\n const parts = path.replace(/^\\/|\\/$/g, '').split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Error(`Invalid endpoint path: '${path}'. Expected format: 'owner/slug'`);\n }\n return [parts[0], parts[1]];\n }\n\n /**\n * Resolve an endpoint path to its ID.\n *\n * This searches the user's own endpoints to find the ID.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @returns The endpoint ID\n */\n private async resolveEndpointId(path: string): Promise<number> {\n const [, slug] = this.parsePath(path);\n\n // Search the user's endpoints to find the ID\n // This uses /api/v1/endpoints which returns full details including ID\n const endpoints = await this.http.get<Array<{ id?: number; slug?: string }>>(\n '/api/v1/endpoints',\n { limit: 100 }\n );\n\n for (const ep of endpoints) {\n if (ep.slug === slug && ep.id !== undefined) {\n return ep.id;\n }\n }\n\n // Import NotFoundError here to avoid circular dependency\n const { NotFoundError } = await import('../errors.js');\n throw new NotFoundError(\n `Could not resolve endpoint ID for '${path}'. ` +\n \"Endpoint not found or you don't have access to get its ID.\"\n );\n }\n\n /**\n * Browse all public endpoints.\n *\n * @param options - Pagination options\n * @returns PageIterator that lazily fetches endpoints\n */\n browse(options?: BrowseOptions): PageIterator<EndpointPublic> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<EndpointPublic>(async (skip, limit) => {\n return this.http.get<EndpointPublic[]>(\n '/api/v1/endpoints/public',\n { skip, limit },\n { includeAuth: false }\n );\n }, pageSize);\n }\n\n /**\n * Get trending endpoints sorted by stars.\n *\n * @param options - Filter and pagination options\n * @returns PageIterator that lazily fetches endpoints\n */\n trending(options?: TrendingOptions): PageIterator<EndpointPublic> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<EndpointPublic>(async (skip, limit) => {\n const params: Record<string, unknown> = { skip, limit };\n if (options?.minStars !== undefined) {\n params['minStars'] = options.minStars;\n }\n return this.http.get<EndpointPublic[]>('/api/v1/endpoints/trending', params, {\n includeAuth: false,\n });\n }, pageSize);\n }\n\n /**\n * Search for endpoints using semantic search.\n *\n * Uses RAG-powered semantic search to find endpoints that match the\n * natural language query. Returns results sorted by relevance score.\n *\n * Note: If RAG is not configured on the server (no OpenAI API key),\n * this method returns an empty array.\n *\n * @param query - Natural language search query (e.g., \"machine learning models for image classification\")\n * @param options - Search options (topK, type filter, minScore)\n * @returns Promise resolving to array of EndpointSearchResult with relevance scores.\n * Returns empty array if query is too short (<3 chars) or no matches found.\n *\n * @example\n * // Search for machine learning models\n * const results = await client.hub.search('image classification models');\n * for (const result of results) {\n * console.log(`${result.ownerUsername}/${result.slug}: ${result.relevanceScore.toFixed(2)}`);\n * }\n *\n * @example\n * // Filter by type and minimum score\n * const dataSources = await client.hub.search('customer data', {\n * type: EndpointType.DATA_SOURCE,\n * minScore: 0.5,\n * });\n */\n async search(query: string, options: SearchOptions = {}): Promise<EndpointSearchResult[]> {\n const { topK = 10, type, minScore = 0 } = options;\n\n // Skip search for very short queries\n if (!query || query.trim().length < 3) {\n return [];\n }\n\n const body: Record<string, unknown> = {\n query: query.trim(),\n top_k: topK,\n };\n\n if (type !== undefined) {\n body['type'] = type;\n }\n\n try {\n const response = await this.http.post<EndpointSearchResponse>(\n '/api/v1/endpoints/search',\n body,\n { includeAuth: false }\n );\n\n // Filter by minScore and return results\n return (response.results ?? []).filter((result) => result.relevanceScore >= minScore);\n } catch {\n // Return empty array on any error (e.g., RAG not configured)\n return [];\n }\n }\n\n /**\n * Get an endpoint by its path.\n *\n * This method searches the public endpoints API to find the endpoint,\n * which works reliably across all deployment configurations.\n *\n * @param path - Endpoint path in \"owner/slug\" format (e.g., \"alice/cool-api\")\n * @returns The EndpointPublic\n * @throws {NotFoundError} If endpoint not found\n */\n async get(path: string): Promise<EndpointPublic> {\n const [owner, slug] = this.parsePath(path);\n\n // Search public endpoints to find the matching one\n // This approach works because /api/v1/endpoints/public is reliably\n // served by the backend API, unlike /{owner}/{slug} which may be\n // intercepted by frontend routing in some deployments.\n for await (const endpoint of this.browse({ pageSize: 100 })) {\n if (endpoint.ownerUsername === owner && endpoint.slug === slug) {\n return endpoint;\n }\n }\n\n // Import NotFoundError here to avoid circular dependency\n const { NotFoundError } = await import('../errors.js');\n throw new NotFoundError(\n `Endpoint not found: '${path}'. No public endpoint found with owner '${owner}' and slug '${slug}'.`\n );\n }\n\n /**\n * Star an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async star(path: string): Promise<void> {\n const endpointId = await this.resolveEndpointId(path);\n // Use POST method for starring (not PATCH)\n await this.http.post<void>(`/api/v1/endpoints/${endpointId}/star`);\n }\n\n /**\n * Unstar an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async unstar(path: string): Promise<void> {\n const endpointId = await this.resolveEndpointId(path);\n // Use DELETE method to /star endpoint (not PATCH to /unstar)\n await this.http.delete<void>(`/api/v1/endpoints/${endpointId}/star`);\n }\n\n /**\n * Check if you have starred an endpoint.\n *\n * @param path - Endpoint path in \"owner/slug\" format\n * @returns True if starred, False otherwise\n * @throws {AuthenticationError} If not authenticated\n * @throws {NotFoundError} If endpoint not found\n */\n async isStarred(path: string): Promise<boolean> {\n const endpointId = await this.resolveEndpointId(path);\n const response = await this.http.get<{ starred: boolean }>(\n `/api/v1/endpoints/${endpointId}/starred`\n );\n return response.starred ?? false;\n }\n}\n","/**\n * Visibility levels for endpoints.\n */\nexport const Visibility = {\n /** Visible to everyone, no authentication required */\n PUBLIC: 'public',\n /** Only visible to the owner and collaborators */\n PRIVATE: 'private',\n /** Visible to authenticated users within the organization */\n INTERNAL: 'internal',\n} as const;\n\nexport type Visibility = (typeof Visibility)[keyof typeof Visibility];\n\n/**\n * Types of endpoints.\n */\nexport const EndpointType = {\n /** Machine learning model endpoint */\n MODEL: 'model',\n /** Data source endpoint */\n DATA_SOURCE: 'data_source',\n} as const;\n\nexport type EndpointType = (typeof EndpointType)[keyof typeof EndpointType];\n\n/**\n * User roles in the system.\n */\nexport const UserRole = {\n /** Administrator with full access */\n ADMIN: 'admin',\n /** Regular user */\n USER: 'user',\n /** Guest user with limited access */\n GUEST: 'guest',\n} as const;\n\nexport type UserRole = (typeof UserRole)[keyof typeof UserRole];\n\n/**\n * Organization member roles.\n */\nexport const OrganizationRole = {\n /** Organization owner with full control */\n OWNER: 'owner',\n /** Administrator with management privileges */\n ADMIN: 'admin',\n /** Regular member */\n MEMBER: 'member',\n} as const;\n\nexport type OrganizationRole = (typeof OrganizationRole)[keyof typeof OrganizationRole];\n","import type { EndpointType, Visibility } from './common.js';\n\n/**\n * Policy configuration for an endpoint.\n */\nexport interface Policy {\n readonly type: string;\n readonly version: string;\n readonly enabled: boolean;\n readonly description: string;\n readonly config: Record<string, unknown>;\n}\n\n/**\n * Connection configuration for an endpoint.\n */\nexport interface Connection {\n readonly type: string;\n readonly enabled: boolean;\n readonly description: string;\n readonly config: Record<string, unknown>;\n}\n\n/**\n * Full endpoint model (for authenticated users viewing their own endpoints).\n */\nexport interface Endpoint {\n readonly id: number;\n readonly userId: number | null;\n readonly organizationId: number | null;\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly type: EndpointType;\n readonly visibility: Visibility;\n readonly isActive: boolean;\n readonly contributors: readonly number[];\n readonly version: string;\n readonly readme: string;\n readonly tags: readonly string[];\n readonly starsCount: number;\n readonly policies: readonly Policy[];\n readonly connect: readonly Connection[];\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\n/**\n * Public endpoint model (for browsing the hub).\n */\nexport interface EndpointPublic {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly type: EndpointType;\n readonly ownerUsername: string;\n /** Number of contributors (user IDs not exposed for privacy) */\n readonly contributorsCount: number;\n readonly version: string;\n readonly readme: string;\n readonly tags: readonly string[];\n readonly starsCount: number;\n readonly policies: readonly Policy[];\n readonly connect: readonly Connection[];\n readonly createdAt: Date;\n readonly updatedAt: Date;\n}\n\n/**\n * Search result with relevance score from semantic search.\n *\n * Extends the public endpoint fields with a relevance score indicating\n * how well the endpoint matches the search query.\n */\nexport interface EndpointSearchResult {\n readonly name: string;\n readonly slug: string;\n readonly description: string;\n readonly type: EndpointType;\n readonly ownerUsername: string;\n /** Number of contributors (user IDs not exposed for privacy) */\n readonly contributorsCount: number;\n readonly version: string;\n readonly readme: string;\n readonly tags: readonly string[];\n readonly starsCount: number;\n readonly policies: readonly Policy[];\n readonly connect: readonly Connection[];\n readonly createdAt: Date;\n readonly updatedAt: Date;\n /** Relevance score from semantic search (0.0-1.0) */\n readonly relevanceScore: number;\n}\n\n/**\n * Response from the endpoint search API.\n */\nexport interface EndpointSearchResponse {\n readonly results: readonly EndpointSearchResult[];\n readonly total: number;\n readonly query: string;\n}\n\n/**\n * Options for semantic search.\n */\nexport interface SearchOptions {\n /** Maximum number of results to return (default: 10) */\n topK?: number;\n /** Filter by endpoint type */\n type?: EndpointType;\n /** Minimum relevance score threshold (0.0-1.0, default: 0.0) */\n minScore?: number;\n}\n\n/**\n * Get the full path for a search result (owner/slug format).\n *\n * @param result - The search result\n * @returns The path in \"owner/slug\" format\n */\nexport function getSearchResultPath(result: EndpointSearchResult): string {\n return `${result.ownerUsername}/${result.slug}`;\n}\n\n/**\n * Input for creating a new endpoint.\n */\nexport interface EndpointCreateInput {\n name: string;\n type: EndpointType;\n visibility?: Visibility;\n description?: string;\n slug?: string;\n version?: string;\n readme?: string;\n tags?: string[];\n policies?: Policy[];\n connect?: Connection[];\n contributors?: number[];\n}\n\n/**\n * Input for updating an existing endpoint.\n */\nexport interface EndpointUpdateInput {\n name?: string;\n description?: string;\n visibility?: Visibility;\n version?: string;\n readme?: string;\n tags?: string[];\n policies?: Policy[];\n connect?: Connection[];\n contributors?: number[];\n}\n\n/**\n * Get the owner type for an endpoint.\n *\n * @param endpoint - The endpoint to check\n * @returns 'user' if user-owned, 'organization' if org-owned\n */\nexport function getEndpointOwnerType(endpoint: Endpoint): 'user' | 'organization' {\n return endpoint.organizationId !== null ? 'organization' : 'user';\n}\n\n/**\n * Get the full path for a public endpoint (owner/slug format).\n *\n * @param endpoint - The public endpoint\n * @returns The path in \"owner/slug\" format\n */\nexport function getEndpointPublicPath(endpoint: EndpointPublic): string {\n return `${endpoint.ownerUsername}/${endpoint.slug}`;\n}\n\n/**\n * Response from the sync endpoints operation.\n *\n * Contains details about the sync operation including how many endpoints\n * were deleted, how many were created, and the full list of created endpoints.\n */\nexport interface SyncEndpointsResponse {\n /** Number of endpoints created */\n readonly synced: number;\n /** Number of endpoints deleted */\n readonly deleted: number;\n /** List of created endpoints with full details */\n readonly endpoints: readonly Endpoint[];\n}\n","/**\n * Accounting Models\n *\n * Models for the external accounting service. The accounting service manages\n * user balances and transactions, and uses its own authentication separate\n * from SyftHub.\n */\n\n// =============================================================================\n// Enums\n// =============================================================================\n\n/**\n * Transaction status in the accounting service.\n */\nexport const TransactionStatus = {\n /** Transaction created, awaiting confirmation */\n PENDING: 'pending',\n /** Transaction confirmed, funds transferred */\n COMPLETED: 'completed',\n /** Transaction cancelled, no funds transferred */\n CANCELLED: 'cancelled',\n} as const;\n\nexport type TransactionStatus = (typeof TransactionStatus)[keyof typeof TransactionStatus];\n\n/**\n * Who created or resolved a transaction.\n */\nexport const CreatorType = {\n /** System-initiated transaction */\n SYSTEM: 'system',\n /** Sender-initiated transaction */\n SENDER: 'sender',\n /** Recipient-initiated transaction (delegated) */\n RECIPIENT: 'recipient',\n} as const;\n\nexport type CreatorType = (typeof CreatorType)[keyof typeof CreatorType];\n\n// =============================================================================\n// Core Models\n// =============================================================================\n\n/**\n * User from accounting service with balance.\n *\n * This represents the user's account in the external accounting service,\n * which is separate from the SyftHub user account.\n */\nexport interface AccountingUser {\n readonly id: string;\n readonly email: string;\n readonly balance: number;\n readonly organization: string | null;\n}\n\n/**\n * Transaction record from accounting service.\n *\n * Transactions go through a lifecycle:\n * 1. Created (status=PENDING)\n * 2. Confirmed or Cancelled (status=COMPLETED or CANCELLED)\n *\n * The createdBy field indicates who initiated the transaction:\n * - SENDER: Direct transaction by the payer\n * - RECIPIENT: Delegated transaction using a token\n * - SYSTEM: System-initiated transaction\n *\n * The resolvedBy field indicates who confirmed/cancelled.\n */\nexport interface Transaction {\n readonly id: string;\n readonly senderEmail: string;\n readonly recipientEmail: string;\n readonly amount: number;\n readonly status: TransactionStatus;\n readonly createdBy: CreatorType;\n readonly resolvedBy: CreatorType | null;\n readonly createdAt: Date;\n readonly resolvedAt: Date | null;\n readonly appName: string | null;\n readonly appEpPath: string | null;\n}\n\n// =============================================================================\n// Input Types\n// =============================================================================\n\n/**\n * Input for creating a direct transaction.\n */\nexport interface CreateTransactionInput {\n /** Email of the recipient */\n recipientEmail: string;\n /** Amount to transfer (must be > 0) */\n amount: number;\n /** Optional app name for context (e.g., \"syftai-space\") */\n appName?: string;\n /** Optional endpoint path for context (e.g., \"alice/model\") */\n appEpPath?: string;\n}\n\n/**\n * Input for creating a delegated transaction.\n */\nexport interface CreateDelegatedTransactionInput {\n /** Email of the sender who created the token */\n senderEmail: string;\n /** Amount to transfer (must be > 0) */\n amount: number;\n /** JWT token from sender's createTransactionToken() */\n token: string;\n}\n\n/**\n * Input for updating password.\n */\nexport interface UpdatePasswordInput {\n /** Current password for verification */\n currentPassword: string;\n /** New password to set */\n newPassword: string;\n}\n\n// =============================================================================\n// Response Types (from API)\n// =============================================================================\n\n/**\n * Raw transaction response from API (before date parsing).\n */\nexport interface TransactionResponse {\n id: string;\n senderEmail: string;\n recipientEmail: string;\n amount: number;\n status: TransactionStatus;\n createdBy: CreatorType;\n resolvedBy: CreatorType | null;\n createdAt: string;\n resolvedAt: string | null;\n appName: string | null;\n appEpPath: string | null;\n}\n\n/**\n * Token response from createTransactionToken.\n */\nexport interface TransactionTokenResponse {\n token: string;\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Parse a transaction response into a Transaction object.\n */\nexport function parseTransaction(response: TransactionResponse): Transaction {\n return {\n ...response,\n createdAt: new Date(response.createdAt),\n resolvedAt: response.resolvedAt ? new Date(response.resolvedAt) : null,\n };\n}\n\n/**\n * Check if a transaction is pending.\n */\nexport function isTransactionPending(tx: Transaction): boolean {\n return tx.status === TransactionStatus.PENDING;\n}\n\n/**\n * Check if a transaction is completed.\n */\nexport function isTransactionCompleted(tx: Transaction): boolean {\n return tx.status === TransactionStatus.COMPLETED;\n}\n\n/**\n * Check if a transaction is cancelled.\n */\nexport function isTransactionCancelled(tx: Transaction): boolean {\n return tx.status === TransactionStatus.CANCELLED;\n}\n","/**\n * Accounting Resource for SyftHub SDK\n *\n * This module connects to an external accounting/billing service for managing\n * user balances and transactions. The accounting service is separate from SyftHub\n * and uses its own authentication (Basic auth with email/password).\n *\n * @example\n * ```typescript\n * // Create accounting client\n * const accounting = new AccountingResource({\n * url: 'https://accounting.example.com',\n * email: 'user@example.com',\n * password: 'secret'\n * });\n *\n * // Get user balance\n * const user = await accounting.getUser();\n * console.log(`Balance: ${user.balance}`);\n *\n * // Create a transaction\n * const tx = await accounting.createTransaction({\n * recipientEmail: 'recipient@example.com',\n * amount: 10.0,\n * appName: 'syftai-space',\n * appEpPath: 'alice/my-model'\n * });\n *\n * // Confirm the transaction\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n\nimport {\n type AccountingUser,\n type Transaction,\n type TransactionResponse,\n type CreateTransactionInput,\n parseTransaction,\n} from '../models/index.js';\nimport { PageIterator } from '../pagination.js';\nimport {\n AuthenticationError,\n AuthorizationError,\n NotFoundError,\n ValidationError,\n APIError,\n SyftHubError,\n} from '../errors.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for creating an AccountingResource.\n */\nexport interface AccountingResourceOptions {\n /** Accounting service URL */\n url: string;\n /** Email for Basic auth */\n email: string;\n /** Password for Basic auth */\n password: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Options for listing transactions.\n */\nexport interface TransactionsOptions {\n /** Number of items per page (default: 20) */\n pageSize?: number;\n}\n\n// =============================================================================\n// Error Handling\n// =============================================================================\n\n/**\n * Handle HTTP error responses from accounting service.\n */\nasync function handleResponseError(response: Response): Promise<void> {\n if (response.ok) return;\n\n let detail: string;\n try {\n const body = (await response.json()) as { detail?: string; message?: string };\n detail = body.detail ?? body.message ?? JSON.stringify(body);\n } catch {\n detail = (await response.text()) || `HTTP ${response.status}`;\n }\n\n switch (response.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 403:\n throw new AuthorizationError(`Permission denied: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 422:\n throw new ValidationError(`Validation error: ${detail}`);\n default:\n throw new APIError(`Accounting API error: ${detail}`, response.status);\n }\n}\n\n/**\n * Create Basic auth header value.\n */\nfunction createBasicAuth(email: string, password: string): string {\n const credentials = `${email}:${password}`;\n // Use btoa for browser, Buffer for Node.js\n const encoded =\n typeof btoa !== 'undefined' ? btoa(credentials) : Buffer.from(credentials).toString('base64');\n return `Basic ${encoded}`;\n}\n\n// =============================================================================\n// AccountingResource\n// =============================================================================\n\n/**\n * Handle accounting/billing operations with external service.\n *\n * The accounting service manages user balances and transactions. It uses\n * Basic auth (email/password) for authentication, which is separate from\n * SyftHub's JWT-based authentication.\n *\n * Transaction Workflow:\n * 1. Sender creates transaction (status=PENDING)\n * 2. Either party confirms (status=COMPLETED) or cancels (status=CANCELLED)\n *\n * Delegated Transaction Workflow:\n * 1. Sender creates a transaction token for recipient\n * 2. Recipient uses token to create delegated transaction\n * 3. Recipient confirms the transaction\n */\nexport class AccountingResource {\n private readonly baseUrl: string;\n private readonly email: string;\n private readonly password: string;\n private readonly timeout: number;\n private readonly authHeader: string;\n\n constructor(options: AccountingResourceOptions) {\n this.baseUrl = options.url.replace(/\\/$/, ''); // Remove trailing slash\n this.email = options.email;\n this.password = options.password;\n this.timeout = options.timeout ?? 30000;\n this.authHeader = createBasicAuth(this.email, this.password);\n }\n\n // ===========================================================================\n // Private HTTP Methods\n // ===========================================================================\n\n /**\n * Make an authenticated request to the accounting service.\n */\n private async request<T>(\n method: string,\n path: string,\n options?: {\n body?: Record<string, unknown>;\n params?: Record<string, string | number>;\n }\n ): Promise<T> {\n const url = new URL(path, this.baseUrl);\n\n if (options?.params) {\n for (const [key, value] of Object.entries(options.params)) {\n url.searchParams.set(key, String(value));\n }\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url.toString(), {\n method,\n headers: {\n Authorization: this.authHeader,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n await handleResponseError(response);\n\n if (response.status === 204) {\n return {} as T;\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof SyftHubError) {\n throw error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n throw new APIError('Request timeout', 408);\n }\n throw new APIError(\n `Accounting request failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 0\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Make a request using Bearer token auth (for delegated transactions).\n */\n private async requestWithToken<T>(\n method: string,\n path: string,\n token: string,\n options?: {\n body?: Record<string, unknown>;\n }\n ): Promise<T> {\n const url = new URL(path, this.baseUrl);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url.toString(), {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: options?.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n await handleResponseError(response);\n\n if (response.status === 204) {\n return {} as T;\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof SyftHubError) {\n throw error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n throw new APIError('Request timeout', 408);\n }\n throw new APIError(\n `Accounting request failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 0\n );\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n // ===========================================================================\n // User Operations\n // ===========================================================================\n\n /**\n * Get the current user's account information including balance.\n *\n * @returns AccountingUser with id, email, balance, and organization\n * @throws {AuthenticationError} If authentication fails\n * @throws {APIError} On other errors\n *\n * @example\n * ```typescript\n * const user = await accounting.getUser();\n * console.log(`Balance: ${user.balance}`);\n * console.log(`Organization: ${user.organization}`);\n * ```\n */\n async getUser(): Promise<AccountingUser> {\n return this.request<AccountingUser>('GET', '/user');\n }\n\n /**\n * Update the user's password.\n *\n * @param currentPassword - Current password for verification\n * @param newPassword - New password to set\n * @throws {AuthenticationError} If current password is wrong\n * @throws {ValidationError} If new password doesn't meet requirements\n *\n * @example\n * ```typescript\n * await accounting.updatePassword('old_secret', 'new_secret');\n * ```\n */\n async updatePassword(currentPassword: string, newPassword: string): Promise<void> {\n await this.request<void>('PUT', '/user/password', {\n body: {\n oldPassword: currentPassword,\n newPassword: newPassword,\n },\n });\n }\n\n /**\n * Update the user's organization.\n *\n * @param organization - New organization name\n * @throws {AuthenticationError} If authentication fails\n *\n * @example\n * ```typescript\n * await accounting.updateOrganization('OpenMined');\n * ```\n */\n async updateOrganization(organization: string): Promise<void> {\n await this.request<void>('PUT', '/user/organization', {\n body: { organization },\n });\n }\n\n // ===========================================================================\n // Transaction Listing\n // ===========================================================================\n\n /**\n * List account transactions with pagination.\n *\n * Returns a lazy iterator that fetches pages on demand.\n *\n * @param options - Pagination options\n * @returns PageIterator that yields Transaction objects\n *\n * @example\n * ```typescript\n * // Iterate through all transactions\n * for await (const tx of accounting.getTransactions()) {\n * console.log(`${tx.createdAt}: ${tx.amount} from ${tx.senderEmail}`);\n * }\n *\n * // Get first page only\n * const firstPage = await accounting.getTransactions().firstPage();\n *\n * // Get all transactions\n * const allTxs = await accounting.getTransactions().all();\n * ```\n */\n getTransactions(options?: TransactionsOptions): PageIterator<Transaction> {\n const pageSize = options?.pageSize ?? 20;\n\n return new PageIterator<Transaction>(async (skip, limit) => {\n const response = await this.request<TransactionResponse[]>('GET', '/transactions', {\n params: { skip, limit },\n });\n return response.map(parseTransaction);\n }, pageSize);\n }\n\n /**\n * Get a specific transaction by ID.\n *\n * @param transactionId - The transaction ID\n * @returns Transaction object\n * @throws {NotFoundError} If transaction not found\n *\n * @example\n * ```typescript\n * const tx = await accounting.getTransaction('tx_123');\n * console.log(`Status: ${tx.status}`);\n * ```\n */\n async getTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'GET',\n `/transactions/${transactionId}`\n );\n return parseTransaction(response);\n }\n\n // ===========================================================================\n // Direct Transaction Operations\n // ===========================================================================\n\n /**\n * Create a new transaction (direct transfer).\n *\n * Creates a PENDING transaction that must be confirmed or cancelled.\n * The transaction is created by the sender (current user).\n *\n * @param input - Transaction details\n * @returns Transaction in PENDING status\n * @throws {ValidationError} If amount <= 0 or insufficient balance\n *\n * @example\n * ```typescript\n * const tx = await accounting.createTransaction({\n * recipientEmail: 'bob@example.com',\n * amount: 10.0,\n * appName: 'syftai-space',\n * appEpPath: 'alice/my-model'\n * });\n * console.log(`Created transaction ${tx.id}: ${tx.status}`);\n *\n * // Later, confirm or cancel\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n async createTransaction(input: CreateTransactionInput): Promise<Transaction> {\n if (input.amount <= 0) {\n throw new ValidationError('Amount must be greater than 0');\n }\n\n const response = await this.request<TransactionResponse>('POST', '/transactions', {\n body: {\n recipientEmail: input.recipientEmail,\n amount: input.amount,\n ...(input.appName && { appName: input.appName }),\n ...(input.appEpPath && { appEpPath: input.appEpPath }),\n },\n });\n\n return parseTransaction(response);\n }\n\n /**\n * Confirm a pending transaction.\n *\n * Confirms the transaction, transferring funds from sender to recipient.\n * Can be called by either the sender or recipient.\n *\n * @param transactionId - The transaction ID to confirm\n * @returns Transaction in COMPLETED status\n * @throws {NotFoundError} If transaction not found\n * @throws {ValidationError} If transaction is not in PENDING status\n *\n * @example\n * ```typescript\n * const tx = await accounting.confirmTransaction('tx_123');\n * console.log(`Confirmed: ${tx.status}`); // \"completed\"\n * ```\n */\n async confirmTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'POST',\n `/transactions/${transactionId}/confirm`\n );\n return parseTransaction(response);\n }\n\n /**\n * Cancel a pending transaction.\n *\n * Cancels the transaction without transferring funds.\n * Can be called by either the sender or recipient.\n *\n * @param transactionId - The transaction ID to cancel\n * @returns Transaction in CANCELLED status\n * @throws {NotFoundError} If transaction not found\n * @throws {ValidationError} If transaction is not in PENDING status\n *\n * @example\n * ```typescript\n * const tx = await accounting.cancelTransaction('tx_123');\n * console.log(`Cancelled: ${tx.status}`); // \"cancelled\"\n * ```\n */\n async cancelTransaction(transactionId: string): Promise<Transaction> {\n const response = await this.request<TransactionResponse>(\n 'POST',\n `/transactions/${transactionId}/cancel`\n );\n return parseTransaction(response);\n }\n\n // ===========================================================================\n // Delegated Transaction Operations\n // ===========================================================================\n\n /**\n * Create a transaction token for delegated transfers.\n *\n * Creates a JWT token that authorizes the recipient to create a\n * transaction on behalf of the sender (current user). The token\n * is short-lived (typically ~5 minutes).\n *\n * Use this when you want to pre-authorize a payment that will be\n * initiated by the recipient (e.g., a service charging for usage).\n *\n * @param recipientEmail - Email of the authorized recipient\n * @returns JWT token string to share with recipient\n *\n * @example\n * ```typescript\n * // Sender creates token\n * const token = await accounting.createTransactionToken('service@example.com');\n *\n * // Share token with recipient out-of-band\n * // Recipient uses token to create delegated transaction\n * ```\n */\n async createTransactionToken(recipientEmail: string): Promise<string> {\n const response = await this.request<{ token: string }>('POST', '/token/create', {\n body: { recipientEmail },\n });\n return response.token;\n }\n\n /**\n * Create a delegated transaction using a pre-authorized token.\n *\n * Creates a transaction on behalf of the sender using their token.\n * This is typically used by services to charge users for usage.\n *\n * The token authenticates the request instead of Basic auth.\n *\n * @param senderEmail - Email of the sender who created the token\n * @param amount - Amount to transfer (must be > 0)\n * @param token - JWT token from sender's createTransactionToken()\n * @returns Transaction in PENDING status (createdBy=RECIPIENT)\n * @throws {AuthenticationError} If token is invalid or expired\n * @throws {ValidationError} If amount <= 0\n *\n * @example\n * ```typescript\n * // Recipient creates transaction using sender's token\n * const tx = await accounting.createDelegatedTransaction(\n * 'alice@example.com',\n * 5.0,\n * aliceToken\n * );\n *\n * // Recipient confirms the transaction\n * await accounting.confirmTransaction(tx.id);\n * ```\n */\n async createDelegatedTransaction(\n senderEmail: string,\n amount: number,\n token: string\n ): Promise<Transaction> {\n if (amount <= 0) {\n throw new ValidationError('Amount must be greater than 0');\n }\n\n const response = await this.requestWithToken<TransactionResponse>(\n 'POST',\n '/transactions',\n token,\n {\n body: {\n senderEmail,\n amount,\n },\n }\n );\n\n return parseTransaction(response);\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a new AccountingResource instance.\n *\n * @param options - Configuration options\n * @returns AccountingResource instance\n *\n * @example\n * ```typescript\n * const accounting = createAccountingResource({\n * url: process.env.ACCOUNTING_URL!,\n * email: process.env.ACCOUNTING_EMAIL!,\n * password: process.env.ACCOUNTING_PASSWORD!\n * });\n * ```\n */\nexport function createAccountingResource(options: AccountingResourceOptions): AccountingResource {\n return new AccountingResource(options);\n}\n","/**\n * Chat resource for RAG-augmented conversations via the Aggregator service.\n *\n * This resource handles satellite token authentication automatically:\n * - Resolves endpoints and extracts owner information\n * - Exchanges Hub access tokens for satellite tokens (one per unique owner)\n * - Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @example\n * // Simple chat completion\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n */\n\nimport type { EndpointPublic } from '../models/index.js';\nimport type {\n ChatMetadata,\n ChatOptions,\n ChatResponse,\n ChatStreamEvent,\n DocumentSource,\n EndpointRef,\n SourceInfo,\n SourceStatus,\n TokenUsage,\n} from '../models/chat.js';\nimport { SyftHubError } from '../errors.js';\nimport type { HubResource } from './hub.js';\nimport type { AuthResource } from './auth.js';\nimport { EndpointType } from '../models/index.js';\n\n/**\n * Error thrown when the aggregator service is unavailable or returns an error.\n */\nexport class AggregatorError extends SyftHubError {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'AggregatorError';\n }\n}\n\n/**\n * Error thrown when an endpoint cannot be resolved.\n */\nexport class EndpointResolutionError extends SyftHubError {\n constructor(\n message: string,\n public readonly endpointPath?: string\n ) {\n super(message);\n this.name = 'EndpointResolutionError';\n }\n}\n\n/**\n * Chat resource for RAG-augmented conversations via the Aggregator.\n *\n * This resource provides high-level chat functionality that:\n * - Queries data sources for relevant context (retrieval)\n * - Sends prompts with context to model endpoints (generation)\n * - Supports both synchronous and streaming responses\n */\nexport class ChatResource {\n constructor(\n private readonly hub: HubResource,\n private readonly auth: AuthResource,\n private readonly aggregatorUrl: string\n ) {}\n\n /**\n * Convert any endpoint format to EndpointRef with URL and owner info.\n * The ownerUsername is critical for satellite token authentication.\n */\n private async resolveEndpointRef(\n endpoint: string | EndpointRef | EndpointPublic,\n expectedType?: 'model' | 'data_source'\n ): Promise<EndpointRef> {\n // Already an EndpointRef\n if (this.isEndpointRef(endpoint)) {\n return endpoint;\n }\n\n // EndpointPublic object\n if (this.isEndpointPublic(endpoint)) {\n // Validate type if expected\n if (expectedType && endpoint.type !== expectedType) {\n throw new Error(\n `Expected endpoint type '${expectedType}', got '${endpoint.type}' for '${endpoint.slug}'`\n );\n }\n\n // Find first enabled connection with URL\n for (const conn of endpoint.connect) {\n if (conn.enabled && conn.config['url']) {\n return {\n url: String(conn.config['url']),\n slug: endpoint.slug,\n name: endpoint.name,\n tenantName: conn.config['tenant_name'] as string | undefined,\n ownerUsername: endpoint.ownerUsername, // Capture owner for satellite token\n };\n }\n }\n\n throw new EndpointResolutionError(\n `Endpoint '${endpoint.slug}' has no connection with URL configured`,\n `${endpoint.ownerUsername}/${endpoint.slug}`\n );\n }\n\n // String path format \"owner/slug\"\n if (typeof endpoint === 'string') {\n let ep: EndpointPublic;\n try {\n ep = await this.hub.get(endpoint);\n } catch (error) {\n throw new EndpointResolutionError(\n `Failed to fetch endpoint '${endpoint}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint\n );\n }\n return this.resolveEndpointRef(ep, expectedType);\n }\n\n throw new TypeError(`Cannot resolve endpoint from type: ${typeof endpoint}`);\n }\n\n /**\n * Collect unique owner usernames from all endpoints.\n * Used to determine which satellite tokens need to be fetched.\n */\n private collectUniqueOwners(modelRef: EndpointRef, dataSourceRefs: EndpointRef[]): string[] {\n const owners = new Set<string>();\n\n if (modelRef.ownerUsername) {\n owners.add(modelRef.ownerUsername);\n }\n\n for (const ds of dataSourceRefs) {\n if (ds.ownerUsername) {\n owners.add(ds.ownerUsername);\n }\n }\n\n return [...owners];\n }\n\n /**\n * Get satellite tokens for all unique endpoint owners.\n * Returns a map of owner username to satellite token.\n */\n private async getSatelliteTokensForOwners(owners: string[]): Promise<Record<string, string>> {\n if (owners.length === 0) {\n return {};\n }\n\n const tokenMap = await this.auth.getSatelliteTokens(owners);\n const result: Record<string, string> = {};\n\n for (const [owner, token] of tokenMap) {\n result[owner] = token;\n }\n\n return result;\n }\n\n /**\n * Get transaction tokens for all unique endpoint owners.\n * Returns a map of owner username to transaction token.\n *\n * Transaction tokens are used for billing - they authorize the endpoint\n * owner to charge the current user for usage.\n */\n private async getTransactionTokensForOwners(owners: string[]): Promise<Record<string, string>> {\n if (owners.length === 0) {\n return {};\n }\n\n const response = await this.auth.getTransactionTokens(owners);\n return response.tokens;\n }\n\n /**\n * Type guard for EndpointRef.\n */\n private isEndpointRef(value: unknown): value is EndpointRef {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'url' in value &&\n 'slug' in value &&\n typeof (value as EndpointRef).url === 'string' &&\n typeof (value as EndpointRef).slug === 'string'\n );\n }\n\n /**\n * Type guard for EndpointPublic.\n */\n private isEndpointPublic(value: unknown): value is EndpointPublic {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'connect' in value &&\n 'ownerUsername' in value &&\n Array.isArray((value as EndpointPublic).connect)\n );\n }\n\n /**\n * Build the request body for the aggregator.\n * Includes endpoint_tokens mapping for satellite token authentication.\n * Includes transaction_tokens mapping for billing authorization.\n * User identity is derived from satellite tokens, not passed in request body.\n */\n private buildRequestBody(\n prompt: string,\n modelRef: EndpointRef,\n dataSourceRefs: EndpointRef[],\n endpointTokens: Record<string, string>,\n transactionTokens: Record<string, string>,\n options: {\n topK?: number;\n maxTokens?: number;\n temperature?: number;\n similarityThreshold?: number;\n stream?: boolean;\n }\n ): Record<string, unknown> {\n return {\n prompt,\n model: {\n url: modelRef.url,\n slug: modelRef.slug,\n name: modelRef.name ?? '',\n tenant_name: modelRef.tenantName ?? null,\n owner_username: modelRef.ownerUsername ?? null,\n },\n data_sources: dataSourceRefs.map((ds) => ({\n url: ds.url,\n slug: ds.slug,\n name: ds.name ?? '',\n tenant_name: ds.tenantName ?? null,\n owner_username: ds.ownerUsername ?? null,\n })),\n endpoint_tokens: endpointTokens,\n transaction_tokens: transactionTokens,\n top_k: options.topK ?? 5,\n max_tokens: options.maxTokens ?? 1024,\n temperature: options.temperature ?? 0.7,\n similarity_threshold: options.similarityThreshold ?? 0.5,\n stream: options.stream ?? false,\n };\n }\n\n /**\n * Parse a SourceInfo from raw data.\n */\n private parseSourceInfo(data: Record<string, unknown>): SourceInfo {\n return {\n path: String(data['path'] ?? ''),\n documentsRetrieved: Number(data['documents_retrieved'] ?? 0),\n status: (data['status'] as SourceStatus) ?? 'success',\n errorMessage: data['error_message'] as string | undefined,\n };\n }\n\n /**\n * Parse ChatMetadata from raw data.\n */\n private parseMetadata(data: Record<string, unknown>): ChatMetadata {\n return {\n retrievalTimeMs: Number(data['retrieval_time_ms'] ?? 0),\n generationTimeMs: Number(data['generation_time_ms'] ?? 0),\n totalTimeMs: Number(data['total_time_ms'] ?? 0),\n };\n }\n\n /**\n * Parse TokenUsage from raw data.\n */\n private parseUsage(data: Record<string, unknown>): TokenUsage {\n return {\n promptTokens: Number(data['prompt_tokens'] ?? 0),\n completionTokens: Number(data['completion_tokens'] ?? 0),\n totalTokens: Number(data['total_tokens'] ?? 0),\n };\n }\n\n /**\n * Parse document sources from raw data.\n * The new format is a dict mapping document title to {slug, content}.\n */\n private parseDocumentSources(\n data: Record<string, unknown> | undefined\n ): Record<string, DocumentSource> {\n const sources: Record<string, DocumentSource> = {};\n if (!data || typeof data !== 'object') {\n return sources;\n }\n\n for (const [title, value] of Object.entries(data)) {\n if (value && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n sources[title] = {\n slug: String(source['slug'] ?? ''),\n content: String(source['content'] ?? ''),\n };\n }\n }\n return sources;\n }\n\n /**\n * Parse retrieval info (SourceInfo array) from raw data.\n */\n private parseRetrievalInfo(data: Record<string, unknown>[] | undefined): SourceInfo[] {\n const retrievalInfo: SourceInfo[] = [];\n if (!Array.isArray(data)) {\n return retrievalInfo;\n }\n\n for (const item of data) {\n retrievalInfo.push(this.parseSourceInfo(item));\n }\n return retrievalInfo;\n }\n\n /**\n * Send a chat request and get the complete response.\n *\n * This method automatically:\n * 1. Resolves endpoints and extracts owner information\n * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)\n * 3. Fetches transaction tokens for billing authorization\n * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @param options - Chat completion options\n * @returns ChatResponse with response text, sources, and metadata\n * @throws {EndpointResolutionError} If endpoint cannot be resolved\n * @throws {AggregatorError} If aggregator service fails\n */\n async complete(options: ChatOptions): Promise<ChatResponse> {\n const modelRef = await this.resolveEndpointRef(options.model, 'model');\n\n const dsRefs: EndpointRef[] = [];\n for (const ds of options.dataSources ?? []) {\n dsRefs.push(await this.resolveEndpointRef(ds, 'data_source'));\n }\n\n // Get satellite tokens for all unique endpoint owners\n const uniqueOwners = this.collectUniqueOwners(modelRef, dsRefs);\n const endpointTokens = await this.getSatelliteTokensForOwners(uniqueOwners);\n\n // Get transaction tokens for billing authorization\n const transactionTokens = await this.getTransactionTokensForOwners(uniqueOwners);\n\n const requestBody = this.buildRequestBody(\n options.prompt,\n modelRef,\n dsRefs,\n endpointTokens,\n transactionTokens,\n {\n topK: options.topK,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n similarityThreshold: options.similarityThreshold,\n stream: false,\n }\n );\n\n // Use custom aggregator URL if provided, otherwise use default\n const effectiveAggregatorUrl = (options.aggregatorUrl ?? this.aggregatorUrl).replace(\n /\\/+$/,\n ''\n );\n const url = `${effectiveAggregatorUrl}/chat`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['message'] ?? data['error'] ?? message);\n } catch {\n // Use default message\n }\n throw new AggregatorError(`Aggregator error: ${message}`, response.status);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n // Parse document sources (new format: dict of title -> {slug, content})\n const sourcesData = data['sources'] as Record<string, unknown> | undefined;\n const sources = this.parseDocumentSources(sourcesData);\n\n // Parse retrieval info (metadata about each data source retrieval)\n const retrievalInfoData = data['retrieval_info'] as Record<string, unknown>[] | undefined;\n const retrievalInfo = this.parseRetrievalInfo(retrievalInfoData);\n\n const metadataData = data['metadata'] as Record<string, unknown> | undefined;\n const metadata = this.parseMetadata(metadataData ?? {});\n\n // Parse usage if available\n const usageData = data['usage'] as Record<string, unknown> | undefined;\n const usage = usageData ? this.parseUsage(usageData) : undefined;\n\n return {\n response: String(data['response'] ?? ''),\n sources,\n retrievalInfo,\n metadata,\n usage,\n };\n }\n\n /**\n * Send a chat request and stream response events.\n *\n * This method automatically:\n * 1. Resolves endpoints and extracts owner information\n * 2. Exchanges Hub tokens for satellite tokens (one per unique owner)\n * 3. Fetches transaction tokens for billing authorization\n * 4. Sends tokens to the aggregator for forwarding to SyftAI-Space\n *\n * @param options - Chat completion options\n * @yields ChatStreamEvent objects as they arrive\n */\n async *stream(options: ChatOptions): AsyncGenerator<ChatStreamEvent, void, unknown> {\n const modelRef = await this.resolveEndpointRef(options.model, 'model');\n\n const dsRefs: EndpointRef[] = [];\n for (const ds of options.dataSources ?? []) {\n dsRefs.push(await this.resolveEndpointRef(ds, 'data_source'));\n }\n\n // Get satellite tokens for all unique endpoint owners\n const uniqueOwners = this.collectUniqueOwners(modelRef, dsRefs);\n const endpointTokens = await this.getSatelliteTokensForOwners(uniqueOwners);\n\n // Get transaction tokens for billing authorization\n const transactionTokens = await this.getTransactionTokensForOwners(uniqueOwners);\n\n const requestBody = this.buildRequestBody(\n options.prompt,\n modelRef,\n dsRefs,\n endpointTokens,\n transactionTokens,\n {\n topK: options.topK,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n similarityThreshold: options.similarityThreshold,\n stream: true,\n }\n );\n\n // Use custom aggregator URL if provided, otherwise use default\n const effectiveAggregatorUrl = (options.aggregatorUrl ?? this.aggregatorUrl).replace(\n /\\/+$/,\n ''\n );\n const url = `${effectiveAggregatorUrl}/chat/stream`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n },\n body: JSON.stringify(requestBody),\n signal: options.signal,\n });\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['message'] ?? data['error'] ?? message);\n } catch {\n // Use default message\n }\n throw new AggregatorError(`Aggregator error: ${message}`, response.status);\n }\n\n if (!response.body) {\n throw new AggregatorError('No response body from aggregator');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let currentEvent: string | null = null;\n let currentData = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (!trimmedLine) {\n // Empty line = end of event\n if (currentEvent && currentData) {\n try {\n const data = JSON.parse(currentData) as Record<string, unknown>;\n const event = this.parseSSEEvent(currentEvent, data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed data\n }\n }\n currentEvent = null;\n currentData = '';\n continue;\n }\n\n if (trimmedLine.startsWith('event:')) {\n currentEvent = trimmedLine.slice(6).trim();\n } else if (trimmedLine.startsWith('data:')) {\n currentData = trimmedLine.slice(5).trim();\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n /**\n * Parse an SSE event into a typed event object.\n */\n private parseSSEEvent(eventType: string, data: Record<string, unknown>): ChatStreamEvent | null {\n switch (eventType) {\n case 'retrieval_start':\n return {\n type: 'retrieval_start',\n sourceCount: Number(data['sources'] ?? 0),\n };\n\n case 'source_complete':\n return {\n type: 'source_complete',\n path: String(data['path'] ?? ''),\n status: String(data['status'] ?? ''),\n documentsRetrieved: Number(data['documents'] ?? 0),\n };\n\n case 'retrieval_complete':\n return {\n type: 'retrieval_complete',\n totalDocuments: Number(data['total_documents'] ?? 0),\n timeMs: Number(data['time_ms'] ?? 0),\n };\n\n case 'generation_start':\n return { type: 'generation_start' };\n\n case 'token':\n return {\n type: 'token',\n content: String(data['content'] ?? ''),\n };\n\n case 'done': {\n // Parse document sources (new format: dict of title -> {slug, content})\n const sourcesData = data['sources'] as Record<string, unknown> | undefined;\n const sources = this.parseDocumentSources(sourcesData);\n\n // Parse retrieval info (metadata about each data source retrieval)\n const retrievalInfoData = data['retrieval_info'] as Record<string, unknown>[] | undefined;\n const retrievalInfo = this.parseRetrievalInfo(retrievalInfoData);\n\n const metadataData = data['metadata'] as Record<string, unknown> | undefined;\n const metadata = this.parseMetadata(metadataData ?? {});\n\n // Parse usage if available (only from non-streaming mode)\n const usageData = data['usage'] as Record<string, unknown> | undefined;\n const usage = usageData ? this.parseUsage(usageData) : undefined;\n\n return { type: 'done', sources, retrievalInfo, metadata, usage };\n }\n\n case 'error':\n return {\n type: 'error',\n message: String(data['message'] ?? 'Unknown error'),\n };\n\n default:\n return {\n type: 'error',\n message: `Unknown event type: ${eventType}`,\n };\n }\n }\n\n /**\n * Get model endpoints that have connection URLs configured.\n *\n * @param limit - Maximum number of results (default: 20)\n * @returns Array of EndpointPublic objects for models with URLs\n */\n async getAvailableModels(limit = 20): Promise<EndpointPublic[]> {\n const results: EndpointPublic[] = [];\n\n for await (const endpoint of this.hub.browse()) {\n if (results.length >= limit) break;\n\n if (endpoint.type !== EndpointType.MODEL) continue;\n\n const hasUrl = endpoint.connect.some((conn) => conn.enabled && conn.config['url']);\n\n if (hasUrl) {\n results.push(endpoint);\n }\n }\n\n return results;\n }\n\n /**\n * Get data source endpoints that have connection URLs configured.\n *\n * @param limit - Maximum number of results (default: 20)\n * @returns Array of EndpointPublic objects for data sources with URLs\n */\n async getAvailableDataSources(limit = 20): Promise<EndpointPublic[]> {\n const results: EndpointPublic[] = [];\n\n for await (const endpoint of this.hub.browse()) {\n if (results.length >= limit) break;\n\n if (endpoint.type !== EndpointType.DATA_SOURCE) continue;\n\n const hasUrl = endpoint.connect.some((conn) => conn.enabled && conn.config['url']);\n\n if (hasUrl) {\n results.push(endpoint);\n }\n }\n\n return results;\n }\n}\n","/**\n * SyftAI-Space resource for direct endpoint queries.\n *\n * This module provides low-level access to SyftAI-Space endpoints, allowing\n * users to build custom RAG pipelines or bypass the aggregator service.\n *\n * @example\n * // Query a data source directly\n * const docs = await client.syftai.queryDataSource({\n * endpoint: { url: 'http://syftai:8080', slug: 'docs' },\n * query: 'What is machine learning?',\n * userEmail: 'alice@example.com',\n * });\n *\n * // Query a model directly\n * const response = await client.syftai.queryModel({\n * endpoint: { url: 'http://syftai:8080', slug: 'gpt-model' },\n * messages: [\n * { role: 'system', content: 'You are a helpful assistant.' },\n * { role: 'user', content: 'Hello!' },\n * ],\n * userEmail: 'alice@example.com',\n * });\n */\n\nimport type { Document, QueryDataSourceOptions, QueryModelOptions } from '../models/chat.js';\nimport { SyftHubError } from '../errors.js';\n\n/**\n * Error thrown when data source retrieval fails.\n */\nexport class RetrievalError extends SyftHubError {\n constructor(\n message: string,\n public readonly sourcePath?: string,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'RetrievalError';\n }\n}\n\n/**\n * Error thrown when model generation fails.\n */\nexport class GenerationError extends SyftHubError {\n constructor(\n message: string,\n public readonly modelSlug?: string,\n public readonly detail?: unknown\n ) {\n super(message);\n this.name = 'GenerationError';\n }\n}\n\n/**\n * Low-level resource for direct SyftAI-Space endpoint queries.\n *\n * This resource provides direct access to SyftAI-Space endpoints without\n * going through the aggregator. Use this when you need:\n * - Custom RAG pipelines with specific retrieval strategies\n * - Direct model queries without data source context\n * - Fine-grained control over the query process\n *\n * For most use cases, prefer the higher-level `client.chat` API instead.\n */\nexport class SyftAIResource {\n // No dependencies - uses direct fetch to SyftAI-Space endpoints\n\n /**\n * Build headers for SyftAI-Space request.\n */\n private buildHeaders(tenantName?: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n if (tenantName) {\n headers['X-Tenant-Name'] = tenantName;\n }\n return headers;\n }\n\n /**\n * Query a data source endpoint directly.\n *\n * @param options - Query options\n * @returns Array of Document objects\n * @throws {RetrievalError} If the query fails\n */\n async queryDataSource(options: QueryDataSourceOptions): Promise<Document[]> {\n const { endpoint, query, userEmail, topK = 5, similarityThreshold = 0.5 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: query, // SyftAI-Space expects \"messages\" for query text\n limit: topK,\n similarity_threshold: similarityThreshold,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: this.buildHeaders(endpoint.tenantName),\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new RetrievalError(\n `Failed to connect to data source '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new RetrievalError(`Data source query failed: ${message}`, endpoint.slug);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const documents: Document[] = [];\n\n const docsData = data['documents'] as Record<string, unknown>[] | undefined;\n if (Array.isArray(docsData)) {\n for (const doc of docsData) {\n documents.push({\n content: String(doc['content'] ?? ''),\n score: Number(doc['score'] ?? 0),\n metadata: (doc['metadata'] as Record<string, unknown>) ?? {},\n });\n }\n }\n\n return documents;\n }\n\n /**\n * Query a model endpoint directly.\n *\n * @param options - Query options\n * @returns Generated response text\n * @throws {GenerationError} If generation fails\n */\n async queryModel(options: QueryModelOptions): Promise<string> {\n const { endpoint, messages, userEmail, maxTokens = 1024, temperature = 0.7 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n })),\n max_tokens: maxTokens,\n temperature,\n stream: false,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: this.buildHeaders(endpoint.tenantName),\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new GenerationError(\n `Failed to connect to model '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new GenerationError(`Model query failed: ${message}`, endpoint.slug);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n const messageData = data['message'] as Record<string, unknown> | undefined;\n return String(messageData?.['content'] ?? '');\n }\n\n /**\n * Stream a model response directly.\n *\n * @param options - Query options\n * @yields Response text chunks as they arrive\n * @throws {GenerationError} If generation fails\n */\n async *queryModelStream(options: QueryModelOptions): AsyncGenerator<string, void, unknown> {\n const { endpoint, messages, userEmail, maxTokens = 1024, temperature = 0.7 } = options;\n\n const url = `${endpoint.url.replace(/\\/$/, '')}/api/v1/endpoints/${endpoint.slug}/query`;\n\n const requestBody = {\n user_email: userEmail,\n messages: messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n })),\n max_tokens: maxTokens,\n temperature,\n stream: true,\n };\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n ...this.buildHeaders(endpoint.tenantName),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify(requestBody),\n });\n } catch (error) {\n throw new GenerationError(\n `Failed to connect to model '${endpoint.slug}': ${error instanceof Error ? error.message : String(error)}`,\n endpoint.slug,\n error\n );\n }\n\n if (!response.ok) {\n let message = `HTTP ${response.status}`;\n try {\n const data = (await response.json()) as Record<string, unknown>;\n message = String(data['detail'] ?? data['message'] ?? message);\n } catch {\n // Use default message\n }\n throw new GenerationError(`Model stream failed: ${message}`, endpoint.slug);\n }\n\n if (!response.body) {\n throw new GenerationError('No response body from model', endpoint.slug);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmedLine = line.trim();\n\n if (!trimmedLine || trimmedLine.startsWith('event:')) {\n continue;\n }\n\n if (trimmedLine.startsWith('data:')) {\n const dataStr = trimmedLine.slice(5).trim();\n if (dataStr === '[DONE]') {\n return;\n }\n\n try {\n const data = JSON.parse(dataStr) as Record<string, unknown>;\n\n // Extract content from various response formats\n if (typeof data['content'] === 'string') {\n yield data['content'];\n } else if (Array.isArray(data['choices'])) {\n // OpenAI-style response\n for (const choice of data['choices'] as Record<string, unknown>[]) {\n const delta = choice['delta'] as Record<string, unknown> | undefined;\n if (delta && typeof delta['content'] === 'string') {\n yield delta['content'];\n }\n }\n }\n } catch {\n // Skip malformed data\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","/**\n * SyftHub TypeScript SDK\n *\n * A TypeScript client library for the SyftHub API.\n *\n * @example\n * import { SyftHubClient, EndpointType, Visibility } from '@syfthub/sdk';\n *\n * const client = new SyftHubClient({ baseUrl: 'https://hub.syft.com' });\n *\n * // Login\n * const user = await client.auth.login('alice', 'password');\n *\n * // Create an endpoint\n * const endpoint = await client.myEndpoints.create({\n * name: 'My Model',\n * type: EndpointType.MODEL,\n * visibility: Visibility.PUBLIC,\n * });\n *\n * // Browse the hub\n * for await (const ep of client.hub.browse()) {\n * console.log(ep.name);\n * }\n *\n * // Chat with RAG via aggregator\n * const response = await client.chat.complete({\n * prompt: 'What is machine learning?',\n * model: 'alice/gpt-model',\n * dataSources: ['bob/ml-docs'],\n * });\n * console.log(response.response);\n *\n * // Streaming chat\n * for await (const event of client.chat.stream(options)) {\n * if (event.type === 'token') {\n * process.stdout.write(event.content);\n * }\n * }\n *\n * @packageDocumentation\n */\n\n// Main client\nexport { SyftHubClient } from './client.js';\nexport type { SyftHubClientOptions } from './client.js';\n\n// HTTP types (for advanced usage)\nexport type { AuthTokens } from './http.js';\n\n// Errors\nexport {\n SyftHubError,\n APIError,\n AuthenticationError,\n AuthorizationError,\n NotFoundError,\n ValidationError,\n NetworkError,\n ConfigurationError,\n // User registration errors\n UserAlreadyExistsError,\n // Accounting-related errors\n AccountingAccountExistsError,\n InvalidAccountingPasswordError,\n AccountingServiceUnavailableError,\n} from './errors.js';\n\n// Chat-specific errors\nexport { AggregatorError, EndpointResolutionError } from './resources/chat.js';\nexport { RetrievalError, GenerationError } from './resources/syftai.js';\n\n// Pagination\nexport { PageIterator } from './pagination.js';\nexport type { PageFetcher } from './pagination.js';\n\n// Models - Enums and constants\nexport {\n Visibility,\n EndpointType,\n UserRole,\n OrganizationRole,\n // Accounting enums\n TransactionStatus,\n CreatorType,\n} from './models/index.js';\n\n// Models - Types\nexport type {\n // User types\n User,\n UserRegisterInput,\n UserUpdateInput,\n PasswordChangeInput,\n AccountingCredentials,\n // Endpoint types\n Policy,\n Connection,\n Endpoint,\n EndpointPublic,\n EndpointCreateInput,\n EndpointUpdateInput,\n SyncEndpointsResponse,\n // Accounting types\n AccountingUser,\n Transaction,\n CreateTransactionInput,\n CreateDelegatedTransactionInput,\n UpdatePasswordInput,\n TransactionResponse,\n TransactionTokenResponse,\n // Chat types\n EndpointRef,\n Document,\n SourceStatus,\n SourceInfo,\n ChatMetadata,\n ChatResponse,\n Message,\n ChatOptions,\n QueryDataSourceOptions,\n QueryModelOptions,\n // Chat streaming events\n ChatStreamEvent,\n RetrievalStartEvent,\n SourceCompleteEvent,\n RetrievalCompleteEvent,\n GenerationStartEvent,\n TokenEvent,\n DoneEvent,\n ErrorEvent,\n} from './models/index.js';\n\n// Model helpers\nexport {\n getEndpointOwnerType,\n getEndpointPublicPath,\n // Accounting helpers\n parseTransaction,\n isTransactionPending,\n isTransactionCompleted,\n isTransactionCancelled,\n} from './models/index.js';\n\n// Accounting Resource (standalone client for external accounting service)\nexport { AccountingResource, createAccountingResource } from './resources/accounting.js';\nexport type { AccountingResourceOptions, TransactionsOptions } from './resources/accounting.js';\n\n// Chat Resource (for type hints)\nexport { ChatResource } from './resources/chat.js';\n\n// SyftAI Resource (for type hints)\nexport { SyftAIResource } from './resources/syftai.js';\n\n// Resource option types (for type-safe usage)\nexport type { ListEndpointsOptions } from './resources/my-endpoints.js';\nexport type { BrowseOptions, TrendingOptions } from './resources/hub.js';\n"]}
|