UNPKG

@gnosticdev/highlevel-sdk

Version:
569 lines (561 loc) 22.9 kB
import { Client, ClientOptions } from 'openapi-fetch'; import { paths as paths$l } from './types/blogs.cjs'; import { paths as paths$6 } from './types/businesses.cjs'; import { paths as paths$p } from './types/calendars.cjs'; import { paths as paths$5 } from './types/campaigns.cjs'; import { paths as paths$m } from './types/companies.cjs'; import { paths as paths$n } from './types/contacts.cjs'; import { paths as paths$7 } from './types/conversations.cjs'; import { paths as paths$9 } from './types/courses.cjs'; import { paths as paths$3 } from './types/custom-menus.cjs'; import { paths as paths$d } from './types/email-isv.cjs'; import { paths as paths$b } from './types/emails.cjs'; import { paths as paths$o } from './types/forms.cjs'; import { paths as paths$i } from './types/funnels.cjs'; import { paths as paths$1 } from './types/invoices.cjs'; import { paths as paths$k } from './types/links.cjs'; import { paths as paths$j } from './types/locations.cjs'; import { paths as paths$q } from './types/medias.cjs'; import { paths as paths$4 } from './types/opportunities.cjs'; import { paths as paths$c } from './types/payments.cjs'; import { paths as paths$8 } from './types/products.cjs'; import { paths as paths$g } from './types/saas-api.cjs'; import { paths as paths$f } from './types/snapshots.cjs'; import { paths as paths$2 } from './types/social-media-posting.cjs'; import { paths as paths$a } from './types/surveys.cjs'; import { paths as paths$h } from './types/users.cjs'; import { paths as paths$e } from './types/workflows.cjs'; import { A as AccessType, S as ScopeLiterals, H as HighLevelScopes } from './type-utils-BG2wp-D1.cjs'; import { components, operations, paths } from './types/oauth.cjs'; import { Client as Client$1 } from 'openapi-fetch/src/index.js'; type AccessTokenRequest = operations['get-access-token']['requestBody']['content']['application/x-www-form-urlencoded'] & { grant_type: 'authorization_code'; }; type RefreshTokenRequest = operations['get-access-token']['requestBody']['content']['application/x-www-form-urlencoded']; /** * Search Params appended to the auth url * @see https://highlevel.stoplight.io/docs/integrations/a04191c0fabf9-authorization */ type AuthUrlParams = { response_type: 'code'; redirect_uri: string; client_id: string; scope: string; }; /** * The params used to generate a new access token, or refresh an existing one */ type TokenParams = AuthCodeParams | RefreshTokenRequest; /** * The params used to generate a new access token */ type AuthCodeParams<TGrantType extends AccessTokenRequest['grant_type'] = 'authorization_code'> = { [K in keyof Pick<AccessTokenRequest, 'client_id' | 'client_secret' | 'refresh_token'>]: AccessTokenRequest[K]; } & { grant_type: TGrantType; user_type: 'Company' | 'Location'; }; /** * The params used to generate a new location access token */ type LocationTokenParams = components['schemas']['GetLocationAccessCodeBodyDto']; /** * The response from the server when generating a new location access token */ type LocationTokenResponse = components['schemas']['GetLocationAccessTokenSuccessfulResponseDto']; /** * The params used to search for installed locations */ type SearchInstalledLocationParams = { query: operations['get-installed-location']['parameters']['query']; }; type GetInstalledLocationResponse = components['schemas']['GetInstalledLocationsSuccessfulResponseDto']; /** * The response from the server when generating a new access token */ type AccessTokenResponse = Required<components['schemas']['GetAccessCodeSuccessfulResponseDto']>; /** * The data stored in the token response. * **NOTE** `expiresAt` is a calculated value based on the `expires_in` value from the token response. */ type TokenData = AccessTokenResponse & { expiresAt: number; }; /** * If providing your own auth provider, you can implement this interface and pass it into the `createHighLevelClient` function. */ interface OAuthClientInterface<T extends AccessType> { /** * The time (in seconds) when the access token expires. Default expiry is 24 hours from the time it was generated. */ expiresAt: number | undefined; /** * Auto generates the authorization url for your app. * @see https://highlevel.stoplight.io/docs/integrations/a04191c0fabf9-authorization * @example * ```ts https://marketplace.gohighlevel.com/oauth/chooselocation?response_type=code&redirect_uri=https://myapp.com/oauth/callback/gohighlevel&client_id=CLIENT_ID&scope=conversations/message.readonly conversations/message.write * ``` */ getAuthorizationUrl(): string; /** * The token response from the server. */ tokenData: TokenData | undefined; /** * The scopes needed for your app. These must be added to your app in the marketplace. */ readonly scopes: ScopeLiterals<T> | (string & {}); /** * Gets the current access token, or generates a new one if needed. * @param authCode - The authorization code received from the OAuth provider. * @returns The access token. */ getAccessToken(authCode?: string): Promise<string | null>; /** * Get all locations under your agency that have installed your app * @param query - search for installed locations using any of these properties * @returns * */ getInstalledLocations(query: SearchInstalledLocationParams['query']): Promise<GetInstalledLocationResponse>; /** * generate a location AccessToken from Agency AccessToken * @param companyId - your agency id * @param locationId - The locationId is the locationId of the location you want to get a token for */ generateLocationToken(params: LocationTokenParams): Promise<LocationTokenResponse>; /** * Exchange an authorization code for an access_token. * * To refresh a token use the `refreshAccessToken` method * @param authCode - Parameters required to generate a new token. * @returns The token response from the server. * */ exchangeToken(authCode: string): Promise<AccessTokenResponse>; /** * Refreshes the current access token. * @returns The token response from the server. */ refreshAccessToken(): Promise<AccessTokenResponse>; } /** * HighLevelClient with built in OAuth methods. * * To create an instance, use the `createHighLevelClient` function from the main client. * * @see {@link createHighLevelClient} * @example * ```ts * const client = createAuth('oauth', { * clientId: 'your-client-id', * clientSecret: 'your-client-secret', * redirectUri: 'http://localhost:3000/callback', * accessType: 'Sub-Account', * scopes: ['contacts.readonly'] * }) * ``` * @internal */ declare class HighLevelClientWithOAuth<T extends AccessType> extends HighLevelClient<T, OauthClientImpl<T>, undefined> { oauth: OauthClientImpl<T>; constructor(oauthConfig: HighLevelOauthConfig<T>, clientConfig?: HighLevelClientConfig); } /** * The configuration for the HighLevel API client with OAuth. */ type HighLevelOauthConfig<T extends AccessType> = { /** * base url for each API endpoint. no need to change unless you are proxying requests. * @default 'https://services.leadconnectorhq.com' */ baseUrl?: string; /** * client_id from app settings in marketplace. * * **Important:** Your client_id and client_secret must have been created after your scopes were added to your app. * @default process.env.HIGHLEVEL_CLIENT_ID * @see https://marketplace.gohighlevel.com/apps */ clientId: string; /** * client_secret from app settings in marketplace. * * **Important:** Your client_id and client_secret must have been created after your scopes were added to your app. * @default process.env.HIGHLEVEL_CLIENT_SECRET * @see https://marketplace.gohighlevel.com/apps */ clientSecret: string; /** * The access level of your app as defined in the ghl marketplace. * * - `Sub-Account` is same as **Location**. * - `Company` is same as **Agency** */ accessType: T; /** * the url to redirect to after the user has authorized the app * - use `client.getAuthorizationUrl()` to generate the the full auth url including your redirectUri, clientId, and scopes */ redirectUri: string; /** * Scopes needed for your app. These must be added to your app in the marketplace. * * Available scopes will change depending on your app type. * @see https://marketplace.gohighlevel.com/apps */ scopes: HighLevelScopes<T>; /** * base url used by the Oauth client to build the redirect uri. no need to change unless you are proxying requests. * @default `https://marketplace.leadconnectorhq.com/oauth/chooselocation` */ baseAuthUrl?: string; /** * the auth code from the redirect uri * * use `client.getAuthCode()` to get the auth code from the query params * @see https://highlevel.stoplight.io/docs/integrations/ */ authCode?: string; /** * Store the token data in your database or cache * @default `(tokenData) => Promise.resolve(tokenData)` */ storageFunction?: (tokenData: TokenData) => Promise<TokenData>; }; /** * Default `openapi-fetch` client for HighLevel OAuth 2.0 endpoints. */ type DefaultOauthClient = Client<paths>; /** * This client has built in methods for generating, refreshing, and storing tokens. * You can extend this class to implement your own methods. * @see https://highlevel.stoplight.io/docs/integrations/ */ declare class OauthClientImpl<T extends AccessType> implements OAuthClientInterface<T> { #private; private _accessToken; private _refreshToken; /** * Type of user that is accessing the API. * * Only used for generating tokens, similar to `accessType` but uses `Location` (Sub-Account) or `Company` (Agency) */ private readonly userType; /** * Underlying oauth client created by `createClient` method from `openapi-fetch` * * Most likely do not need to use this unless special use case. */ _client: DefaultOauthClient; private _expiresAt; readonly scopes: ScopeLiterals<T> | (string & {}); readonly config: HighLevelOauthConfig<T>; private readonly baseUrl; private readonly baseOauthUrl; tokenData: TokenData | undefined; storeTokenFn: (tokenData: TokenData) => Promise<TokenData>; /** * creates a new oauth client for use with the HighLevel API * @constructor * @param config - configuration for your app */ constructor(config: HighLevelOauthConfig<T>); /** * The time (in seconds) when the access token expires. */ get expiresAt(): number | undefined; /** * Update the stored token data with the provided token data. * @param updatedTokenData - The token data to update. */ updateTokenData(updatedTokenData: Partial<TokenData>): void; /** * generates the authorization url for your app using the baseAuthUrl, clientId, redirectUri, and scopes. * @see https://highlevel.stoplight.io/docs/integrations/a04191c0fabf9-authorization * @example * ```ts https://marketplace.leadconnectorhq.com/oauth/chooselocation?response_type=code&redirect_uri=https://myapp.com/oauth/callback/gohighlevel&client_id=CLIENT_ID&scope=conversations/message.readonly conversations/message.write * ``` */ getAuthorizationUrl(): string; /** * Stores everything from the Token response including the accessToken, refreshToken, locationID, and adds the expiresAt time (in ms). * **NOTE**: You can add a `storageFunction` to the config to store the token data in your database or cache. * @param tokenData - the token response from the server * @returns the token data with the `expiresAt` time added */ storeTokenData(tokenData: TokenData): Promise<TokenData>; /** * Check if the token is expired or if we need to refresh it * @returns true if the token is expired or if we need to refresh it */ private isTokenExpired; /** * Returns a valid access token by either refreshing the token or exchanging the auth code for a new token. * * Also stores the token via the `storeTokenData` if provided. * @param authCode - The authorization code received from the OAuth provider. * @throws {Error} - If no token response is received or if no auth code or refresh token is provided. * @returns The access token. */ getAccessToken(authCode?: string): Promise<string | null>; /** * Generates a new access token using the provided authorization code. \ * **NOTE**: This method does not save the token data to the client. * To store the token: * - `storeTokenData` - saves the token data. * - `getAccessToken` - fetches and stores the token data. * @param authCode - Parameters required to generate a new token. * @returns The token response from the server. */ exchangeToken(authCode: string): Promise<TokenData>; /** * Refreshes the current access token. * **NOTE**: This method does not save the token data to the client. * To store the token: * - `storeTokenData` - saves the token data. * - `getAccessToken` - fetches and stores the token data. * @returns The token response from the server. */ refreshAccessToken(): Promise<TokenData>; /** * generate a location AccessToken from Agency AccessToken * @param companyId - your agency id * @param locationId - The locationId is the locationId of the location you want to get a token for */ generateLocationToken({ companyId, locationId }: LocationTokenParams): Promise<{ access_token?: string; expires_in?: number; locationId?: string; planId?: string; scope?: string; token_type?: string; userId: string; }>; /** * Get all locations under your agency that have installed your app * @param query - search for installed locations using any of these properties * @param appId - the appId of your app * @param companyId - the companyId of your agency */ getInstalledLocations(query: SearchInstalledLocationParams['query']): Promise<{ count?: number; installToFutureLocations?: boolean; locations?: components["schemas"]["InstalledLocationSchema"][]; }>; } type HTTPMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options' | 'trace'; type RemoveAuthHeaders<T> = T extends { parameters: { header: infer H; }; } ? H extends { Authorization: string; Version: string; } ? { parameters: { header?: Partial<Pick<H, 'Authorization' | 'Version'>> & Omit<H, 'Authorization' | 'Version'>; } & Omit<T['parameters'], 'header'>; } & Omit<T, 'parameters'> : T : never; /** * An `openapi-fetch` client with optional Authentication headers. * * @see {@link createClientWithAuth} */ type OptionalAuthParamsClient<T> = T extends Client$1<infer Paths> ? Client$1<{ [P in keyof Paths]: { [M in keyof Paths[P]]: M extends 'parameters' ? Paths[P][M] : M extends HTTPMethod ? RemoveAuthHeaders<Paths[P][M]> : Paths[P][M]; }; }> : never; interface ClientWithAuth<TPaths extends {}> extends OptionalAuthParamsClient<Client$1<TPaths>> { } /** * Authentication headers for the HighLevel v2 API. */ type AuthHeaders = { /** * The token to use for authentication. * * @example `Bearer 1234567890` */ Authorization: string; /** * The version of the API to use. * * @default '2021-07-28' */ Version: '2021-07-28'; }; interface HighLevelClientInterface<T extends AccessType, TOAuth extends DefaultOauthClient | OauthClientImpl<T>> { /** * Exposed config object for convenience. */ _clientConfig: HighLevelClientConfig; oauth: TOAuth; invoices: Client<paths$1> | ClientWithAuth<paths$1>; socialMediaPosting: Client<paths$2> | ClientWithAuth<paths$2>; customMenus: Client<paths$3> | ClientWithAuth<paths$3>; opportunities: Client<paths$4> | ClientWithAuth<paths$4>; campaigns: Client<paths$5> | ClientWithAuth<paths$5>; businesses: Client<paths$6> | ClientWithAuth<paths$6>; conversations: Client<paths$7> | ClientWithAuth<paths$7>; products: Client<paths$8> | ClientWithAuth<paths$8>; courses: Client<paths$9> | ClientWithAuth<paths$9>; surveys: Client<paths$a> | ClientWithAuth<paths$a>; emails: Client<paths$b> | ClientWithAuth<paths$b>; payments: Client<paths$c> | ClientWithAuth<paths$c>; emailIsv: Client<paths$d> | ClientWithAuth<paths$d>; workflows: Client<paths$e> | ClientWithAuth<paths$e>; snapshots: Client<paths$f> | ClientWithAuth<paths$f>; saasApi: Client<paths$g> | ClientWithAuth<paths$g>; users: Client<paths$h> | ClientWithAuth<paths$h>; funnels: Client<paths$i> | ClientWithAuth<paths$i>; locations: Client<paths$j> | ClientWithAuth<paths$j>; links: Client<paths$k> | ClientWithAuth<paths$k>; blogs: Client<paths$l> | ClientWithAuth<paths$l>; companies: Client<paths$m> | ClientWithAuth<paths$m>; contacts: Client<paths$n> | ClientWithAuth<paths$n>; forms: Client<paths$o> | ClientWithAuth<paths$o>; calendars: Client<paths$p> | ClientWithAuth<paths$p>; medias: Client<paths$q> | ClientWithAuth<paths$q>; } /** * Configuration used on every request made by the HighLevelClient. */ interface HighLevelClientConfig extends ClientOptions { /** * base url for each API endpoint. no need to change unless you are proxying requests. * @default 'https://services.leadconnectorhq.com' */ baseUrl?: string; } /** * Default client for HighLevel API endpoints. * * @remarks use the `createHighLevelClient` function to create an instance of this client without handling generic types. * * @see {@link createHighLevelClient} * * @example * ```ts * const client = new HighLevelClient({}, {headers: {Authorization: 'Bearer 1234567890'}}) * const locations = client.locations.GET('/locations/search', {query: {name: 'John Doe'}}) * ``` */ declare class HighLevelClient< /** * access level for the client. `Sub-Account` or `Agency` */ T extends AccessType, /** * oauth client implementation. */ TOauth extends DefaultOauthClient | OauthClientImpl<T> = DefaultOauthClient, /** * headers for the client. */ THeaders extends AuthHeaders | undefined = undefined> implements HighLevelClientInterface<T, TOauth> { private authHeaders?; /** * oauth client implementation. */ oauth: TOauth; /** * businesses client implementation. */ businesses: THeaders extends undefined ? Client<paths$6> : ClientWithAuth<paths$6>; blogs: Client<paths$l, `${string}/${string}`> | ClientWithAuth<paths$l>; customMenus: Client<paths$3, `${string}/${string}`> | ClientWithAuth<paths$3>; emails: Client<paths$b, `${string}/${string}`> | ClientWithAuth<paths$b>; emailIsv: Client<paths$d, `${string}/${string}`> | ClientWithAuth<paths$d>; /** * invoices client implementation. */ invoices: THeaders extends undefined ? Client<paths$1> : ClientWithAuth<paths$1>; /** * opportunities client implementation. */ opportunities: THeaders extends undefined ? Client<paths$4> : ClientWithAuth<paths$4>; /** * campaigns client implementation. */ campaigns: THeaders extends undefined ? Client<paths$5> : ClientWithAuth<paths$5>; /** * conversations client implementation. */ conversations: THeaders extends undefined ? Client<paths$7> : ClientWithAuth<paths$7>; /** * products client implementation. */ products: THeaders extends undefined ? Client<paths$8> : ClientWithAuth<paths$8>; /** * courses client implementation. */ courses: THeaders extends undefined ? Client<paths$9> : ClientWithAuth<paths$9>; /** * surveys client implementation. */ surveys: THeaders extends undefined ? Client<paths$a> : ClientWithAuth<paths$a>; /** * payments client implementation. */ payments: THeaders extends undefined ? Client<paths$c> : ClientWithAuth<paths$c>; /** * workflows client implementation. */ workflows: THeaders extends undefined ? Client<paths$e> : ClientWithAuth<paths$e>; /** * snapshots client implementation. */ snapshots: THeaders extends undefined ? Client<paths$f> : ClientWithAuth<paths$f>; /** * saasApi client implementation. */ saasApi: THeaders extends undefined ? Client<paths$g> : ClientWithAuth<paths$g>; /** * users client implementation. */ users: THeaders extends undefined ? Client<paths$h> : ClientWithAuth<paths$h>; /** * funnels client implementation. */ funnels: THeaders extends undefined ? Client<paths$i> : ClientWithAuth<paths$i>; /** * locations client implementation. */ locations: THeaders extends undefined ? Client<paths$j> : ClientWithAuth<paths$j>; /** * links client implementation. */ links: THeaders extends undefined ? Client<paths$k> : ClientWithAuth<paths$k>; /** * companies client implementation. */ companies: THeaders extends undefined ? Client<paths$m> : ClientWithAuth<paths$m>; /** * contacts client implementation. */ contacts: THeaders extends undefined ? Client<paths$n> : ClientWithAuth<paths$n>; /** * forms client implementation. */ forms: THeaders extends undefined ? Client<paths$o> : ClientWithAuth<paths$o>; /** * calendars client implementation. */ calendars: THeaders extends undefined ? Client<paths$p> : ClientWithAuth<paths$p>; /** * medias client implementation. */ medias: THeaders extends undefined ? Client<paths$q> : ClientWithAuth<paths$q>; /** * social media posting client implementation. */ socialMediaPosting: THeaders extends undefined ? Client<paths$2> : ClientWithAuth<paths$2>; /** * client configuration */ _clientConfig: HighLevelClientConfig; constructor(clientConfig?: HighLevelClientConfig, authHeaders?: THeaders | undefined); } export { type AuthHeaders as A, type DefaultOauthClient as D, type GetInstalledLocationResponse as G, HighLevelClient as H, type LocationTokenParams as L, OauthClientImpl as O, type SearchInstalledLocationParams as S, type TokenParams as T, type HighLevelClientConfig as a, type HighLevelOauthConfig as b, HighLevelClientWithOAuth as c, type AuthUrlParams as d, type AuthCodeParams as e, type LocationTokenResponse as f, type AccessTokenResponse as g, type TokenData as h, type OAuthClientInterface as i };