UNPKG

nabii-sdk

Version:

Private SDK of Nabii by Ulysse Dupont

1,795 lines (1,752 loc) 69.8 kB
import { AxiosError, AxiosInstance, AxiosResponse, AxiosRequestConfig, } from "axios"; import * as SocketClient from "socket.io-client"; import * as buffer from "buffer"; import { Op, Any } from "@dulysse1/ts-helper"; import FormData from "form-data"; import { Brand, Infer } from "@dulysse1/ts-branding"; import { PushNotifications } from "@capacitor/push-notifications"; /** * Symbol used to brand objects with form error information. * Values branded with this symbol indicate an error condition in form data. */ declare const formErrorBrand: unique symbol; /** * Make all properties in T optional but non-nullable. * * @template T - The type whose properties will be made optional and non-nullable. */ declare type IPartialNonNullable<T> = { [Key in keyof T]?: T[Key] extends object ? T[Key] extends INabiiFile ? NonNullable<T[Key]> : IPartialNonNullable<T[Key]> : NonNullable<T[Key]>; }; /** * Check if a type `T` is not `any`. * * This utility type resolves to `T` if `T` is not `any`. Otherwise, it resolves to `never`. * * @template T - The type to be checked. */ declare type IResolve<T> = Any.Is<T> extends true ? never : T; /** * Represents the format of a form data file to upload for {@link NabiiV1}. * * The file can be of several types, including: * - A resolved `Buffer` object from the `buffer` module. * - A resolved `Blob` object from the `global` module. */ declare type INabiiFile = IResolve<buffer.Buffer> | IResolve<Blob>; /** * Improved type definition for `form-data` objects. * * This interface extends the built-in `FormData` interface, adding type safety for appending data. * The `append` method only accepts keys and values that exist in the provided type `T`. * * @template T - The type of the data object. Keys and values of this type will be enforced when appending data. */ declare interface IFormData<T = object> extends FormData { append: <TKey extends keyof T>( key: TKey extends string ? TKey : string, value: T[TKey], ) => void; } /** * A type representing safe form data. * * This type ensures type safety when dealing with form data objects. It uses conditional types to enforce * specific rules: * * - If the type `T` extends `IFormData`, it is returned as is. * - If the type `T` satisfies the condition defined by `IRequireFile`, it is converted to `FormData`. * - Otherwise, the type `T` itself is returned. * * The type also ensures compatibility with {@link IFormErrorBrand}, making it a safe choice for optional form data parameters. * * @template T - The type of the data object to be checked. Defaults to `object`. */ declare type ISafeForm<T = object> = Op.Satisfy< T extends IFormData ? T : Op.Or< INabiiFile extends NonNullable<T[keyof T]> ? true : false, INabiiFile[] extends NonNullable<T[keyof T]> ? true : false > extends true ? T & { [formErrorBrand]: "You are using 'INabiiFile' data in your form, please bind 'data' using the 'useFormData' function!"; } : T, T | undefined >; /** * Unpack socket event parameters. * * @template T - The type representing an array of event listener functions. */ declare type IUnpackEventParam<T> = T extends (( ...args: infer Param ) => unknown)[] ? Op.Satisfy<Param, unknown[]> : never; /** * Unpack socket event listener function. * * @template T - The type representing an array of event listener functions. * @returns {Function} - The unpacked event listener function. */ declare type IUnpackEventFunction<T> = T extends (infer Func)[] ? Func : never; /** * Check if a `type` contains a specific `Brand`. * * @template T - The type to check for the presence of the brand. * @template Brand - The brand symbol to check for in the type. * @returns {boolean} - `true` if the brand is present in the type, otherwise `false`. */ declare type IIsBranded<T, TBrand extends symbol> = TBrand extends keyof T ? true : false; /** * A type representing a class with a constructor. * * @template TArgs - The type of arguments the constructor accepts. Defaults to an array of unknown types. * @template TReturn - The type of the instance returned by the constructor. Defaults to an unknown type. */ declare interface IClass< TArgs extends unknown[] = unknown[], TReturn = unknown, > { new (...args: TArgs): TReturn; } /** * #### The email subject JWT token format * This type represents the possible email subjects for JWT tokens. * * ##### Possible Values: * - `forgotPassword`: Page for resetting password. * - `activateAccount`: Page for validating the new email. * - `activateAccountInvite`: Page for setting a password. * * @example * ```tsx * const subject: IEmailSubject = "forgotPassword"; * ``` * * @since v1.0.0 */ declare type IEmailSubject = | "forgotPassword" | "activateAccount" | "activateAccountInvite"; /** * This type represents the response type of a check token request. * * @since v1.0.13 */ declare type ICheckTokenResponseType = | { /** * the token is not valid... */ tokenIsValid: false; /** * ...so the user response is `null` */ user: null; } | { /** * the token is valid... */ tokenIsValid: true; /** * ...so the user object contain the user important information */ user: Pick< IUser<Platform.APPLICATION>, "firstName" | "lastName" | "email" >; }; /** * A unique symbol used to brand instances as `Logged`. * * @since v1.0.0 */ declare const loggedBrand: unique symbol; /** * Interface representing an instance with the `Logged` brand. * This can be used to mark class instances as logged. * * @since v1.0.0 */ declare interface ILogged { [loggedBrand]?: true; } /** * Type utility to check if a class instance contains the `Logged` brand. * * @template T - The type to check for the `Logged` brand. * * @since v1.0.0 */ declare type IIsLogged<T> = IIsBranded<T, typeof loggedBrand>; /** * The list of strategy names used to authenticate users with SSO. * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). */ declare type IStrategyName = Exclude< IStrategies, "local" | "apple" >[keyof Exclude<IStrategies, "local" | "apple">]; /** * The list of strategies used to authenticate users. */ declare type IStrategies = { /** * The default strategy. when you create your account with a password authentication * @default */ LOCAL: "local"; // skip local /** * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). */ GOOGLE: "google"; /** * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). */ FACEBOOK: "facebook"; /** * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). */ APPLE: "apple"; // not implemented }; /** * The list of strategy names used to authenticate users. */ declare type IStrategy = IStrategies[keyof IStrategies]; /** * #### ✨ List of {@link NabiiV1} authentication module types ✨: * - {@link IEmailSubject} * - {@link IStrategyName} * - {@link IStrategy} * - {@link IStrategies} * - {@link ICheckTokenResponseType} * --------------------------- * Do you have ideas or recommendations for improvement? * * @author Ulysse Dupont --> * [Email](mailto:ulyssedupont2707@gmail.com) * | [Github](https://github.com/Dulysse) * | [LinkedIn](https://www.linkedin.com/in/ulysse-dupont) * @since v1.0.0 */ declare namespace IAuthTypes { export type { IEmailSubject }; export type { IStrategyName }; export type { IStrategy }; export type { IStrategies }; export type { ICheckTokenResponseType }; } /** * User {@link NabiiV1} model type * @template TPlatform the platform currently in use * @since v1.0.0 */ declare type IUser<TPlatform extends Platform> = { [Platform.APPLICATION]: { /** * - The user `primary key` */ id: Brand.Pk<number>; /** * The `firstName` of the user */ firstName: string; /** * The `lastName` of the user */ lastName: string; /** * The `avatar` URL of the user * @expiredIn 30mn */ avatar: string; /** * The `email` of the user * @unique */ email: string; /** * The trategy names used to authenticate users with `SSO` or `local`. */ strategy: IStrategy; /** * The `role` of the user with one value from {@link IRoles} * - *To get the values, use `nabii.v1.User.roles`.* */ role: IRole; /** * The `firebaseToken` of the user to receive notification */ firebaseToken: string | null; /** * The `lastConnection` date of the user */ lastConnection: string | null; /** * The value is `false` if the user has not activated their account. */ isActivated: boolean; }; [Platform.ADMIN]: { /** * - The user `primary key` */ id: Brand.Pk<number>; /** * The `firstName` of the user */ firstName: string; /** * The `lastName` of the user */ lastName: string; /** * The `avatar` URL of the user * @expiredIn 30mn */ avatar: string; /** * The trategy names used to authenticate users with `SSO` or `local`. */ strategy: IStrategy; /** * The `email` of the user * @unique */ email: string; /** * The `role` of the user with one value from {@link IRoles} * - *To get the values, use `nabii.v1.User.roles`.* */ role: IRole; /** * The `firebaseToken` of the user to receive notification */ firebaseToken: string | null; /** * The `lastConnection` date of the user */ lastConnection: string | null; /** * The value is `false` if the user has not activated their account. */ isActivated: boolean; /** * The user `creation` date */ createdAt: string; /** * The user `last edit` date */ updatedAt: string; /** * The user `delete` date will always be `null` */ deletedAt: null; }; }[TPlatform]; /** * User {@link NabiiV1} model creation fields type * @template TPlatform the platform currently in use * @since v1.0.0 */ declare type ICreateUserForm<TPlatform extends Platform> = { [Platform.APPLICATION]: Pick< IUser<TPlatform>, "firstName" | "lastName" | "email" > & Partial<IAvatarSchema> & IPasswordSchema; [Platform.ADMIN]: Pick<IUser<TPlatform>, "firstName" | "lastName" | "email"> & Partial<IAvatarSchema>; }[TPlatform]; /** * User {@link NabiiV1} model edition fields type * @template TPlatform the platform currently in use * @since v1.0.0 */ declare type IUpdateUserForm<TPlatform extends Platform> = { [Platform.APPLICATION]: IPartialNonNullable< Pick<IUser<TPlatform>, "firstName" | "lastName"> & IAvatarSchema & IPasswordSchema >; [Platform.ADMIN]: IPartialNonNullable<ICreateUserForm<TPlatform>>; }[TPlatform]; /** * password object type definition for forms */ interface IPasswordSchema { /** * The `password` of the user account * @rules Here the password rules: * - must contain at least `8 characters` * - must contain a maximum of `64 characters` */ password: string; } /** * avatar object type definition for forms */ interface IAvatarSchema { /** * the avatar as buffer {@link INabiiFile} type */ avatar: INabiiFile; } /** * User {@link NabiiV1} model `GET` field parameters type * @template TPlatform the platform currently in use * @template TSearch the generic request `search` value (optional) * @template TLimit the generic request `limit` value (optional) * @template TPage the generic request `page` value (optional) * @since v1.0.0 */ declare type IUserParams< TPlatform extends Platform, TSearch extends string | undefined = string | undefined, TLimit extends number = number, TPage extends number = number, > = IPaginateOptions< { [Platform.APPLICATION]: "id" | "firstName" | "lastName" | "email"; [Platform.ADMIN]: | "id" | "firstName" | "lastName" | "email" | "role" | "createdAt" | "updatedAt"; }[TPlatform], TSearch, TLimit, TPage >; /** * Result when private information is updated. * * *This interface represents the result returned after updating a user's private information.* * * @since v1.0.0 */ declare interface IUserUpdatedResult extends Pick<IUser<Platform>, "id" | "email"> { /** * The date when the user was last edited. * * @type {string} */ updatedAt: string; } /** * Result when an email is sent. * * *This interface represents the result returned after sending an email to a user.* * * @since v1.0.0 */ declare interface IEmailSentResult extends Pick<IUser<Platform>, "email"> { /** * A boolean indicating that the email has been successfully sent. * * @type {boolean} */ emailSuccess: true; } /** * List of user roles. * * *This interface defines the various roles a user can have in the system. * Each role is associated with a specific integer value.* * * @since v1.0.0 */ declare interface IRoles { /** * The banned role value. * * @type {number} * @readonly */ readonly BANNED: 0; /** * The default user role value. * * @type {number} * @readonly */ readonly USER: 100; /** * The supervisor role value. * * @type {number} * @readonly */ readonly SUPERVISOR: 150; /** * The administrator role value. * * @type {number} * @readonly */ readonly ADMIN: 200; } /** * List of user role values. * * *This type represents the possible role values for users.* * * @since v1.0.0 */ declare type IRole = IRoles[keyof IRoles]; /** * A deleted user from the administrator's perspective, with a deletion date. * * *This type represents a user who has been deleted by an administrator, including the date of deletion.* * * @since v1.0.0 */ declare interface IDeletedUser extends Omit<IUser<Platform.ADMIN>, "deletedAt"> { /** * The date when the user was deleted. * * @type {string} */ deletedAt: string; } /** * Result of importing multiple users. * * *This interface represents the result of a bulk user creation operation, including counts of successes and failures.* * * @since v1.0.0 */ declare interface IBulkCreateResult { /** * The array of users created successfully. * * @type {IUser<Platform.ADMIN>[]} */ succeed: IUser<Platform.ADMIN>[]; /** * The array of users that were not created. * * @type {IDeletedUser[]} */ failed: IDeletedUser[]; } /** * #### ✨ List of {@link NabiiV1} user module types ✨: * - {@link IUser} * - {@link ICreateUserForm} * - {@link IUpdateUserForm} * - {@link IUserParams} * - {@link IUserUpdatedResult} * - {@link IEmailSentResult} * - {@link IRoles} * - {@link IRole} * - {@link IDeletedUser} * - {@link IBulkCreateResult} * - {@link IPasswordSchema} * - {@link IAvatarSchema} * --------------------------- * Do you have ideas or recommendations for improvement? * * @author Ulysse Dupont --> * [Email](mailto:ulyssedupont2707@gmail.com) * | [Github](https://github.com/Dulysse) * | [LinkedIn](https://www.linkedin.com/in/ulysse-dupont) * @since v1.0.0 */ declare namespace IUserTypes { export type { IUser }; export type { ICreateUserForm }; export type { IUpdateUserForm }; export type { IUserParams }; export type { IUserUpdatedResult }; export type { IEmailSentResult }; export type { IRoles }; export type { IRole }; export type { IDeletedUser }; export type { IBulkCreateResult }; export type { IPasswordSchema }; export type { IAvatarSchema }; } /** * #### List of {@link NabiiV1} platforms * *Enum representing the different platforms available in the {@link NabiiV1} system.* */ declare enum Platform { /** * 📱 Application platform for non-administrator {@link NabiiV1} routes. 📱 */ APPLICATION = "application", /** * 🖥️ Admin platform for administrator {@link NabiiV1} routes. 🖥️ */ ADMIN = "admin", } declare class ConfigV1 { /** * ⚠️ Use `setLang()` to modify the language ⚠️ */ lang: ILanguage; /** * ⚠️ Use `setUrl()` to modify the url ⚠️ */ url: string; /** * ⚠️ Use `setMode()` to modify the mode ⚠️ */ mode: IMode; isLogged: boolean; platform: Platform; allowSocket: boolean; firebaseToken?: string; allowFirebaseToken: boolean; credentials: ICredentials | IEmptyCredentials; errorHandler: (err: NabiiError) => void | Promise<void>; socket: SocketClient.Socket; readonly eventListener: { login: ((credentials: ICredentials) => void | Promise<void>)[]; logout: (() => void | Promise<void>)[]; refresh: ((credentials: ICredentials) => void | Promise<void>)[]; }; get roles(): IRoles; get strategies(): IStrategies; } /** * #### List of allowed {@link NabiiV1} languages * *An object representing the supported languages in the {@link NabiiV1} system.* */ declare const languages: { /** * French language. * @default */ readonly FR: "fr"; /** * English language. */ readonly EN: "en"; }; /** * #### List of allowed {@link NabiiV1} languages as type */ declare type ILanguages = typeof languages; /** * {@link NabiiV1} API header mode for unit testing rate limiter, only test mode allowed on `localhost` */ declare const modes: { /** * {@link modes}: * - `test` mode for unit testing */ readonly TEST: "test"; /** * {@link modes}: * - `production` mode * @default */ readonly PRODUCTION: "production"; }; /** * {@link NabiiV1} API header mode for unit testing rate limiter, only test mode allowed on `localhost` as type */ declare type IModes = typeof modes; /** * 🔗 {@link NabiiV1} `application` credentials 🔗 * * This interface defines the credentials required for accessing the * {@link NabiiV1} application, including the access token, refresh token, * and user data. */ declare interface ICredentials { /** * Your {@link NabiiV1} access token. * * *This token is used for authenticating API requests to the NabiiV1 application.* */ accessToken: string; /** * Your {@link NabiiV1} refresh token. * * *This token is used to obtain a new access token once the current one expires.* */ refreshToken: string; /** * Your {@link NabiiV1} user logged data. * * *Contains information about the authenticated user within the application.* * */ user: IUser<Platform.APPLICATION>; } /** * 🔗 {@link NabiiV1} `application` refresh token result object 🔗 */ declare type IRefreshTokenResult = Omit<ICredentials, "refreshToken">; /** * 🔗❌ {@link NabiiV1} type definition for an empty credentials object ❌🔗 * * *This type is used for the {@link NabiiV1} application where credentials are required to be an empty object.* * */ declare type IEmptyCredentials = Record<string, never>; /** * Type of allowed {@link NabiiV1} language values */ declare type ILanguage = ILanguages[keyof ILanguages]; /** * Generic paginated {@link NabiiV1} API `getAll` result * @template TModel the data resource type * @template TSearch the generic request `search` value (optional) * @template TLimit the generic request `limit` value (optional) * @template TPage the generic request `page` value (optional) * @since v1.0.0 */ declare interface IPaginated< TModel extends object, TSearch extends string | undefined = string | undefined, TLimit extends number = number, TPage extends number = number, > { /** * Your generic {@link TModel} data as array for this request * #### ✅ Good practice usage ✅ * ##### 🔱React hooks 🔱 * - Create a React hook with your SDK {@link IPaginated} method * ```tsx * import nabii, { type INabiiV1 } from "nabii-sdk"; * import { useInfiniteQuery } from "@tanstack/react-query"; * * export default function useUser( * params?: INabiiV1.IUserTypes.IUserParams< * INabiiV1.Platform.APPLICATION * > * ) { * return useInfiniteQuery({ * queryKey: ["user", params], * initialPageParam: params?.page ?? 1, * queryFn: ({ pageParam }) => { * return nabii.v1.User.Admin.getAll({ * page: pageParam, * ...params, * }); * }, * getNextPageParam: (lastPage, allPages) => { * return lastPage.hasNextPage ? allPages.length + 1 : undefined; * }, * }); * }; * ``` * - Then, use your hook into your component * ```tsx * import React from "react"; * import useUser from "../hooks/useUser"; * * const MyComponent = () => { * const { * data, * fetchNextPage, * hasNextPage, * isFetchingNextPage, * status, * error, * } = useUser(); * * if (status === "loading") { * return <div>Loading...</div>; * } * * if (status === "error") { * return <div>Error: {error.message}</div>; * } * * return ( * <div> * {data.pages.map((page, index) => ( * <div key={index}> * {page.data.map(user => ( * <div key={user.id}>{user.name}</div> * ))} * </div> * ))} * <button * onClick={() => fetchNextPage()} * disabled={!hasNextPage || isFetchingNextPage} * > * {isFetchingNextPage ? "Loading more..." : hasNextPage ? "Load More" : "No more results"} * </button> * </div>); * }; * export default MyComponent; * ``` */ data: TModel[]; /** * Check if there is more {@link TPage} for this request */ hasNextPage: boolean; /** * Get the current {@link TPage} number for this request * @sql * (limit * `page`) - limit + additionalOffset * @default 1 */ currentPage: TPage; /** * The amount of `pages` for this request */ totalPages: number; /** * The total count of {@link TModel} for this request */ totalCount: number; /** * The current {@link TPage} size for this request * @sql * (`limit` * page) - `limit` + additionalOffset * @default 15 */ currentLimit: TLimit; /** * Your {@link TSearch} value for this request * @default undefined */ search: TSearch; /** * The additional `offset` value * @sql * (limit * page) - limit + `additionalOffset` * @default 0 */ additionalOffset: number; } /** * #### Generic paginated {@link NabiiV1} API `getAll` params * @template TSortField the `sortField` options for this resource * @template TSearch the generic request `search` value (optional) * @template TLimit the generic request `limit` value (optional) * @template TPage the generic request `page` value (optional) * @since v1.0.0 */ declare interface IPaginateOptions< TSortField extends string, TSearch extends string | undefined = string | undefined, TLimit extends number = number, TPage extends number = number, > { /** * Set the {@link TLimit} of data to get in a single {@link TPage} * @sql * (`limit` * page) - `limit` + additionalOffset * @default 5 */ limit?: TLimit; /** * Set the data {@link TPage} index * @sql * (limit * `page`) - limit + additionalOffset * @default 1 */ page?: TPage; /** * Set the {@link TSearch} field * @default undefined */ search?: TSearch; /** * Set field for the data sorting * @default "id" */ sortField?: TSortField; /** * Set order for the data sorting * @default "ASC" */ sortOrder?: "ASC" | "DESC"; /** * The additional `offset` value * @sql * (limit * page) - limit + `additionalOffset` * @default 0 */ additionalOffset?: number; } /** * Creation or modification date format allowed for {@link NabiiV1} form */ declare type IDate = string | Date; /** * {@link NabiiV1} API header mode for unit testing rate limiter, only test mode allowed on `localhost` */ declare type IMode = IModes[keyof IModes]; /** * #### ✨ List of {@link NabiiV1} global types ✨: * - {@link Platform} * - {@link ICredentials} * - {@link IRefreshTokenResult} * - {@link IEmptyCredentials} * - {@link ILanguage} * - {@link INabiiFile} * - {@link IPaginated} * - {@link IPaginateOptions} * - {@link IDate} * - {@link IMode} * --------------------------- * Do you have ideas or recommendations for improvement? * * @author Ulysse Dupont --> * [Email](mailto:ulyssedupont2707@gmail.com) * | [Github](https://github.com/Dulysse) * | [LinkedIn](https://www.linkedin.com/in/ulysse-dupont) * @since v1.0.0 */ declare namespace IGlobalTypes { export { Platform, type ICredentials, type IRefreshTokenResult, type IEmptyCredentials, type ILanguage, type INabiiFile, type IPaginated, type IPaginateOptions, type IDate, type IMode, }; } /** * #### 🏴‍☠️ Nabii SDK error object 🏴‍☠️ * @example * ```tsx * import { NabiiError } from "nabii-sdk"; * * try { * // do some nabii stuff! * } catch (err) { * if (err instanceof NabiiError) { * if (err.response) { * // get error message! * console.log(err.response.data); * } else { * console.log("No internet connection!"); * } * } * } * ``` */ declare class NabiiError extends AxiosError<string, string> { constructor(error: AxiosError<string, string>); } declare interface INabiiAxiosInstance extends AxiosInstance { /** * Overrides the {@link axios.post} method to enforce the usage of `useFormData` * function if the data object contains an {@link INabiiFile}. * * *If it contains an {@link INabiiFile}, it must use `useFormData` If not, TypeScript will infer the type as {@link IFormErrorBrand}* * * @template T - The expected response type. * @template TResponse - The Axios response type. * @template TData - The type of the data object. * @param {string} url - The URL to send the request to. * @param {ISafeForm<TData>} data - The data to send with the request. If it contains an {@link INabiiFile}, it must use `useFormData` If not, TypeScript will infer the type as {@link IFormErrorBrand}. * @param {AxiosRequestConfig} config - The Axios request configuration. * @returns {Promise<TResponse>} - The Axios response promise. */ post<T = unknown, TResponse = AxiosResponse<T>, TData = object>( url: string, data?: ISafeForm<TData>, config?: AxiosRequestConfig, ): Promise<TResponse>; /** * Overrides the {@link axios.patch} method to enforce the usage of `useFormData` * function if the data object contains an {@link INabiiFile}. * * *If it contains an {@link INabiiFile}, it must use `useFormData` If not, TypeScript will infer the type as {@link IFormErrorBrand}* * * @template T - The expected response type. * @template TResponse - The Axios response type. * @template TData - The type of the data object. * @param {string} url - The URL to send the request to. * @param {ISafeForm<TData>} data - The data to send with the request. If it contains an {@link INabiiFile}, it must use `useFormData` If not, TypeScript will infer the type as {@link IFormErrorBrand}. * @param {AxiosRequestConfig} config - The Axios request configuration. * @returns {Promise<TResponse>} - The Axios response promise. */ patch<T = unknown, TResponse = AxiosResponse<T>, TData = object>( url: string, data?: ISafeForm<TData>, config?: AxiosRequestConfig, ): Promise<TResponse>; } /** * #### 🏴‍☠️ {@link BaseV1} class for {@link NabiiV1} 🏴‍☠️ * - List of `global` and `protected` SDK `methods` and `properties` of {@link NabiiV1} */ declare abstract class BaseV1 { protected readonly _axios: INabiiAxiosInstance; protected readonly _config: ConfigV1; protected _initAxiosHooks(): void; protected _throwError(err: NabiiError): Promise<never>; protected _initSocket(): void; protected _updateSocketConnection(): Promise<void>; protected _connectSocket(): Promise<void>; protected _disconnectSocket(): Promise<void>; protected _resetSocket(): Promise<void>; protected _triggerEventListener< T extends InstanceType<IBaseV1>["_config"]["eventListener"], TKey extends keyof T = keyof T, >(eventName: TKey, ...payload: IUnpackEventParam<T[TKey]>): Promise<void>; protected _refresh(): Promise<IRefreshTokenResult>; protected _logout(): Promise<void>; protected _setCredentials( credentials: Partial<ICredentials>, ): Promise<IRefreshTokenResult>; protected _checkEnableFirebaseToken(): Promise<void>; protected _enableFirebaseToken(): Promise<void>; protected _disableFirebaseToken(): Promise<void>; } declare type IBaseV1 = typeof BaseV1; /** * List of default server {@link NabiiV1} event listeners for `on` and `off` socket methods */ declare interface IDefaultEventListeners { connect: () => void; connect_error: () => void; connect_success: () => void; disconnect: (data: "io client disconnect") => void; } /** * List of event `emitter` for server {@link NabiiV1} for `emit` socket method */ declare interface IEmitEvents { ping: (data: { /** * the actual date to get delay in milliseconds with the server for `pong` event response. * {@link IOnEvents.pong} */ now: Date; }) => void; } /** * List of server {@link NabiiV1} event listeners for `on` and `off` socket methods */ declare interface IOnEvents extends IDefaultEventListeners { pong: (data: { /** * The response delay to join the server in milliseconds * {@link IEmitEvents.ping} */ responseTime: number; }) => void; } /** * #### ✨ List of {@link NabiiV1} socket module types ✨: * - {@link IDefaultEventListeners} * - {@link IEmitEvents} * - {@link IOnEvents} * --------------------------- * Do you have ideas or recommendations for improvement? * * @author Ulysse Dupont --> * [Email](mailto:ulyssedupont2707@gmail.com) * | [Github](https://github.com/Dulysse) * | [LinkedIn](https://www.linkedin.com/in/ulysse-dupont) * @since v1.0.0 */ declare namespace ISocketTypes { export type { IDefaultEventListeners, IEmitEvents, IOnEvents }; } /** * @class {@link SocketV1} * @since v1.0.0 * @extends {BaseV1} */ declare class SocketV1 extends BaseV1 { /** * `📱 SOCLE 📱` * #### ⬆️ Send a socket to the server ⬆️ * @param evName the name of the target socket event refer to {@link IEmitEvents} * @param payload the payload to send to socket server refer to {@link IEmitEvents} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * nabii.v1.Socket.emit("ping", "payload!"); * ``` * @returns a void function * @since v1.0.0 */ emit<TEmitEv extends IEmitEvents, TEvName extends keyof IEmitEvents>( evName: TEvName, ...payload: Parameters<TEmitEv[TEvName]> ): void; /** * @public * `📱 SOCLE 📱` * #### ⬇️ Receive a socket from the server ⬇️ * @param evName the name of the target socket event refer to {@link IOnEvents} * @param listener the listener to apply to this event refer to {@link IOnEvents} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * nabii.v1.Socket.on("pong", msg => { * console.log("Message:", msg); * }); * ``` * @returns a void function * @since v1.0.0 */ on<TOnEv extends IOnEvents, TEvName extends keyof IOnEvents>( evName: TEvName, listener: TOnEv[TEvName], ): void; /** * @public * `📱 SOCLE 📱` * #### 🗑️ Kill a socket event from the server 🗑️ * @param evName the name of the target socket event refer to {@link IOnEvents} * @param listener the listener to apply to this event refer to {@link IOnEvents} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * nabii.v1.Socket.off("pong", msg => { * console.log("Message:", msg); * }); * nabii.v1.Socket.off("pong"); * ``` * @returns a void function * @since v1.0.0 */ off<TOnEv extends IOnEvents, TEvName extends keyof IOnEvents>( evName: TEvName, listener?: TOnEv[TEvName], ): void; /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if socket is connected to {@link NabiiV1} (you must call the `login` or `setCredential` method before) 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Socket.isLogged()) { * console.log("Socket is up!"); * } * ``` * @returns the login as socket state * @since v1.0.0 */ isLogged(): boolean; /** * @public * `📱 SOCLE 📱` * #### ✅ Enable socket connection to {@link NabiiV1} ✅ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * await nabii.v1.Socket.enable(); * console.log("Socket is up!"); * ``` * @returns a void function * @since v1.0.0 */ enable(): Promise<void>; /** * @public * `📱 SOCLE 📱` * #### ❌ Disable socket connection to {@link NabiiV1} ❌ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * await nabii.v1.Socket.disable(); * console.log("Socket is down!"); * ``` * @returns a void function * @since v1.0.0 */ disable(): Promise<void>; } /** * @class {@link AuthV1} * @since v1.0.0 * @extends {BaseV1} */ declare class AuthV1 extends BaseV1 { /** * @public * `📱 SOCLE 📱` * #### 🔑 Get the login `href` URL to {@link NabiiV1} Oauth SSO strategy 🔑 * @description this URL will redirect you to the SSO provider login page, on success, the callback will be called and open the application * page `/login/cb` with query params `{accessToken, refreshToken, strategy}`, then you will have to call the SDK method {@link AuthV1.setCredentials} method with the query params and finally redirect to the home page to be connected. * @example * ```tsx * <a href={nabii.v1.Auth.strategy("google")}>Sign in with Google</a> * <a href={nabii.v1.Auth.strategy("apple")}>Sign in with Apple</a> * <a href={nabii.v1.Auth.strategy("facebook")}>Sign in with Facebook</a> * ``` * @param name The strategy names used to authenticate users with SSO. * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). * @returns the server URL to handle SSO login request * @since v1.0.10 */ strategy(name: IStrategyName): string; /** * The list of strategies used to authenticate users. * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). * @returns the server URL to handle SSO login request * @since v1.0.19 */ get strategies(): IStrategies; /** * @public * `📱 SOCLE 📱` * #### 🆕 Create a new {@link NabiiV1} {@link IUser} 🆕 * @param data user data to create * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.create({ * firstName : "MyName", * lastName: "MyLastName", * email: "email@domain.com", * password: "my_password", * }); // {...} * ``` * @returns the created {@link IUser} object * @since v1.0.0 */ register( data: ICreateUserForm<Platform.APPLICATION>, ): Promise<IUser<Platform.APPLICATION>>; /** * @public * `📱 SOCLE 📱` * ### ♻️ Callback email creation to get another email sent ♻️ * @param email your email address to receive an email * @example * ```ts * await nabii.v1.Auth.callbackActivateAccount("email@domain.com"); // {...} * ``` * @returns the object result of email receive * @since v1.0.12 */ callbackActivateAccount(email: string): Promise<IEmailSentResult>; /** * @public * `📱 SOCLE 📱` * #### 🔐 Login to {@link NabiiV1} 🔐 * *ℹ If you are already logged in from storage, use the {@link AuthV1.setCredentials} method instead. ℹ* * @param email Your {@link NabiiV1} email address * @param password Your {@link NabiiV1} account password * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { accessToken } = await nabii.v1.Auth.login( * "email@domain.com", * "my_password" * ); * console.log("I am logged!"); * ``` * @returns the {@link ICredentials} object * @since v1.0.0 */ login(email: string, password: string): Promise<ICredentials>; /** * @public * `📱 SOCLE 📱` * #### 📡 Set credentials to {@link NabiiV1} when you're already logged in from `storage` 📡 * @param credentials app credentials (accessToken, refreshToken and user object: {@link ICredentials}) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { accessToken, refreshToken, user } = storage; * await nabii.v1.Auth.setCredentials({ * accessToken, * refreshToken, * user, * }); * ``` * @returns the {@link ICredentials} `accessToken` up-to-date * @since v1.0.0 */ setCredentials( credentials: Partial<ICredentials>, ): Promise<IRefreshTokenResult>; /** * @public * `📱 SOCLE 📱` * #### 📡 Get credentials when you're already logged 📡 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (!nabii.v1.Auth.isLogged()) { * throw new Error("Not logged!"); * } * const { * accessToken, * refreshToken, * user * } = await nabii.v1.Auth.getCredentials(); * ``` * @returns the {@link ICredentials} object * @since v1.0.0 */ getCredentials(): IIsLogged<this> extends true ? ICredentials : ICredentials | IEmptyCredentials; /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if your are connected to {@link NabiiV1} API 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Auth.isLogged()) { * console.log("I am logged!"); * const { user } = nabii.v1.Auth.getCredentials(); * console.log(`Hello ${user.firstName}!`); * } * ``` * @returns a `boolean` at true if you are logged * @since v1.0.0 */ isLogged(): this is ILogged; /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if your are connected to {@link NabiiV1} API as `administrator` 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Auth.isAdmin()) { * console.log("I am logged as administrator!"); * const { user } = nabii.v1.Auth.getCredentials(); * console.log(`Hello ${user.firstName}!`); * } * ``` * @returns a `boolean` at true if you are logged as administrator * @since v1.0.0 */ isAdmin(): this is ILogged; /** * `📱 SOCLE 📱` * #### ☝️ Get connected {@link IUser} object ☝️ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { email } = await nabii.v1.Auth.me(); * console.log(email); //"my-email@domain.com" * ``` * @returns the connected {@link IUser} object * @since v1.0.0 */ me(): Promise<IUser<Platform.APPLICATION>>; /** * @public * `📱 SOCLE 📱` * #### 🛌 Logout from {@link NabiiV1} 🛌 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * await nabii.v1.Auth.logout(); * ``` * @returns a void function * @since v1.0.0 */ logout(): Promise<void>; /** * @public * `📱 SOCLE 📱` `🖥️ ADMIN 🖥️` * #### ♻️ Receive an email to reset your password ♻️ * @param email your email address to receive an email * @example * ```tsx * import { nabii } from "nabii-sdk"; * * await nabii.v1.Auth.forgotPassword(myEmail); // {...} * ``` * @returns the {@link IEmailSentResult} object result of email receive * @since v1.0.0 */ forgotPassword(email: string): Promise<IEmailSentResult>; /** * `📱 SOCLE 📱` * #### ♻️ Callback email creation to get another email sent ♻️ * @param token your email link `JWT` request token * @param subject the subject of the email: {@link IEmailSubject} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/reset-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * const {tokenIsValid} = await nabii.v1.Auth.checkTokenValidity(token, "forgotPassword"); // true | false * ``` * @returns the {@link ICheckTokenResponseType} object representing the token validity and user information. * @since v1.0.0 */ checkTokenValidity( token: string, subject: IEmailSubject, ): Promise<ICheckTokenResponseType>; /** * `📱 SOCLE 📱` * #### ✅ Activate your {@link NabiiV1} account when you have changed your email ✅ * @param token your email link `JWT` request token with subject `"activateAccount"` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/activate-account?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "activateAccount")) { * await nabii.v1.Auth.activateAccount(token); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ activateAccount(token: string): Promise<IUserUpdatedResult>; /** * `📱 SOCLE 📱` * #### 💾 Set your new {@link NabiiV1} account password 💾 * @param token your email link `JWT` request token with subject `"activateAccountInvite"` * @param password the new password of your {@link NabiiV1} account * - must contain at least `8 characters` * - must contain a maximum of `64 characters` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/set-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "activateAccountInvite")) { * const password = "@TestNabii1"; * await nabii.v1.Auth.setPassword(token, password); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ setPassword(token: string, password: string): Promise<IUserUpdatedResult>; /** * `📱 SOCLE 📱` * #### ♻️ Reset your {@link NabiiV1} account password ♻️ * @param token your email link `JWT` request token with subject `"forgotPassword"` * @param newPassword the new password of your {@link NabiiV1} account * - must contain at least `8 characters` * - must contain a maximum of `64 characters` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/reset-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "forgotPassword")) { * const password = "@TestNabii1"; * await nabii.v1.Auth.resetPassword(token, password); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ resetPassword( token: string, newPassword: string, ): Promise<IUserUpdatedResult>; } /** * #### Load mixin interfaces * * *This utility type takes a record of classes and returns a new type where each key in the record is * mapped to an instance of the corresponding class. This is useful for loading and working with * multiple module instances in a type-safe manner.* * * @template T - A record where the key is a string and the value is a class constructor. * * @example * ```typescript * import { MyClass1, MyClass2 } from '@v1/modules'; * * type IObject = { * class1: typeof MyClass1; * class2: typeof MyClass2; * }; * * type ILoadedModules = ILoadModules<IObject>; * // ILoadedModules is now { class1: MyClass1; class2: MyClass2; } * ``` */ declare type ILoadModules<T extends Record<string, IClass>> = { [key in keyof T]: InstanceType<T[key]>; }; /** * #### Apply interface `Admin` mixin to a module * * *This abstract class is used to apply an `Admin` mixin to a module. It extends `BaseV1` and * ensures that the module includes the properties and methods of the `Admin` class.* * * @template T - The type of administrator constructor, which should extend from the `IClass` type. * * @extends BaseV1 * * @example * * ```tsx * class ModuleV1 { * // administrator methods and properties! * readonly Admin: new AdminModuleV1(); * } * ``` */ declare abstract class AdminMixin<T extends IClass> extends BaseV1 { /** * ##### 🖥️ Administrator `methods` and `properties` of this module 🖥️ * * *An instance of the `Admin` class, which provides additional methods and properties * specific to administrative functionality of this module.* * * @readonly * * @example * ```tsx * class ModuleV1 { * // administrator methods and properties! * readonly Admin: new AdminModuleV1(); * } * ``` */ readonly Admin: InstanceType<T>; } /** * @class {@link AdminUserV1} * @since v1.0.0 * @extends {BaseV1} */ declare class AdminUserV1 extends BaseV1 { /** * `🖥️ ADMIN 🖥️` * #### 📚 Get all pending {@link NabiiV1} user} 📚 * @param params set request query {@link IPaginateOptions} (optional) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { data } = await nabii.v1.User.Admin.getAllPending(); // [...] * ``` * @returns a {@link IPaginated} object of {@link IUser} * @since v1.0.0 */ getAllPending< TSearch extends string | undefined = undefined, TLimit extends number = 15, TPage extends number = 1, >( params?: IUserParams<Platform.ADMIN, TSearch, TLimit, TPage>, ): Promise<IPaginated<IUser<Platform.ADMIN>, TSearch, TLimit, TPage>>; /** * `🖥️ ADMIN 🖥️` * #### 📚 Get all {@link NabiiV1} {@link IUser} 📚 * @param params set request query {@link IPaginateOptions} (optional) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { data } = await nabii.v1.User.Admin.getAll(); // [...] * ``` * @returns a {@link IPaginated} object of {@link IUser} * @since v1.0.0 */ getAll< TSearch extends string | undefined = undefined, TLimit extends number = 15, TPage extends number = 1, >( params?: IUserParams<Platform.ADMIN, TSearch, TLimit, TPage>, ): Promise<IPaginated<IUser<Platform.ADMIN>, TSearch, TLimit, TPage>>; /** * `🖥️ ADMIN 🖥️` * #### 📖 Retrieve a {@link NabiiV1} {@link IUser} by `primary key` 📖 * @param pk the {@link IUser} `primary key` you want to retrieve * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.getByPk(pk); // {...} * ``` * @returns an {@link IUser} object or `null` * @since v1.0.0 */ getByPk( pk: Infer.PrimaryKey<IUser<Platform.ADMIN>>, ): Promise<IUser<Platform.ADMIN> | null>; /** * `🖥️ ADMIN 🖥️` * #### 🆕 Create a new {@link NabiiV1} {@link IUser} 🆕 * @param data user data to create * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.create({ * firstName : "MyName", * lastName: "MyLastName", * email: "email@domain.com", * }); // {...} * ``` * @returns the created {@link IUser} object * @since v1.0.0 */ create(data: ICreateUserForm<Platform.ADMIN>): Promise<IUser<Platform.ADMIN>>; /** * `🖥️ ADMIN 🖥️` * #### 🔄 Update {@link NabiiV1} {@link IUser} by `primary key` 🔄 * @param pk the {@link IUser} `primary key` you want to update * @param data user data to update * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.update( * pk, * { * firstName: "updatedName" * } * ); // {...} * ``` * @returns the updated {@link IUser} object * @since v1.0.0 */ update( pk: Infer.PrimaryKey<IUser<Platform.ADMIN>>, data: IUpdateUserForm<Platform.ADMIN>, ): Promise<IUser<Platform.ADMIN>>; /** * `🖥️ ADMIN 🖥️` * #### 🗑️ Delete a {@link NabiiV1} {@link IUser} by `primary key` 🗑️ * @param pk the {@link IUser} `primary key` you want to delete * @example * ```tsx * import { nabii } from "nabii-sdk"; * * await nabii.v1.User.Admin.delete(pk); * ``` * @returns a void function * @since v1.0.0 */ delete(pk: Infer.PrimaryKey<IUser<Platform.ADMIN>>): Promise<void>; /** * `🖥️ ADMIN 🖥️` * #### 🔄 Update {@link NabiiV1} {@link IUser} `role` by `primary key` 🔄 * @param pk the {@link IUser} `primary key` you want to update * @param newRole the new {@link IRole} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.updateRole( * pk, * nabii.v1.User.roles.ADMIN * ); // {...} * ``` * @returns the updated {@link IUser} object * @since v1.0.0 */ updateRole( pk: Infer.PrimaryKey<IUser<Platform.ADMIN>>, newRole: IRole, ): Promise<IUser<Platform.ADMIN>>; /** * `🖥️ ADMIN 🖥️` * #### 📚 Get all {@link NabiiV1} administrator {@link IUser} 📚 * @param params set request query {@link IPaginateOptions} (optional) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { data } = await nabii.v1.User.Admin.getAll(); // [...] * ``` * @returns a {@link IPaginated} object of {@link IUser} * @since v1.0.0 */ getAllAdmins< TSearch extends string | undefined = undefined, TLimit extends number = 15, TPage extends number = 1, >( params?: IUserParams<Platform.ADMIN, TSearch, TLimit, TPage>, ): Promise<IPaginated<IUser<Platform.ADMIN>, TSearch, TLimit, TPage>>; /** * `🖥️ ADMIN 🖥️` * #### ⤴️ Export all your users as excel file ⤴️ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const attachment = await nabii.v1.User.Admin.export(); // "<html>...</html>" * ``` * @returns the attachment `xls` file as `string` * @since v1.0.0 */ export(): Promise<string>; /** * `🖥️ ADMIN 🖥️` * #### ⤵️ Import many users ⤵️ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { succeed, failed } = await nabii.v1.User.Admin.import([ * { * firstName: "...", * lastName: