import Macroable from '@poppinss/macroable'; import type { HttpContext } from '@adonisjs/core/http'; import type { EmitterService } from '@adonisjs/core/types'; import type { HttpError } from '@adonisjs/core/types/http'; import { ValuesStore } from './values_store.ts'; import type { SessionData, SessionConfig, SessionStoreFactory, AllowedSessionValues } from './types.ts'; /** * The session class exposes the API to read and write values to * the session store. * * A session instance is isolated between requests but * uses a centralized persistence store. * * @example * // Creating and using a session * const session = new Session(config, storeFactory, emitter, ctx) * await session.initiate(false) * * session.put('username', 'john') * const username = session.get('username') * * await session.commit() */ export declare class Session extends Macroable { #private; config: SessionConfig; /** * Store of flash messages that will be written during the HTTP request */ responseFlashMessages: ValuesStore; /** * Store of flash messages for the current HTTP request */ flashMessages: ValuesStore; /** * The key used for storing flash messages inside the session store */ flashKey: string; /** * Gets the session id for the current HTTP request */ get sessionId(): string; /** * Returns true if a fresh session was created during the request */ get fresh(): boolean; /** * Returns true if the session is in readonly state */ get readonly(): boolean; /** * Returns true if the session store has been initiated */ get initiated(): boolean; /** * Returns true if the session id has been re-generated during the current request */ get hasRegeneratedSession(): boolean; /** * Returns true if the session store is empty */ get isEmpty(): boolean; /** * Returns true if the session store has been modified */ get hasBeenModified(): boolean; /** * Creates a new session instance * * @param config - Session configuration * @param storeFactory - Factory function to create session store * @param emitter - Event emitter service * @param ctx - HTTP context */ constructor(config: SessionConfig, storeFactory: SessionStoreFactory, emitter: EmitterService, ctx: HttpContext); /** * Determines whether a value should be stored in flash messages. * Objects can opt out by setting a STORE_IN_FLASH symbol property to false. * * @param value - Value to check for flash storage eligibility */ protected shouldFlashValue(value: unknown): unknown; /** * Filters flash data to only include values that should be flashed. * Removes values that have opted out of flash storage. * * @param data - Flash data to filter */ protected cleanupFlashData(data: T): T | Record; /** * Initiates the session store. The method results in a noop when called multiple times. * * @param readonly - Whether to initiate the session in readonly mode * * @example * await session.initiate(false) // Read-write mode * await session.initiate(true) // Readonly mode */ initiate(readonly: boolean): Promise; /** * Puts a key-value pair to the session data store * * @param key - The key to store the value under * @param value - The value to store * * @example * session.put('username', 'john') * session.put('user.preferences', { theme: 'dark' }) */ put(key: string, value: AllowedSessionValues): void; /** * Checks if a key exists inside the datastore * * @param key - The key to check for existence * * @example * if (session.has('username')) { * console.log('User is logged in') * } */ has(key: string): boolean; /** * Gets the value of a key from the session datastore. * You can specify a default value to use when key does not exist or has undefined value. * * @param key - The key to retrieve * @param defaultValue - Default value to return if key doesn't exist * * @example * const username = session.get('username', 'guest') * const preferences = session.get('user.preferences', {}) */ get(key: string, defaultValue?: any): any; /** * Gets everything from the session store * * @example * const allData = session.all() * console.log(allData) // { username: 'john', theme: 'dark' } */ all(): any; /** * Removes a key from the session datastore * * @param key - The key to remove * * @example * session.forget('temp_data') * session.forget('user.cache') */ forget(key: string): void; /** * Reads value for a key from the session datastore and removes it simultaneously * * @param key - The key to pull * @param defaultValue - Default value to return if key doesn't exist * * @example * const message = session.pull('notification', 'No messages') * // message contains the value, and it's removed from session */ pull(key: string, defaultValue?: any): any; /** * Increments the value of a key inside the session store. * A new key will be defined if it doesn't exist already with value 1. * * @param key - The key to increment * @param steps - Number of steps to increment (default: 1) * * @example * session.increment('page_views') // Increments by 1 * session.increment('score', 10) // Increments by 10 */ increment(key: string, steps?: number): void; /** * Decrements the value of a key inside the session store. * A new key will be defined if it doesn't exist already with value -1. * * @param key - The key to decrement * @param steps - Number of steps to decrement (default: 1) * * @example * session.decrement('attempts') // Decrements by 1 * session.decrement('credits', 5) // Decrements by 5 */ decrement(key: string, steps?: number): void; /** * Empties the session store * * @example * session.clear() // Removes all session data */ clear(): void; /** * Adds a key-value pair to flash messages * * @param key - The key or object of key-value pairs to flash * @param value - The value to flash (when key is a string) * * @example * session.flash('success', 'Data saved successfully!') * session.flash({ error: 'Validation failed', info: 'Try again' }) */ flash(key: string, value: AllowedSessionValues): void; flash(keyValue: SessionData): void; /** * Flashes errors to the errorsBag. You can read these errors via the "@error" tag. * Appends new messages to the existing collection. * * @param errorsCollection - Collection of error messages * * @example * session.flashErrors({ * general: 'Something went wrong', * validation: ['Name is required', 'Email is invalid'] * }) */ flashErrors(errorsCollection: Record): void; /** * Flashes validation error messages. Make sure the error is an instance of VineJS ValidationException. * Overrides existing inputErrors. * * @param error - HTTP error containing validation messages * * @example * try { * await request.validate(schema) * } catch (error) { * session.flashValidationErrors(error) * } */ flashValidationErrors(error: HttpError, withInput?: boolean): void; /** * Flashes all form input data to the flash messages store * * @example * session.flashAll() // Flashes all request input for next request */ flashAll(): void; /** * Flashes form input data (except some keys) to the flash messages store * * @param keys - Array of keys to exclude from flashing * * @example * session.flashExcept(['password', '_csrf']) */ flashExcept(keys: string[]): void; /** * Flashes form input data (only some keys) to the flash messages store * * @param keys - Array of keys to include in flashing * * @example * session.flashOnly(['name', 'email']) */ flashOnly(keys: string[]): void; /** * Reflashes messages from the last request in the current response * * @example * session.reflash() // Keep all flash messages for another request */ reflash(): void; /** * Reflashes messages (only some keys) from the last request in the current response * * @param keys - Array of keys to reflash * * @example * session.reflashOnly(['success', 'info']) */ reflashOnly(keys: string[]): void; /** * Reflashes messages (except some keys) from the last request in the current response * * @param keys - Array of keys to exclude from reflashing * * @example * session.reflashExcept(['error', 'warning']) */ reflashExcept(keys: string[]): void; /** * Checks if the current store supports session tagging. * Only Memory, Redis, and Database stores support tagging. * * @example * if (session.supportsTagging()) { * await session.tag(String(user.id)) * } */ supportsTagging(): boolean; /** * Tag the current session with a user ID. * Only supported by Memory, Redis, and Database stores. * This enables features like "logout from all devices". * * @param userId - The user ID to tag this session with * * @example * // During login, tag the session with the user's ID * await session.tag(String(user.id)) */ tag(userId: string): Promise; /** * Removes the tag association between this session and a user ID. * Only supported by Memory, Redis, and Database stores. * * @param userId - The user ID to untag this session from * * @example * // During logout, untag the session * await session.untag(String(user.id)) */ untag(userId: string): Promise; /** * Store a URL as the intended redirect destination. The URL is * validated using `isValidRedirectUrl` before storing. Invalid * URLs are silently ignored. * * @param url - The URL to store as the intended destination */ setIntendedUrl(url: string): void; /** * Returns the intended URL without consuming it, or `null` * if no intended URL is stored. */ getIntendedUrl(): string | null; /** * Returns the intended URL and removes it from the session, * or `null` if no intended URL is stored. */ pullIntendedUrl(): string | null; /** * Removes the intended URL from the session. */ clearIntendedUrl(): void; /** * Re-generates the session id and migrates data to it * * @example * session.regenerate() // Generates new session ID for security */ regenerate(): void; /** * Commits session changes. No more mutations will be allowed after commit. * * @example * await session.commit() // Save all changes to the session store */ commit(): Promise; }