/** * Account Manager API client for B2C Commerce. * * Provides clients for the Account Manager REST APIs including users, roles, and organizations. * Uses openapi-fetch with OAuth authentication middleware for users and roles, * and fetch with OAuth for organizations. * * @module clients/am-api */ import { type Client } from 'openapi-fetch'; import type { AuthStrategy } from '../auth/types.js'; import type { paths as UsersPaths, components as UsersComponents, operations as UsersOperations } from './am-users-api.generated.js'; import type { paths as RolesPaths, components as RolesComponents } from './am-roles-api.generated.js'; import type { paths as ApiClientsPaths, components as ApiClientsComponents, operations as ApiClientsOperations } from './am-apiclients-api.generated.js'; import { type MiddlewareRegistry } from './middleware-registry.js'; /** * Regex for Account Manager role tenant filter format: * ROLE_ENUM:realm_instance(,realm_instance)*(;ROLE_ENUM:...)* * e.g. SALESFORCE_COMMERCE_API:abcd_prd or bm-admin:tenant1,tenant2;ECOM_USER:wxyz_stg */ export declare const ROLE_TENANT_FILTER_PATTERN: RegExp; /** * Validates whether a string matches the Account Manager role tenant filter format. * * Format: `ROLE_ENUM:realm_instance(,realm_instance)*(;ROLE_ENUM:...)*` * Examples: `SALESFORCE_COMMERCE_API:abcd_prd` or `bm-admin:tenant1,tenant2;ECOM_USER:wxyz_stg` * * @param value - The string to validate * @returns True if the value matches the role tenant filter format, false otherwise */ export declare function isValidRoleTenantFilter(value: string): boolean; /** * The typed Account Manager Users client - this is the openapi-fetch Client with full type safety. * * @see {@link createAccountManagerUsersClient} for instantiation */ export type AccountManagerUsersClient = Client; /** * Helper type to extract response data from an operation. */ export type AccountManagerResponse = T extends { content: { 'application/json': infer R; }; } ? R : never; /** * Account Manager error response type from the generated schema. */ export type AccountManagerError = UsersComponents['schemas']['ErrorResponse']; /** * User type from the generated schema. */ export type AccountManagerUser = UsersComponents['schemas']['UserRead']; export type UserCreate = UsersComponents['schemas']['UserCreate']; export type UserUpdate = UsersComponents['schemas']['UserUpdate']; /** * Expand parameter type for user operations. * Extracted from the generated API types to ensure consistency. */ export type UserExpandOption = NonNullable['expand']>[number]; export type UserCollection = UsersComponents['schemas']['UserCollection']; export type UserState = 'INITIAL' | 'ENABLED' | 'DELETED'; /** * Options for listing users. */ export interface ListUsersOptions { /** Page size (default: 20, min: 1, max: 4000) */ size?: number; /** Page number (default: 0) */ page?: number; } /** * Role mapping built from the Account Manager roles API. * Maps between role `id` (e.g., `bm-admin`) and `roleEnumName` (e.g., `ECOM_ADMIN`). */ export interface RoleMapping { /** Maps role id (e.g., 'bm-admin') to roleEnumName (e.g., 'ECOM_ADMIN') */ byId: Map; /** Maps roleEnumName (e.g., 'ECOM_ADMIN') to role id (e.g., 'bm-admin') */ byEnumName: Map; /** Maps roleEnumName (e.g., 'ECOM_ADMIN') to description (e.g., 'Business Manager Administrator') */ descriptions: Map; } /** * Organization mapping built from the Account Manager organizations API. * Maps organization ID to name. */ export interface OrgMapping { /** Maps organization ID to name */ byId: Map; } /** * Fetches all roles from the Account Manager roles API and builds a mapping * between role `id` and `roleEnumName`. * * @param rolesClient - Account Manager Roles client * @returns Role mapping */ export declare function fetchRoleMapping(rolesClient: AccountManagerRolesClient): Promise; /** * Resolves a role to its internal `roleEnumName` using an API-fetched role mapping. * Accepts either the role `id` (e.g., `bm-admin`) or `roleEnumName` (e.g., `ECOM_ADMIN`). * Falls back to a generic transform (uppercase + replace hyphens with underscores) for unknown roles. */ export declare function resolveToInternalRole(role: string, mapping: RoleMapping): string; /** * Resolves an internal `roleEnumName` to its external role `id` using an API-fetched role mapping. * Falls back to a generic transform (lowercase + replace underscores with hyphens) for unknown roles. */ export declare function resolveFromInternalRole(roleEnumName: string, mapping: RoleMapping): string; /** * Configuration for creating Account Manager clients. * Used for all Account Manager API clients (users, roles, orgs). */ export interface AccountManagerClientConfig { /** * Account Manager hostname. * Defaults to: account.demandware.com * * @example "account.demandware.com" */ hostname?: string; /** * Middleware registry to use for this client. * If not specified, uses the global middleware registry. */ middlewareRegistry?: MiddlewareRegistry; } /** * Creates a typed Account Manager Users API client. * * Returns the openapi-fetch client directly, with authentication * handled via middleware. This gives full access to all openapi-fetch * features with type-safe paths, parameters, and responses. * * @param config - Account Manager Users client configuration * @param auth - Authentication strategy (typically OAuth) * @returns Typed openapi-fetch client * * @example * // Create Account Manager Users client with OAuth auth * const oauthStrategy = new OAuthStrategy({ * clientId: 'your-client-id', * clientSecret: 'your-client-secret', * }); * * const client = createAccountManagerUsersClient({}, oauthStrategy); * * // List users * const { data, error } = await client.GET('/dw/rest/v1/users', { * params: { query: { pageable: { size: 25, page: 0 } } } * }); */ export declare function createAccountManagerUsersClient(config: AccountManagerClientConfig, auth: AuthStrategy): AccountManagerUsersClient; /** * Retrieves details of a user by ID. * * @param client - Account Manager Users client * @param userId - User ID (UUID) * @param expand - Optional array of fields to expand (organizations, roles) * @returns User details * @throws Error if user is not found or request fails */ export declare function getUser(client: AccountManagerUsersClient, userId: string, expand?: UserExpandOption[]): Promise; /** * Lists users with pagination. * * @param client - Account Manager Users client * @param options - List options (size, page) * @returns Paginated user collection * @throws Error if request fails */ export declare function listUsers(client: AccountManagerUsersClient, options?: ListUsersOptions): Promise; /** * Creates a new user. * * @param client - Account Manager Users client * @param user - User details * @returns Created user * @throws Error if request fails */ export declare function createUser(client: AccountManagerUsersClient, user: UserCreate): Promise; /** * Updates an existing user. * * @param client - Account Manager Users client * @param userId - User ID * @param changes - Changes to apply * @returns Updated user * @throws Error if request fails */ export declare function updateUser(client: AccountManagerUsersClient, userId: string, changes: UserUpdate): Promise; /** * Disables a user (soft delete - sets userState to DELETED). * Users must be disabled before they can be purged. * * @param client - Account Manager Users client * @param userId - User ID * @throws Error if request fails */ export declare function deleteUser(client: AccountManagerUsersClient, userId: string): Promise; /** * Purges a user (hard delete). * Users must be in DELETED state before they can be purged. * * @param client - Account Manager Users client * @param userId - User ID * @throws Error if request fails */ export declare function purgeUser(client: AccountManagerUsersClient, userId: string): Promise; /** * Resets a user to INITIAL state and sends activation instructions. * * @param client - Account Manager Users client * @param userId - User ID * @throws Error if request fails */ export declare function resetUser(client: AccountManagerUsersClient, userId: string): Promise; /** * Finds a user by login (email) using the dedicated search endpoint. * * @param client - Account Manager Users client * @param login - User login (email) * @param expand - Optional array of fields to expand (organizations, roles) * @returns User if found, undefined if not found * @throws Error if request fails */ export declare function findUserByLogin(client: AccountManagerUsersClient, login: string, expand?: UserExpandOption[]): Promise; /** * The typed Account Manager Roles client - this is the openapi-fetch Client with full type safety. * * @see {@link createAccountManagerRolesClient} for instantiation */ export type AccountManagerRolesClient = Client; /** * Helper type to extract response data from an operation. */ export type AccountManagerRolesResponse = T extends { content: { 'application/json': infer R; }; } ? R : never; /** * Account Manager Roles error response type from the generated schema. */ export type AccountManagerRolesError = RolesComponents['schemas']['ErrorResponse']; /** * Role type from the generated schema. */ export type AccountManagerRole = RolesComponents['schemas']['Role']; export type RoleCollection = RolesComponents['schemas']['RoleCollection']; /** * Options for listing roles. */ export interface ListRolesOptions { /** Page size (default: 20, min: 1, max: 4000) */ size?: number; /** Page number (default: 0) */ page?: number; /** Filter by target type (User or ApiClient) */ roleTargetType?: 'ApiClient' | 'User'; } /** * Creates a typed Account Manager Roles API client. * * Returns the openapi-fetch client directly, with authentication * handled via middleware. This gives full access to all openapi-fetch * features with type-safe paths, parameters, and responses. * * @param config - Account Manager Roles client configuration * @param auth - Authentication strategy (typically OAuth) * @returns Typed openapi-fetch client * * @example * // Create Account Manager Roles client with OAuth auth * const oauthStrategy = new OAuthStrategy({ * clientId: 'your-client-id', * clientSecret: 'your-client-secret', * }); * * const client = createAccountManagerRolesClient({}, oauthStrategy); * * // List roles * const { data, error } = await client.GET('/dw/rest/v1/roles', { * params: { query: { pageable: { size: 25, page: 0 } } } * }); */ export declare function createAccountManagerRolesClient(config: AccountManagerClientConfig, auth: AuthStrategy): AccountManagerRolesClient; /** * Retrieves details of a role by ID. * * @param client - Account Manager Roles client * @param roleId - Role ID * @returns Role details * @throws Error if role is not found or request fails */ export declare function getRole(client: AccountManagerRolesClient, roleId: string): Promise; /** * Lists roles with pagination. * * @param client - Account Manager Roles client * @param options - List options (size, page, roleTargetType) * @returns Paginated role collection * @throws Error if request fails */ export declare function listRoles(client: AccountManagerRolesClient, options?: ListRolesOptions): Promise; /** * The typed Account Manager API Clients client - this is the openapi-fetch Client with full type safety. * * @see {@link createAccountManagerApiClientsClient} for instantiation */ export type AccountManagerApiClientsClient = Client; /** * API client type from the generated schema (read operations). */ export type AccountManagerApiClient = ApiClientsComponents['schemas']['APIClientRead']; export type APIClientCreate = ApiClientsComponents['schemas']['APIClientCreate']; export type APIClientUpdate = ApiClientsComponents['schemas']['APIClientUpdate']; export type APIClientCollection = ApiClientsComponents['schemas']['APIClientCollection']; /** * Expand parameter type for API client get operation. */ export type ApiClientExpandOption = NonNullable['expand']>[number]; /** * Options for listing API clients. */ export interface ListApiClientsOptions { /** Page size (default: 20, min: 1, max: 4000) */ size?: number; /** Page number (default: 0) */ page?: number; } /** * Creates a typed Account Manager API Clients API client. * * @param config - Account Manager client configuration * @param auth - Authentication strategy (typically OAuth) * @returns Typed openapi-fetch client for API Clients API */ export declare function createAccountManagerApiClientsClient(config: AccountManagerClientConfig, auth: AuthStrategy): AccountManagerApiClientsClient; /** * Lists API clients with pagination. */ export declare function listApiClients(client: AccountManagerApiClientsClient, options?: ListApiClientsOptions): Promise; /** * Retrieves an API client by ID. * * @param client - Account Manager API Clients client instance * @param apiClientId - ID of the API client to retrieve * @param expand - Optional array of fields to expand in the response * @returns Promise resolving to the API client details * @throws Error if the API client is not found (404) or if the request fails */ export declare function getApiClient(client: AccountManagerApiClientsClient, apiClientId: string, expand?: ApiClientExpandOption[]): Promise; /** * Creates a new API client. * Omits active when false so the API uses its default (inactive); some implementations * reject or mishandle explicit active: false and return "invalid argument APIClient". */ export declare function createApiClient(client: AccountManagerApiClientsClient, body: APIClientCreate): Promise; /** * Updates an existing API client. * * @param client - Account Manager API Clients client * @param apiClientId - API client ID to update * @param body - API client update data * @returns Updated API client * @throws Error if request fails or if the request body contains validation errors */ export declare function updateApiClient(client: AccountManagerApiClientsClient, apiClientId: string, body: APIClientUpdate): Promise; /** * Deletes an API client. Only clients disabled for at least 7 days can be deleted. */ export declare function deleteApiClient(client: AccountManagerApiClientsClient, apiClientId: string): Promise; /** * Changes the password for an API client. */ export declare function changeApiClientPassword(client: AccountManagerApiClientsClient, apiClientId: string, oldPassword: string, newPassword: string): Promise; /** * Account Manager Organization type. */ export interface AccountManagerOrganization { id: string; name: string; realms: string[]; twoFARoles: string[]; twoFAEnabled: boolean; allowedVerifierTypes: string[]; vaasEnabled: boolean; sfIdentityFederation: boolean; [key: string]: unknown; } /** * Account Manager Organization collection response. */ export interface OrganizationCollection { content: AccountManagerOrganization[]; totalElements?: number; totalPages?: number; number?: number; size?: number; [key: string]: unknown; } /** * Options for listing organizations. */ export interface ListOrgsOptions { /** Page size (default: 25, max: 5000) */ size?: number; /** Page number (0-based, default: 0) */ page?: number; /** Return all orgs (uses max page size of 5000) */ all?: boolean; } /** * Account Manager Organizations API client. */ export interface AccountManagerOrgsClient { /** * Get organization by ID. */ getOrg(orgId: string): Promise; /** * Get organization by name (searches for exact or partial match). */ getOrgByName(name: string): Promise; /** * List organizations with pagination. */ listOrgs(options?: ListOrgsOptions): Promise; } /** * Creates an Account Manager Organizations API client. * * @param config - Account Manager Organizations client configuration * @param auth - Authentication strategy (typically OAuth) * @returns Organizations API client * * @example * const oauthStrategy = new OAuthStrategy({ * clientId: 'your-client-id', * clientSecret: 'your-client-secret', * }); * * const client = createAccountManagerOrgsClient({}, oauthStrategy); * * // List organizations * const orgs = await client.listOrgs({ size: 25, page: 0 }); * * // Get organization by ID * const org = await client.getOrg('org-id'); */ export declare function createAccountManagerOrgsClient(config: AccountManagerClientConfig, auth: AuthStrategy): AccountManagerOrgsClient; /** * Unified Account Manager API client that combines users, roles, and organizations. * * This client provides direct access to all Account Manager API methods through * a single interface, while internally using separate typed clients for type safety. */ export interface AccountManagerClient { /** Get user by ID */ getUser(userId: string, expand?: UserExpandOption[]): Promise; /** List users with pagination */ listUsers(options?: ListUsersOptions): Promise; /** Create a new user */ createUser(user: UserCreate): Promise; /** Update an existing user */ updateUser(userId: string, changes: UserUpdate): Promise; /** Disable a user (soft delete) */ deleteUser(userId: string): Promise; /** Purge a user (hard delete) */ purgeUser(userId: string): Promise; /** Reset a user to INITIAL state */ resetUser(userId: string): Promise; /** Find a user by login (email) */ findUserByLogin(login: string, expand?: UserExpandOption[]): Promise; /** Grant a role to a user, optionally with scope */ grantRole(userId: string, role: string, scope?: string): Promise; /** Revoke a role from a user, optionally removing specific scope */ revokeRole(userId: string, role: string, scope?: string): Promise; /** Get role by ID */ getRole(roleId: string): Promise; /** List roles with pagination */ listRoles(options?: ListRolesOptions): Promise; /** Get the role mapping (id ↔ roleEnumName), lazily cached */ getRoleMapping(): Promise; /** Get the org mapping (id → name), lazily cached */ getOrgMapping(): Promise; /** List API clients with pagination */ listApiClients(options?: ListApiClientsOptions): Promise; /** Get API client by ID */ getApiClient(apiClientId: string, expand?: ApiClientExpandOption[]): Promise; /** Create a new API client */ createApiClient(body: APIClientCreate): Promise; /** Update an existing API client */ updateApiClient(apiClientId: string, body: APIClientUpdate): Promise; /** Delete an API client (must be disabled 7+ days) */ deleteApiClient(apiClientId: string): Promise; /** Change an API client password */ changeApiClientPassword(apiClientId: string, oldPassword: string, newPassword: string): Promise; /** Get organization by ID */ getOrg(orgId: string): Promise; /** Get organization by name */ getOrgByName(name: string): Promise; /** List organizations with pagination */ listOrgs(options?: ListOrgsOptions): Promise; } /** * Creates a unified Account Manager API client. * * This client provides direct access to all Account Manager API methods (users, roles, orgs) * through a single interface, while internally using separate typed clients for type safety. * * @param config - Account Manager client configuration * @param auth - Authentication strategy (typically OAuth) * @returns Unified Account Manager client * * @example * const oauthStrategy = new OAuthStrategy({ * clientId: 'your-client-id', * clientSecret: 'your-client-secret', * }); * * const client = createAccountManagerClient({}, oauthStrategy); * * // Users API * const users = await client.listUsers({ size: 25, page: 0 }); * const user = await client.getUser('user-id'); * await client.createUser({ mail: 'user@example.com', ... }); * * // Roles API * const roles = await client.listRoles({ size: 20, page: 0 }); * const role = await client.getRole('bm-admin'); * * // Organizations API * const orgs = await client.listOrgs({ size: 25, page: 0 }); * const org = await client.getOrg('org-id'); */ export declare function createAccountManagerClient(config: AccountManagerClientConfig, auth: AuthStrategy): AccountManagerClient;