/*! @azure/msal-common v16.6.2 2026-05-19 */
'use strict';
import { RESOURCE_DELIM } from './Constants.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { noCryptoObject, invalidState } from '../error/ClientAuthErrorCodes.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
/**
 * Appends user state with random guid, or returns random guid.
 * @param cryptoObj
 * @param userState
 * @param meta
 */
function setRequestState(cryptoObj, userState, meta) {
    const libraryState = generateLibraryState(cryptoObj, meta);
    return userState
        ? `${libraryState}${RESOURCE_DELIM}${userState}`
        : libraryState;
}
/**
 * Generates the state value used by the common library.
 * @param cryptoObj
 * @param meta
 */
function generateLibraryState(cryptoObj, meta) {
    if (!cryptoObj) {
        throw createClientAuthError(noCryptoObject);
    }
    // Create a state object containing a unique id and the timestamp of the request creation
    const stateObj = {
        id: cryptoObj.createNewGuid(),
    };
    if (meta) {
        stateObj.meta = meta;
    }
    const stateString = JSON.stringify(stateObj);
    return cryptoObj.base64Encode(stateString);
}
/**
 * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
 * @param base64Decode
 * @param state
 */
function parseRequestState(base64Decode, state) {
    if (!base64Decode) {
        throw createClientAuthError(noCryptoObject);
    }
    if (!state) {
        throw createClientAuthError(invalidState);
    }
    try {
        // Split the state between library state and user passed state and decode them separately
        const splitState = state.split(RESOURCE_DELIM);
        const libraryState = splitState[0];
        const userState = splitState.length > 1
            ? splitState.slice(1).join(RESOURCE_DELIM)
            : "";
        const libraryStateString = base64Decode(libraryState);
        const libraryStateObj = JSON.parse(libraryStateString);
        return {
            userRequestState: userState || "",
            libraryState: libraryStateObj,
        };
    }
    catch (e) {
        throw createClientAuthError(invalidState);
    }
}

export { generateLibraryState, parseRequestState, setRequestState };
//# sourceMappingURL=ProtocolUtils.mjs.map
