import { IRateLimiterOptions } from 'rate-limiter-flexible'; import { RateLimiterAbstract } from 'rate-limiter-flexible'; import { RateLimiterQueue } from 'rate-limiter-flexible'; import { RateLimiterQueueError } from 'rate-limiter-flexible/lib/component/index.js'; /** {@inheritDoc argumentErrorType} * * @public * */ export declare class ArgumentError extends Error implements MotionError { /** Name of the invalid argument. */ readonly argumentName: string; /** Value of the invalid argument. */ readonly argumentValue: T; /** {@inheritDoc MotionError.message} */ readonly message: string; /** {@inheritDoc MotionError.errorType} */ errorType: typeof argumentErrorType; constructor( /** Name of the invalid argument. */ argumentName: string, /** Value of the invalid argument. */ argumentValue: T, /** {@inheritDoc MotionError.message} */ message: string); } /** An illegal argument was passed to a function or method. * * @remarks * See {@link isArgumentError} for a built-in way to identify {@link ArgumentError} objects. * * @public */ export declare const argumentErrorType: "ARGUMENT_ERROR"; /** {@inheritDoc closedErrorType} * * @public */ export declare class ClosedError extends Error implements MotionError { /** Developer-readable reason for the closure. */ readonly reason: string; /** Error that caused the closure. */ readonly cause?: MotionError | undefined; /** {@inheritDoc MotionError.errorType} */ readonly errorType: typeof closedErrorType; constructor( /** Developer-readable reason for the closure. */ reason: string, /** Error that caused the closure. */ cause?: MotionError | undefined); } /** The client is already closed. * * @remarks * See {@link isClosedError} for a built-in way to identify {@link ClosedError} objects. * * @public * */ export declare const closedErrorType: "MOTION_CLIENT_CLOSED"; /** End-of-life information on a {@link Motion} client. * * @public */ export declare interface ClosedReason { /** Brief, developer-readable explanation for the closure. */ reason: string; /** Error that caused the client to closed, if any. */ cause?: MotionError; } /** Number of requests that can be queued to comply with the rate limit. * * @remarks * Override with {@link MotionOptions.maxQueueSize}. * * @public * */ export declare const defaultQueueSize = 20; /** {@inheritDoc fetchErrorType} * * @public */ export declare class FetchError extends Error implements MotionError { /** The underlying error that was thrown by {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch}. */ readonly cause: unknown; /** The failing parameters to {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch}. */ readonly request: { input: string | URL | globalThis.Request; init?: RequestInit; }; /** {@inheritDoc MotionError.errorType} */ readonly errorType: typeof fetchErrorType; constructor( /** The underlying error that was thrown by {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch}. */ cause: unknown, /** The failing parameters to {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch}. */ request: { input: string | URL | globalThis.Request; init?: RequestInit; }); } /** There was an error in making the request. * * @remarks * See {@link isFetchError} for a built-in way to identify {@link FetchError} objects. * * @public */ export declare const fetchErrorType: "FETCH_ERROR"; /** Possible single errors returned by {@link Motion.fetch}. * * @public */ export declare type FetchIndividualError = UnsafeFetchIndividualError | ClosedError | LimiterError | QueueOverflowError; /** Type assertion for {@link ArgumentError}. * * @public */ export declare function isArgumentError(o: unknown): o is ArgumentError; /** Type assertion for {@link ClosedError}. * * @public */ export declare function isClosedError(o: unknown): o is ClosedError; /** Type assertion for {@link FetchError}. * * @public */ export declare function isFetchError(o: unknown): o is FetchError; /** Type assertion for {@link LimiterError}. * * @public */ export declare function isLimiterError(o: unknown): o is LimiterError; /** Type assertion for {@link LimitExceededError}. * * @public */ export declare function isLimitExceededError(o: unknown): o is LimitExceededError; /** Type assertion for {@link MotionError}. * * @public */ export declare function isMotionError(o: unknown): o is MotionError; /** Type assertion for {@link MultiError}. * * @public */ export declare function isMultiError(o: unknown): o is MultiError; /** Type assertion for {@link QueueOverflowError}. * * @public */ export declare function isQueueOverflowError(o: unknown): o is QueueOverflowError; /** {@inheritDoc limiterErrorType} * * @public */ export declare class LimiterError extends Error implements MotionError { /** The erroring rate limiter. See {@link https://github.com/animir/node-rate-limiter-flexible/wiki | rate-limiter-abstract reference}. * */ readonly limiter: RateLimiterAbstract; /** The underlying error from the rate limiter. */ readonly cause: unknown; /** The rate limiter key that was attempted. * * @remarks * An {@link https://github.com/animir/node-rate-limiter-flexible/wiki | rate-limiter-flexible} * tracks the same limit independently across multiple keys. In some * cases it is important to know which particular key is returning * errors. * */ readonly attemptedKey?: string | number | undefined; /** {@inheritDoc MotionError.errorType} */ errorType: typeof limiterErrorType; constructor( /** The erroring rate limiter. See {@link https://github.com/animir/node-rate-limiter-flexible/wiki | rate-limiter-abstract reference}. * */ limiter: RateLimiterAbstract, /** The underlying error from the rate limiter. */ cause: unknown, /** The rate limiter key that was attempted. * * @remarks * An {@link https://github.com/animir/node-rate-limiter-flexible/wiki | rate-limiter-flexible} * tracks the same limit independently across multiple keys. In some * cases it is important to know which particular key is returning * errors. * */ attemptedKey?: string | number | undefined); } /** An error prevented checking or updating the rate limit. * * @remarks * See {@link isLimiterError} for a built-in way to identify {@link LimiterError} objects. * * @public * */ export declare const limiterErrorType: "MOTION_LIMITER_ERROR"; /** {@inheritDoc limitExceededErrorType} * * @public */ export declare class LimitExceededError extends Error implements MotionError { /** {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} that was returned by Motion. */ readonly response: Response; /** {@inheritDoc MotionError.errorType} */ errorType: typeof limitExceededErrorType; constructor( /** {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} that was returned by Motion. */ response: Response); } /** Motion returned 429 Limit Exceeded. We have overrun the rate limit. * * @remarks * See {@link isLimitExceededError} for a built-in way to identify {@link LimitExceededError} objects. * * @public * */ export declare const limitExceededErrorType: "MOTION_API_RATE_LIMIT_EXCEEDED"; /** Motion API client. * * @remarks * * Simple wrapper around the usemotion.com API. Just provide a user ID * and API key, and then start making requests. * * Warning: Motion {@link https://docs.usemotion.com/docs/motion-rest-api/44e37c461ba67-motion-rest-api#rate-limit-information | enforces} * its rate limit strictly. Excessive overruns of the rate limit can * result in losing your API privileges and having to get them back * through customer support. * * This client will not exceed the rate limit so long as only one * instance makes requests to the Motion API for any one user and no * calls are made directly to any of the `unsafe_` methods. If you * require more advanced usage, you can pass a custom rate limiter. * * @public */ declare class Motion { /** {@inheritDoc MotionOptions.userId} */ readonly userId: string | null; /** {@inheritDoc MotionOptions.apiKey} */ private readonly apiKey; /** {@inheritDoc MotionOptions.baseUrl} */ readonly baseUrl: string; /** Request queue. */ readonly requestQueue: RateLimiterQueue; /** {@inheritDoc MotionOptions.requestLimiter} */ readonly requestLimiter: RateLimiterAbstract; /** {@inheritDoc MotionOptions.overrunLimiter}*/ readonly overrunLimiter: RateLimiterAbstract; /** Rate limiter key where requests are tracked. */ readonly requestLimiterKey: string; /** Rate limiter key where overruns are tracked. */ readonly overrunLimiterKey: string; private _closedReason; /** Create a Motion API client. * * @remarks * Initializes a Motion API client with the provided user ID and API key. * Consult the {@link https://help.usemotion.com/integrations/integrations-101/api-docs | Motion API docs} for how to get an API key. * * If there may be multiple `Motion` clients sharing the same user, * you must pass a custom request rate limiter and a custom overrun * rate limiter that share the same backing store as the other * `Motion` clients. * * You may adjust the maximum number of queued requests; the * default is {@link defaultQueueSize}. * * `motion-sdk` does not throw. If the constructor is called with * invalid arguments or if another error occurs, the client will be * closed immediately. The error will be set in * {@link Motion.closedReason | closedReason}. * * @example * Basic usage: * ```typescript * const motion = new Motion({ * userId: 'my-user-id', * apiKey: 'my-api-key', * }); * ``` * * @example * Or, you can set the environment variables `MOTION_USER_ID` and * `MOTION_API_KEY`. Then: * ```typescript * const motion = new Motion(); * ``` * * @example * To set custom rate limiters: * * ```typescript * // 1 request per 5 seconds * const requestLimiter = new RateLimiterMemory({ * points: 1, * duration: 5, // seconds * }); * // 2 overruns per day * const overrunLimiter = new RateLimiterMemory({ * points: 2, * duration: 60 * 60 * 24, * }); * const motion = new Motion({ * requestLimiter, * overrunLimiter, * maxQueueSize: 0, // Disable queue * }); * await motion.fetch("/users/me"); * ``` * * The requestLimiter and overrunLimiter must be instances of the * {@link https://github.com/animir/node-rate-limiter-flexible/blob/master/lib/RateLimiterAbstract.js | RateLimiterAbstract} * class from {@link https://www.npmjs.com/package/rate-limiter-flexible | rate-limiter-flexible}. * * As of this writing, `rate-limiter-flexible` provides rate limiters * backed by Redis, Prisma, DynamoDB, process Memory, Cluster or PM2, * Memcached, MongoDB, MySQL, and PostgreSQL. Refer to their * documentation for more detailed help. * * The default limiter is * {@link https://github.com/animir/node-rate-limiter-flexible/blob/master/lib/RateLimiterMemory.js | RateLimiterMemory} * with the limits from {@link recommendedRateLimits}. The maximum * queue size is given by {@link defaultQueueSize}. * * @param opts - Object with client parameters * * @public */ constructor(opts?: MotionOptions); /** Safe entry point to the HTTP layer. * * @remarks * This function makes an HTTP request to the Motion API. The request * and return values are the same as the platform * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch()}, * except some logic is added for authentication and session management. * If a string is passed as the request URL, the API's base URL will * be prepended. * * This method enforces a client-side rate limit so as not to exceed * Motion's API rate limits. If there have been too many recent * requests, the request will be queued up to the client's maximum * queue size. An error will be returned if the queue is overflowing * or if there is an issue with the rate limit. * * In the event the request limiter is misconfigured and Motion returns * a 429 Limit Exceeded response, `fetch` assumes the client has * entered an unsafe state. The client will close immediately and make * no further requests. The overrun will be recorded with the overrun * limiter. * * @example * A basic example: * ```typescript * const response = await motion.fetch("/users/me"); * if (!isMotionError(response) && response.ok) { * const json = await response.json(); * console.log(JSON.stringify(json)); * // {"id":"elp69uRwOplFSiM3llAGhixqmPTP","name":"Bill Lumbergh","email":"blumbergh@initech.com"} * } * ``` * * @param input - URL or Request object * @param init - Request parameters * @returns {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} or a {@link MotionFetchError} */ fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise; /** Status of the client. * * @returns `true` if the client initialized successfully and can * still be used to make requests. * */ isOpen(): boolean; /** Reason the client was closed, if any. */ get closedReason(): ClosedReason | null; /** Terminate the client and free any associated resources. * * @remarks * After calling, it will be impossible to make requests to Motion under most * circumstances. Some `unsafe_` methods will continue to work. * * @param reason - Developer-readable explanation for the closure. * @param cause - Error that precipitated the closure, if any. */ close(reason: string, cause?: MotionError): undefined | ClosedError; /** Low-level interface to the Motion API. * * @remarks * This function makes a call to the Motion API. The request and * return values are the same as the platform * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch()}, * except some logic is added for authentication and session management. * If a string is passed as the request URL, the API's base URL will * be prepended. * * `unsafe_fetch` does not respect rate limiting or anything else about * the client's state. It can be called and will happily make requests * to the Motion API even if the limit is already exceeded and even if * {@link Motion.close | close} has been called. It will _not_ update * the internal rate limiter, even if Motion reports a rate limit overrun. * * Normally this function should be called only from * {@link Motion.fetch}, but it is exposed to accommodate performance * optimizations by advanced users. Use at your own peril. * * @param input - URL or Request object. * @param init - Request parameters. * * @returns {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} or an {@link UnsafeFetchError} */ unsafe_fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise; private handleLimitExceeded; private setHeaders; private waitForTurn; } export { Motion } export default Motion; /** Location of the live API. * * @public */ export declare const motionBaseUrl: "https://api.usemotion.com/v1"; /** Base interface for all errors returned by `motion-sdk`. * * @public */ export declare interface MotionError { /** Indicates the class of the error. * * @remarks * Each distinct type of {@link MotionError} has its own constant value * of `errorType`. This is the recommended way to programmatically * distinguish between, say, a {@link LimiterError} and a {@link FetchError}, * to take appropriate recovery steps. * * See {@link isMotionError} and the related `is*Error` functions for * built-in type assertions. * */ readonly errorType: typeof argumentErrorType | typeof fetchErrorType | typeof limiterErrorType | typeof queueOverflowErrorType | typeof closedErrorType | typeof limitExceededErrorType | typeof multiErrorType; /** Developer-readable error message. */ readonly message: string; } /** Possible errors returned by {@link Motion.fetch}. * * @public */ export declare type MotionFetchError = FetchIndividualError | MultiError; /** Location of the mock API. * * @public */ export declare const motionMockBaseUrl: "https://stoplight.io/mocks/motion/motion-rest-api/33447"; /** Arguments to the {@link Motion} constructor. * @public * */ export declare interface MotionOptions { /** Base URL of the API. * * @remarks * Base URL the client should target. Useful to override in development. * * Motion provides a mock API at {@link motionMockBaseUrl}. * * @defaultValue * The constructor uses the following URLs in order of precedence: * 1. The URL set explicitly in the `MotionOptions` object. * 2. Value of {@link motionBaseUrl}. * */ baseUrl?: string; /** ID of the Motion user making the requests. * * @defaultValue This can instead be set with an environment variable, * `process.env.MOTION_USER_ID`. * */ userId?: string; /** API key for the requests. * * @defaultValue This can instead be set with an environment variable, * `process.env.MOTION_API_KEY`. * */ apiKey?: string; /** Rate limiter that tracks number of requests. * * @remarks * The default rate limiter will suffice for non-concurrent usage patterns. * If you are using multiple {@link Motion} objects with the same user ID, * make sure each client has the same limiter. * * See {@link https://github.com/animir/node-rate-limiter-flexible?tab=readme-ov-file#docs-and-examples | rate-limiter-flexible}. * * @defaultValue {@link https://github.com/animir/node-rate-limiter-flexible/wiki/Memory | RateLimiterMemory} with the {@link recommendedRateLimits | recommended} rate limit. */ requestLimiter?: RateLimiterAbstract; /** Rate limiter that tracks how many times we've exceeded the limit recently. * * @remarks * The default rate limiter will suffice for non-concurrent usage patterns. * If you are using multiple {@link Motion} objects with the same user ID, * make sure each client has the same limiter and uses the same key. * * An "overrun" refers an instance of exceeding Motion's maximum number * of requests per minute and receiving a 429 Limit Exceeded response. * Too many overruns results in automatic and permanent lockout. * * See {@link https://github.com/animir/node-rate-limiter-flexible?tab=readme-ov-file#docs-and-examples | rate-limiter-flexible}. * * @defaultValue {@link https://github.com/animir/node-rate-limiter-flexible/wiki/Memory | RateLimiterMemory} with the {@link recommendedRateLimits | recommended} rate limit. */ overrunLimiter?: RateLimiterAbstract; /** Maximum number of queued requests. */ maxQueueSize?: number; } /** Rate limit information about the Motion API. * * @remarks * Motion has two rate limits: * * - If you exceed 12 requests in a minute, Motion will return 429 * Limit Exceeded and disable your API access for an hour. * `motion-sdk` calls that an 'overrun'. * - If you have three overruns in a day, Motion will disable your * API access until you contact support and ask them to restore it. * * `motion-sdk` is an _unofficial_ client and its authors are not * affiliated with Motion. Always consult the * {@link https://docs.usemotion.com/docs/motion-rest-api/44e37c461ba67-motion-rest-api#rate-limit-information | official API reference } * for up-to-date rate limit information. * * @public * */ export declare interface MotionRateLimits { /** Rate limiter parameters for requests. */ requests: Required>; /** Rate limiter parameters for overruns. */ overruns: Required>; } /** Official rate limits used by Motion. * * NOTE: For additional safety, consider using {@link recommendedRateLimits} instead. * * @public * */ export declare const motionRateLimits: MotionRateLimits; /** {@inheritDoc multiErrorType} * * @public */ export declare class MultiError extends Error implements MotionError { /** The underlying errors. */ readonly errors: T[]; /** {@inheritDoc MotionError.errorType} */ readonly errorType: typeof multiErrorType; constructor( /** The underlying errors. */ errors: T[]); } /** Multiple errors occurred. * * @remarks * See {@link isMultiError} for a built-in way to identify {@link MultiError} objects. * * @public * */ export declare const multiErrorType: "MOTION_MULTI_ERROR"; /** {@inheritDoc queueOverflowErrorType } * * @public * */ export declare class QueueOverflowError extends Error implements MotionError { /** The overflowing queue. */ readonly queue: RateLimiterQueue; /** The overflow error from the underlying framework. */ readonly cause: RateLimiterQueueError; /** The rate limiter key that was attempted. */ readonly attemptedKey: string | number; /** {@inheritDoc MotionError.errorType} */ errorType: typeof queueOverflowErrorType; constructor( /** The overflowing queue. */ queue: RateLimiterQueue, /** The overflow error from the underlying framework. */ cause: RateLimiterQueueError, /** The rate limiter key that was attempted. */ attemptedKey: string | number); } /** Too many waiting requests already. * * @remarks * See {@link isQueueOverflowError} for a built-in way to identify {@link QueueOverflowError} objects. * * @public * */ export declare const queueOverflowErrorType: "MOTION_LIMITER_QUEUE_EXCEEDED"; /** Internal rate limits with a small headroom against the official limits. * * @public */ export declare const recommendedRateLimits: MotionRateLimits; /** Possible errors returned by {@link Motion.unsafe_fetch}. * * @public */ export declare type UnsafeFetchError = UnsafeFetchIndividualError | MultiError; /** Possible single errors returned by {@link Motion.unsafe_fetch}. * * @public */ export declare type UnsafeFetchIndividualError = ArgumentError | LimitExceededError | FetchError; export { }