import { SpecifyDesignTokenFormat } from '@specifyapp/specify-design-token-format'; import { SDKTelemetry } from '../telemetry/provider.js'; import { HttpResources } from './internals/HttpResources.js'; import { Authentication } from './internals/Authentication.js'; import { SDTFClient } from './SDTFClient.js'; /** * The main Specify client to interact with the Specify API. */ export class SpecifyClient { readonly #authentication: Authentication; readonly #http: HttpResources; constructor() { this.#authentication = new Authentication(); this.#http = new HttpResources(this.#authentication); } /** * Returns whether the client is authenticated or not. */ get isAuthenticated() { return this.#authentication.isAuthenticated; } /** * Authenticates the client with a Personal Access Token. Can be generated at https://specifyapp.com/user/personal-access-tokens * @param personalAccessToken */ async authenticate(personalAccessToken: string) { await this.#http.login(personalAccessToken); const { currentUser, currentOrganization } = this.#authentication.credentials; new SDKTelemetry({ personalAccessToken, userId: currentUser.id, userEmail: currentUser.email, organizationId: currentOrganization.id, organizationNamespace: currentOrganization.namespace, }).track('SDK User Logged In', {}); } /** * Returns the current user if authenticated. */ whoAmI() { try { const { currentUser } = this.#authentication.credentials; return currentUser; } catch (error) { return null; } } /** * Logs out the current user. */ logout() { this.#authentication.reset(); } /** * Returns the repositories list of the current organization. */ async getRepositories() { const { payload } = await this.#http.getMyRepositories(); return payload.filter(repo => repo.version === 2); } /** * Returns a SDTFClient instance to work with the SDTF token tree of the repository. * * @param repositoryName - The name of the repository. */ async getSDTFClientByRepositoryName(repositoryName: string) { const { payload: repositoryInformation } = await this.#http.getMyRepositoryByName( repositoryName, ); const tokenTree = await this.#http.getMyRepositoryTokenTreeByName(repositoryName); new SDKTelemetry({ repositoryId: repositoryInformation.id, }).track('SDK User Fetched Repository', { repositoryName: repositoryInformation.name, }); return new SDTFClient(repositoryInformation, tokenTree); } /** * Returns a SDTFClient instance to work with an empty SDTF token tree. * @param tokenTree */ loadSDTFClient(tokenTree: SpecifyDesignTokenFormat) { return new SDTFClient( { id: 'local', name: 'local', version: 2, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }, tokenTree, ); } }