/**
 * @public
 * Options for requesting an access token for the current user.
 */
export declare type AccessTokenRequest = {
  /**
   * If `true`, the access token will be refreshed, even if it hasn't expired.
   *
   * @remarks
   * By default, access tokens are automatically refreshed after expiry.
   */
  forceRefresh?: boolean;
  /**
   * The scopes associated with the access token.
   */
  scope?: Set<string>;
};

/**
 * @public
 * The result of requesting an access token for the current user.
 *
 * @remarks
 * This is `null` when the current user doesn't have an access token.
 */
export declare type AccessTokenResponse = {
  /**
   * The access token for the current user.
   */
  token: string;
  /**
   * The scopes associated with the current user's access token.
   */
  scope: Set<string>;
} | null;

/**
 * An alias for the Authentication interface, providing access to authentication related functionality
 * @public
 */
export declare const auth: Authentication;

/**
 * @public
 * Provides methods for authenticating users within apps.
 */
export declare interface Authentication {
  /**
   * @public
   * Returns a JSON Web Token (JWT) that contains information about the current user.
   *
   * @remarks
   * This token must be decoded and verified via the app's backend.
   *
   * The verified token is an object with the following properties:
   *
   * - `appId` - The ID of the app.
   * - `teamId` - The ID of the user's team.
   * - `userId` - The ID of the user.
   *
   *  To learn how to decode and verify JWTs, see [JSON Web Tokens](https://www.canva.dev/docs/apps/verifying-jwts/).
   */
  getCanvaUserToken: () => Promise<CanvaUserToken>;

  /**
   * @public
   * Creates a client for authenticating users with OAuth.
   *
   * @remarks
   * To learn more, see {@link https://www.canva.dev/docs/apps/authenticating-users/oauth}.
   *
   * @example
   * ```ts
   * import { auth } from "@canva/user";
   *
   * // Initialize an OAuth client
   * const oauth = auth.initOauth();
   *
   * // Check if the user has a token
   * const token = await oauth.getAccessToken();
   *
   * // If an access token is available, the user is authorized
   * if (token) {
   *  // Use the token to implement behavior that requires authorization
   *  console.log(token);
   * } else {
   *  // Otherwise, start an authorization flow
   *  const response = await oauth.requestAuthorization();
   *
   *  if (response.status === "complete") {
   *    // The user successfully authorized
   *    // The app can now get the user's access token
   *  } else {
   *    // The user did not successfully authorize
   *  }
   * }
   * ```
   */
  initOauth(): Oauth;
}

/**
 * @public
 * The result when a user fails to complete an OAuth authorization flow.
 */
declare type AuthorizationAborted = {
  /**
   * The status of the authorization flow.
   */
  status: "aborted";
};

/**
 * @public
 * The result when a user successfully completes an OAuth authorization flow.
 */
declare type AuthorizationCompleted = {
  /**
   * The status of the authorization flow.
   */
  status: "completed";
  /**
   * The scopes associated with the user.
   */
  scope: Set<string>;
};

/**
 * @public
 * Options for authorizing a user with OAuth.
 */
export declare type AuthorizationRequest<T extends Record<string, string>> = {
  /**
   * Query parameters to append to the URL of the request.
   */
  queryParams?: ExcludeKeys<T, ForbiddenKey>;
  /**
   * The list of scopes to request access to.
   */
  scope?: Set<string>;
};

/**
 * @public
 * The result of an OAuth authorization flow.
 */
export declare type AuthorizationResponse =
  | AuthorizationCompleted
  | AuthorizationAborted;

/** @public */
declare interface BaseCanvaError extends Error {
  code: ErrorCode;
}

/**
 * @public
 * An error thrown by the Apps SDK.
 */
declare class CanvaErrorClass extends Error implements BaseCanvaError {
  /**
   * A code that identifies why the error was thrown.
   */
  readonly code: ErrorCode;

  constructor(opts: { code: ErrorCode; message: string });
}

/**
 * @public
 * A JSON Web Token (JWT) that contains information about the current user.
 */
export declare type CanvaUserToken = string & {
  __canvaUserToken: never;
};

/**
 * @public
 * An error code that identifies why an error was thrown by the Apps SDK.
 *
 * @remarks
 * The possible error codes include:
 *
 * - `"bad_external_service_response"` - A response from an external service is invalid or malformed.
 * - `"bad_request"` - The app made a request with invalid or malformed inputs.
 * - `"failed_precondition"` - The requested operation can't be performed because a precondition hasn't been met.
 * - `"internal_error"` - An error occurred within the Apps SDK's internal implementation.
 * - `"not_found"` - The specified resource couldn't be found.
 * - `"not_allowed"` - The app isn't allowed to perform the requested operation.
 * - `"permission_denied"` - The app isn't allowed perform the requested operation because the appropriate permissions aren't set.
 * - `"quota_exceeded"` - The app or user has exceeded their allocated quota for a resource or service.
 * - `"rate_limited"` - The app attempted too many operations within a certain period of time.
 * - `"timeout"` - The requested operation took too long to complete.
 * - `"unsupported_surface"` - The requested operation isn't supported on the current surface.
 * - `"unsupported_page_type"` - The requested operation isn't supported on the current page.
 * - `"user_offline"` - The requested operation can't be performed because the user is offline.
 */
declare type ErrorCode =
  | "bad_external_service_response"
  | "bad_request"
  | "failed_precondition"
  | "internal_error"
  | "not_found"
  | "not_allowed"
  | "permission_denied"
  | "quota_exceeded"
  | "rate_limited"
  | "timeout"
  | "unsupported_surface"
  | "unsupported_page_type"
  | "user_offline";

declare type ExcludeKeys<T extends object, Keys> = {
  [K in keyof T]: K extends Keys ? never : T[K];
};

/**
 * @public
 * A key that can't be used as a query parameter in an OAuth request.
 *
 * @remarks
 * A key is forbidden when it's already used by Canva.
 */
export declare type ForbiddenKey =
  | "client_id"
  | "redirect_uri"
  | "scope"
  | "state"
  | "response_type"
  | "code_challenge"
  | "code_challenge_method"
  | "client_secret";

/**
 * @public
 * A client for authorizing users with OAuth.
 */
export declare interface Oauth {
  /**
   * @public
   * Starts an OAuth authorization flow.
   *
   * @param request - Options for configuring the authorization flow.
   *
   * @returns
   * The result of the authorization flow.
   *
   * @example
   * ```ts
   * import { auth } from "@canva/user";
   *
   * // Initialize an OAuth client
   * const oauth = auth.initOauth();
   *
   * // Start an authorization flow
   * const response = await oauth.requestAuthorization();
   * console.log(response);
   * ```
   */
  requestAuthorization<T extends Record<string, string>>(
    request?: AuthorizationRequest<T>,
  ): Promise<AuthorizationResponse>;
  /**
   * @public
   * Gets the access token and scopes for the current user.
   *
   * @param request - Options for requesting an access token for the current user.
   *
   * @returns
   * The access token and scopes for the current user, or `null` if the user isn't authorized.
   *
   * @remarks
   * - When a token expires, it's automatically refreshed by Canva.
   * - The token is cached by Canva, so the app's frontend shouldn't store the token.
   *
   * @example
   * ```ts
   * import { auth } from "@canva/user";
   *
   * // Initialize an OAuth client
   * const oauth = auth.initOauth();
   *
   * // Get an access token for the user
   * const token = await oauth.getAccessToken();
   *
   * // If a token isn't available, the user isn't authorized
   * if (token) {
   *  // The user is authorized
   *  console.log(token);
   * } else {
   *  console.log("The user is not authorized.");
   * }
   *
   * ```
   */
  getAccessToken(request?: AccessTokenRequest): Promise<AccessTokenResponse>;
  /**
   * @public
   * Disconnects the user from the identity provider (IdP).
   *
   * @returns
   * An empty `Promise` that resolves once the user is disconnected from the IdP.
   *
   * @remarks
   * If token revocation is supported by the OAuth provider, the refresh and access tokens will be revoked.
   *
   * @example
   * ```ts
   * import { auth } from "@canva/user";
   *
   * // Initialize an OAuth client
   * const oauth = auth.initOauth();
   *
   * // Disconnect the user from the IdP
   * await oauth.deauthorize();
   * ```
   */
  deauthorize(): Promise<void>;
}

/**
 * @public
 * An error that may occur during an OAuth authorization flow.
 */
export declare const OauthError: typeof OauthErrorClass;

/**
 * @public
 * An error that may occur during an OAuth authorization flow.
 */
declare class OauthErrorClass extends CanvaErrorClass {
  readonly oauthCode: OauthErrorCode;
  readonly uri: string | undefined;
  readonly rawMessage: string;
  constructor(
    oauthCode: OauthErrorCode,
    message: string | undefined,
    uri: string | undefined,
  );
}

/**
 * @public
 * An error code that indicates why an error has occurred during an OAuth authorization flow.
 *
 * @remarks
 * The possible error codes include:
 *
 * - `"invalid_request"` - The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.
 * - `"access_denied"` - The resource owner or authorization server denied the request.
 * - `"unauthorized_client"` - The client is not authorized to request an authorization code using this method.
 * - `"invalid_client"` - Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).
 * - `"invalid_scope"` - The requested scope is invalid, unknown, or malformed.
 * - `"invalid_grant"` - The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.
 * - `"unsupported_response_type"` - The authorization server does not support obtaining an authorization code using this method.
 * - `"unsupported_grant_type"` - The authorization grant type is not supported by the authorization server.
 * - `"unsupported_token_type"` - The authorization server does not support the requested token type.
 * - `"server_error"` - The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
 * - `"temporarily_unavailable"` - The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
 * - `"bad_server_response"` - The authorization server returned an invalid response.
 * - `"other_error"` - An error occurred during the OAuth flow.
 */
export declare type OauthErrorCode =
  | "invalid_request"
  | "access_denied"
  | "unauthorized_client"
  | "invalid_client"
  | "invalid_scope"
  | "invalid_grant"
  | "unsupported_response_type"
  | "unsupported_grant_type"
  | "unsupported_token_type"
  | "server_error"
  | "temporarily_unavailable"
  | "bad_server_response"
  | "other_error";

/**
 * @public
 * A JSON Web Token (JWT) that contains information about the current user and their premium access.
 *
 * @remarks
 * This is a {@link CanvaUserToken} with an additional `experimentalPremiumAccess` claim.
 */
export declare type UserCapabilitiesToken = string & {
  _userCapabilitiesToken: never;
};

export {};
