### Initialize and Use State Methods Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/README.md Initialize the state client and perform basic CRUD operations and queries. Use `init` for setup and then `put`, `get`, `delete`, `deleteAll`, `list`, `any`, and `stats` for state management. ```javascript const { init } = require('@adobe/aio-lib-state') // Initialize const state = await init({ ow: { namespace: 'ns', auth: 'key' } }) // CRUD operations await state.put('key', 'value', { ttl: 3600 }) // Store (1hr TTL) const result = await state.get('key') // { value, expiration } await state.delete('key') // Delete one await state.deleteAll({ match: 'pattern-*' }) // Delete many // Query for await (const { keys } of state.list()) // Iterate all const empty = await state.any() === false // Check if empty const { keys, bytesKeys, bytesValues } = await state.stats() ``` -------------------------------- ### Examples of Valid and Invalid Keys/Match Patterns Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Illustrates valid and invalid examples for both store keys and match patterns, including the use of wildcards for matching multiple keys. ```javascript // Valid keys 'user-123' 'session_abc' 'cache.data' 'item-2024' // Invalid keys '' // empty 'key with space' // spaces not allowed 'key@domain' // @ not allowed 'a'.repeat(1025) // exceeds 1024 character limit // Valid match patterns (with wildcards) 'user-*' 'session_*_temp' '*-cache' '*' // all keys ``` -------------------------------- ### Initialize AdobeState SDK Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Initializes the AdobeState SDK with configuration. Use this to get an instance of the AdobeState class for interacting with the state service. ```javascript const { init } = require('@adobe/aio-lib-state') const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'amer' }) ``` -------------------------------- ### Mocking aio-lib-state for Jest Tests Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md Provides an example of how to mock the '@adobe/aio-lib-state' module for unit testing with Jest. It sets up mock implementations for the 'init' function and its returned methods like 'get' and 'put'. ```javascript jest.mock('@adobe/aio-lib-state') const { init } = require('@adobe/aio-lib-state') beforeEach(async () => { const mockState = { get: jest.fn(), put: jest.fn() } init.mockResolvedValue(mockState) }) ``` -------------------------------- ### Initialize State for Production Setup Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Configures the state client for production, allowing overrides for OpenWhisk namespace, authentication, region, log level, and retry settings via environment variables. ```javascript const { init } = require('@adobe/aio-lib-state') const state = await init({ ow: { namespace: process.env.OW_NAMESPACE || process.env.__OW_NAMESPACE, auth: process.env.OW_AUTH || process.env.__OW_API_KEY }, region: process.env.STATE_REGION || 'amer', logLevel: process.env.LOG_LEVEL || 'error', logRetryAfterSeconds: 30 }) ``` -------------------------------- ### Complete State Operation with Error Handling Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/errors.md An example demonstrating how to initialize the state SDK and perform a 'put' operation with comprehensive error handling for various error codes. It includes retries for rate limiting and specific handling for validation, authentication, payload size, and internal errors. ```javascript const { init, MAX_TTL } = require('@adobe/aio-lib-state') async function safeStateOperation() { try { // Initialize with defaults (uses __OW_NAMESPACE and __OW_API_KEY env vars) const state = await init() // Try to store a value with maximum TTL const key = 'cache-data' const value = JSON.stringify({ timestamp: Date.now(), data: '...' }) await state.put(key, value, { ttl: MAX_TTL }) console.log(`Stored ${key}`) } catch (error) { const { code, message, sdkDetails } = error switch (code) { case 'ERROR_BAD_ARGUMENT': console.error(`Invalid argument: ${message}`, sdkDetails) // Handle validation errors break case 'ERROR_UNAUTHORIZED': case 'ERROR_BAD_CREDENTIALS': console.error(`Authentication failed: ${message}`) // Log out, refresh credentials, notify admin break case 'ERROR_PAYLOAD_TOO_LARGE': console.error(`Payload exceeds limits: ${message}`) // Reduce value size, compress data, split into multiple keys break case 'ERROR_REQUEST_RATE_TOO_HIGH': console.error(`Rate limited, backing off: ${message}`) // Implement exponential backoff await new Promise(r => setTimeout(r, 5000)) return safeStateOperation() // retry case 'ERROR_INTERNAL': console.error(`Service error: ${message}`) console.error(`Request ID: ${sdkDetails.requestId}`) // Log for support investigation, retry later break default: console.error(`Unknown error: ${code}`, message) } throw error // re-throw if not handled } } ``` -------------------------------- ### Handling ERROR_BAD_CREDENTIALS Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/errors.md Example of catching and inspecting an ERROR_BAD_CREDENTIALS. This error is thrown when supplied credentials are invalid or cannot access the state service. ```javascript try { const state = init({ ow: { namespace: 'nonexistent-namespace', auth: 'valid-key-wrong-ns' } }) await state.put('key', 'value') } catch (error) { if (error.code === 'ERROR_BAD_CREDENTIALS') { console.error(`Bad credentials: ${error.message}`) // Message: "cannot access State service, make sure your credentials are valid" } } ``` -------------------------------- ### Error Details Object Example Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/errors.md Demonstrates the structure of the `sdkDetails` object when an invalid key is used in a delete operation. This object provides context for debugging. ```javascript try { await state.delete('key@invalid') } catch (error) { console.log(error.sdkDetails) // Output: { // key: 'key@invalid', // errors: [ // { // keyword: 'pattern', // message: 'must match pattern "^[a-zA-Z0-9-_.]{1,1024}$"' // } // ] // } } ``` -------------------------------- ### Store Data with Custom Time-To-Live (TTL) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Shows how to set a specific time-to-live for stored data in seconds, including examples for a short duration, a week, and the maximum allowed TTL. ```javascript // 1 hour TTL await state.put('session-abc', sessionData, { ttl: 3600 }) // 7 days TTL await state.put('weekly-cache', data, { ttl: 604800 }) // Maximum TTL const { MAX_TTL } = require('@adobe/aio-lib-state') await state.put('archive', data, { ttl: MAX_TTL }) ``` -------------------------------- ### Initialize and Get State in Adobe App Builder Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md Shows how to initialize the state client and retrieve cached data within an Adobe App Builder function. It automatically uses environment variables for credentials. ```javascript async function main(params) { const state = await init() // Uses __OW_* env vars automatically const cachedData = await state.get('cache-key') return cachedData ? JSON.parse(cachedData.value) : null } ``` -------------------------------- ### Initialize State with Default Americas Region Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md This example shows initialization without specifying a region, which defaults to the Americas ('amer'). ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' } // region defaults to 'amer' }) ``` -------------------------------- ### Put Key-Value Pair with Custom TTL Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Stores a key-value pair with a specified custom time-to-live (TTL) in seconds. The example shows a 7-day TTL. ```javascript await state.put('key2', 'value2', { ttl: 604800 }) ``` -------------------------------- ### init(config?) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Initializes the SDK and returns an AdobeState instance. Configuration options for OpenWhisk credentials and region can be provided. ```APIDOC ## init(config?) ### Description Initializes the SDK and returns an AdobeState instance. Configuration options for OpenWhisk credentials and region can be provided. ### Method `init` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object) - Optional - Initialization configuration. - **ow** (object) - OpenWhisk credentials. - **namespace** (string) - Required - OpenWhisk namespace. - **auth** (string) - Required - OpenWhisk authentication key. - **region** (string) - Optional - The region for the state service. ### Request Example ```javascript const { init } = require('@adobe/aio-lib-state') const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'amer' }) ``` ### Response #### Success Response (AdobeState instance) - **AdobeState instance** - An instance of the AdobeState class with methods for state management. #### Response Example (Instance of AdobeState) ``` -------------------------------- ### init Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Initializes and returns the key-value-store SDK. You must provide OpenWhisk credentials or they can be read from environment variables. ```APIDOC ## init([config]) ### Description Initializes and returns the key-value-store SDK. To use the SDK you must either provide your OpenWhisk credentials in `config.ow` or they can be read from environment variables `__OW_NAMESPACE` and `__OW_API_KEY`. ### Returns `Promise` - An AdobeState instance ### Parameters #### config (optional) * **config.ow** (OpenWhiskCredentials) - Used to init the sdk. Set those if you want to use ootb credentials to access the state management service. OpenWhisk namespace and auth can also be passed through environment variables: `__OW_NAMESPACE` and `__OW_API_KEY`. * **config.region** (string, optional) - Optional region to use, accepted values: `amer` (default), `emea`, `apac`, `aus`. * **config.logLevel** (string, optional) - Optional log level for the HttpExponentialBackoff instance. * **config.logRetryAfterSeconds** (number, optional) - Defaults to 10. If the request has to retry because of a 429, it will log the retry attempt as a warning if the Retry-After value is greater than this number. Set to 0 to disable. ``` -------------------------------- ### Initialize State with Minimal Configuration Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Initializes the state client using environment variables for namespace and API key. Ensure __OW_NAMESPACE and __OW_API_KEY are set. ```javascript const { init } = require('@adobe/aio-lib-state') // Uses environment variables process.env.__OW_NAMESPACE = 'my-namespace' process.env.__OW_API_KEY = 'my-api-key' const state = await init() ``` -------------------------------- ### AdobeState.getRegionalEndpoint Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Gets the regional endpoint for a given endpoint and region. ```APIDOC ## AdobeState.getRegionalEndpoint(endpoint, region) ### Description Gets the regional endpoint for an endpoint. ### Method GET (Conceptual) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters - **endpoint** (string) - Required - the endpoint to test - **region** (string) - Required - the region to set ### Request Example ```javascript const regionalEndpoint = await adobeState.getRegionalEndpoint('https://example.com', 'us-east-1'); ``` ### Response #### Success Response (200) - **string**: the endpoint, with the correct region ``` -------------------------------- ### init Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Initializes and returns the key-value-store SDK. Configuration can be provided via an object or environment variables. ```APIDOC ## init([config]) ### Description Initializes and returns the key-value-store SDK. To use the SDK you must either provide your OpenWhisk credentials in `config.ow` or your own. OpenWhisk credentials can also be read from environment variables `__OW_NAMESPACE` and `__OW_API_KEY`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage with config object const stateSDK = await init({ // ... other config options ow: { namespace: '__OW_NAMESPACE', apiKey: '__OW_API_KEY' } }); ``` ### Response #### Success Response (200) - **AdobeState**: An instance of the AdobeState class. ``` -------------------------------- ### Get a value Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/INDEX.md Retrieves a value associated with a given key from the State service. ```APIDOC ## Get a value ### Description Retrieves a value associated with a given key from the State service. ### Method `state.get(key)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of the value to retrieve. ``` -------------------------------- ### Initialize and Use Adobe I/O State Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md Demonstrates the basic workflow of initializing the state client, storing a value with a default TTL, retrieving it, and then deleting it. It also shows how to delete multiple keys using a pattern and how to list keys. ```javascript const { init } = require('@adobe/aio-lib-state') // Initialize const state = await init({ ow: { namespace: 'my-ns', auth: 'my-key' } }) // Store a value with 24-hour TTL (default) await state.put('user-123', JSON.stringify({ name: 'Alice' })) // Retrieve it const result = await state.get('user-123') console.log(result.value) // {"name":"Alice"} console.log(result.expiration) // ISO-8601 date when key expires // Delete it await state.delete('user-123') // Delete multiple with pattern await state.deleteAll({ match: 'user-*' }) // List keys (with pagination) for await (const { keys } of state.list({ match: 'user-*' })) { console.log(keys) } ``` -------------------------------- ### AdobeStateGetReturnValue Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Return value from the `get()` method, containing the stored value and its expiration datetime. ```APIDOC ## AdobeStateGetReturnValue ### Description Return value from the `get()` method, containing the stored value and its expiration datetime. ### Properties #### `value` - **Type**: `string` - **Description**: The value that was stored with `put()` #### `expiration` - **Type**: `string` - **Description**: ISO-8601 formatted datetime string indicating when the key will expire (e.g., `"2025-06-19T14:30:00.000Z"`) ### Notes - Only returned when the key exists - If key does not exist, `get()` returns `undefined` - The expiration datetime is always in ISO-8601 format with timezone offset ### Returned by - `AdobeState.get()` method ``` -------------------------------- ### Initialize State Client for Multi-Region Support Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Demonstrates initializing separate state clients for different AWS regions ('amer', 'emea', 'apac') to support multi-region deployments. It shows how to select the appropriate client based on user location. ```javascript const { init } = require('@adobe/aio-lib-state') const stateByRegion = {} for (const region of ['amer', 'emea', 'apac']) { stateByRegion[region] = await init({ ow: { namespace: `ns-${region}`, auth: `key-${region}` }, region }) } // Route based on user location const userState = stateByRegion[getUserRegion()] await userState.put(`user-${id}`, userData) ``` -------------------------------- ### Get statistics Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/INDEX.md Retrieves statistics about the State service usage, such as number of keys, storage size, etc. ```APIDOC ## Get statistics ### Description Retrieves statistics about the State service usage, such as number of keys, storage size, etc. ### Method `state.stats()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### Initialize AdobeState SDK Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Initializes and returns the AdobeState SDK instance. Provide OpenWhisk credentials in `config.ow` or rely on environment variables `__OW_NAMESPACE` and `__OW_API_KEY`. Optional region and logging configurations can also be set. ```javascript init([config]) ``` -------------------------------- ### Entry Point Exports Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md The main entry point exports the init() function for initializing the AdobeState instance and the MAX_TTL constant representing the maximum allowed time-to-live in seconds. ```javascript module.exports = { init: async (config?) => Promise, MAX_TTL: number // 31536000 (365 days in seconds) } ``` -------------------------------- ### init() Function Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/init-function.md Initializes and returns the Adobe State SDK instance for key-value store operations. It accepts an optional configuration object for specifying OpenWhisk credentials, region, and logging preferences. ```APIDOC ## init() Function Initializes and returns the Adobe State SDK instance for key-value store operations. ### Signature ```javascript async function init(config?: { ow?: OpenWhiskCredentials, region?: string, logLevel?: string, logRetryAfterSeconds?: number }): Promise ``` ### Parameters #### `config` (object) - Optional Configuration object for SDK initialization. - **`config.ow`** (OpenWhiskCredentials) - Optional - OpenWhisk namespace and auth credentials. If not provided, reads from environment variables `__OW_NAMESPACE` and `__OW_API_KEY`. - **`config.region`** (string) - Optional - Region for the state store. Allowed values: `'amer'` (default), `'emea'`, `'apac'`, `'aus'`. Only `'amer'` is supported when `AIO_CLI_ENV=stage`. - **`config.logLevel`** (string) - Optional - Log level for the HttpExponentialBackoff instance. Propagated to internal networking layer. - **`config.logRetryAfterSeconds`** (number) - Optional - If a request retries due to 429 rate limit, logs as warning only if Retry-After exceeds this value. Set to 0 to disable retry logging. Default: `10`. ### Return Value **Type:** `Promise` Resolves to an initialized AdobeState instance. Rejects with `ERROR_BAD_ARGUMENT` if credentials are missing or invalid, or `ERROR_BAD_ARGUMENT` if region is not allowed. ### Usage Examples #### Using environment variables ```javascript const stateLib = require('@adobe/aio-lib-state') // Uses __OW_NAMESPACE and __OW_API_KEY from environment const state = await stateLib.init() ``` #### Using explicit credentials ```javascript const stateLib = require('@adobe/aio-lib-state') const state = await stateLib.init({ ow: { namespace: 'my-namespace', auth: 'my-api-key' }, region: 'emea' }) ``` #### With logging configuration ```javascript const state = await stateLib.init({ ow: { namespace: 'my-namespace', auth: 'my-api-key' }, logLevel: 'debug', logRetryAfterSeconds: 15 }) ``` ### Error Handling ```javascript const stateLib = require('@adobe/aio-lib-state') try { const state = await stateLib.init({ ow: { namespace: '', // Missing namespace auth: 'key' } }) } catch (error) { if (error.code === 'ERROR_BAD_ARGUMENT') { console.error('Invalid configuration:', error.message) console.error('Details:', error.sdkDetails) } } ``` ``` -------------------------------- ### Handling ERROR_BAD_ARGUMENT Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/errors.md Example of catching and inspecting an ERROR_BAD_ARGUMENT. This error is thrown when function arguments are invalid, such as an out-of-range TTL value. ```javascript try { await state.put('my_key', 'value', { ttl: 99999999 }) } catch (error) { if (error.code === 'ERROR_BAD_ARGUMENT') { console.error(`Argument error: ${error.message}`) // Message example: "ttl must be <= 365 days (31536000s). Infinite TTLs (< 0) are not supported." console.error('Invalid parameters:', error.sdkDetails) } } ``` -------------------------------- ### AdobeStateGetReturnValue Type Definition Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Defines the structure of the return value from the `get()` method, containing the stored value and its expiration time. ```typescript type AdobeStateGetReturnValue = { value: string, expiration: string } ``` -------------------------------- ### get(key) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Retrieves the state value for a given key. Returns the value and its expiration time, or undefined if the key does not exist. ```APIDOC ## get(key) ### Description Retrieves the state value for a given key. Returns the value and its expiration time, or undefined if the key does not exist. ### Method `async get(key: string): Promise` ### Parameters #### Path Parameters - **key** (string) - Required - State key identifier. Must match pattern `[a-zA-Z0-9-_.]{1,1024}` ### Response #### Success Response - **value** (string) - The value stored for this key - **expiration** (string) - ISO-8601 datetime string indicating when the key expires ### Response Example ```json { "value": "some stored value", "expiration": "2025-06-19T14:30:00.000Z" } ``` ### Throws - `ERROR_BAD_ARGUMENT`: Key is missing, empty, or contains invalid characters - `ERROR_UNAUTHORIZED`: Credentials lack access to the state service - `ERROR_BAD_CREDENTIALS`: Supplied credentials are invalid - `ERROR_INTERNAL`: Unexpected response from state service ``` -------------------------------- ### Handling ERROR_UNAUTHORIZED Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/errors.md Example of catching and inspecting an ERROR_UNAUTHORIZED. This error occurs when credentials are valid but lack the necessary authorization to access the state service. ```javascript try { const state = await init({ ow: { namespace: 'some-namespace', auth: 'invalid-or-expired-key' } }) await state.get('key') } catch (error) { if (error.code === 'ERROR_UNAUTHORIZED') { console.error(`Not authorized: ${error.message}`) // Message: "you are not authorized to access State service" console.error('Request ID:', error.sdkDetails.requestId) } } ``` -------------------------------- ### Initialize State for Multi-Region Configuration Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Initializes multiple state clients for different regions (US, EU, AP) and demonstrates how to select the appropriate client based on user region for data retrieval. ```javascript const { init } = require('@adobe/aio-lib-state') const regions = { us: await init({ ow: { namespace: 'ns-us', auth: 'key-us' }, region: 'amer' }), eu: await init({ ow: { namespace: 'ns-eu', auth: 'key-eu' }, region: 'emea' }), ap: await init({ ow: { namespace: 'ns-ap', auth: 'key-ap' }, region: 'apac' }) } // Use appropriate region based on request const userState = regions[userRegion] const data = await userState.get(`user-${userId}`) ``` -------------------------------- ### Initialize SDK Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/INDEX.md Initializes the Adobe State SDK with the provided configuration. This is the first step before using any other SDK methods. ```APIDOC ## Initialize SDK ### Description Initializes the Adobe State SDK with the provided configuration. This is the first step before using any other SDK methods. ### Method `init(config)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object) - Required - The configuration object for initializing the SDK. ``` -------------------------------- ### Initialize State for Development with Debug Logging Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Sets up the state client for development with a specific namespace, API key, region, and enables debug logging with a short retry interval. ```javascript const { init } = require('@adobe/aio-lib-state') const state = await init({ ow: { namespace: 'development-namespace', auth: 'dev-api-key' }, region: 'amer', logLevel: 'debug', logRetryAfterSeconds: 5 }) ``` -------------------------------- ### Stage Environment Region Constraint Example Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md This code will fail when the AIO_CLI_ENV is set to 'stage' because only the 'amer' region is allowed in that environment. It demonstrates the stage environment restriction for regions. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'emea' // Only 'amer' allowed in stage }) // Throws: ERROR_BAD_ARGUMENT with message about stage region restriction ``` -------------------------------- ### Initialize State Using Environment Variables for Credentials Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md This method initializes the state management service by reading OpenWhisk credentials from environment variables (__OW_NAMESPACE and __OW_API_KEY). Ensure these variables are set before calling init(). ```javascript process.env.__OW_NAMESPACE = 'my-namespace' process.env.__OW_API_KEY = 'my-api-key' const state = await init() ``` -------------------------------- ### Get Regional Endpoint for AdobeState Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Resolves a regional endpoint template by substituting the region placeholder. If the AIO_STATE_ENDPOINT environment variable is set, that custom endpoint is returned instead. ```javascript const url = state.getRegionalEndpoint( 'https://storage-state-.app-builder.adp.adobe.io', 'emea' ) // Returns: 'https://storage-state-emea.app-builder.adp.adobe.io' ``` -------------------------------- ### Basic Store and Retrieve Data Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Demonstrates how to initialize the state client, store a JSON string value with a key, and retrieve it. The retrieved value includes the stored data and its expiration time. ```javascript const { init } = require('@adobe/aio-lib-state') const state = await init() await state.put('user-123', JSON.stringify({ name: 'Alice' })) const result = await state.get('user-123') console.log(result.value) // {"name":"Alice"} console.log(result.expiration) // ISO-8601 datetime ``` -------------------------------- ### Get State Container Statistics Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Retrieves statistics about the state container, including the total number of keys and their sizes in bytes. Returns zeroed stats if the container does not exist. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' } }) const stats = await state.stats() console.log(`Total keys: ${stats.keys}`) console.log(`Total key size: ${stats.bytesKeys} bytes`) console.log(`Total value size: ${stats.bytesValues} bytes`) ``` -------------------------------- ### Initialize Adobe State with Logging Configuration Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/init-function.md Configure logging levels and retry behavior for the SDK instance during initialization. ```javascript const state = await stateLib.init({ ow: { namespace: 'my-namespace', auth: 'my-api-key' }, logLevel: 'debug', logRetryAfterSeconds: 15 }) ``` -------------------------------- ### Initialize State with Mixed Credentials (Explicit Namespace, Env Var Auth) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md This snippet demonstrates initializing with an explicit OpenWhisk namespace while using an environment variable for the authentication key. ```javascript const state = await init({ ow: { namespace: 'my-namespace', auth: process.env.__OW_API_KEY } }) ``` -------------------------------- ### Retrieve State Value Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Use this snippet to get the value associated with a specific key. It returns the value and its expiration time, or undefined if the key is not found. Ensure the key is valid and credentials have access. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' } }) // Retrieve a value const result = await state.get('user-profile-123') if (result) { console.log('Value:', result.value) console.log('Expires at:', result.expiration) // e.g., "2025-06-19T14:30:00.000Z" } else { console.log('Key not found') } ``` -------------------------------- ### Missing Configuration and Environment Variables Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md This snippet demonstrates the error caught when neither configuration nor environment variables are provided for required parameters like namespace and apikey. ```javascript try { await init() } catch (e) { // ERROR_BAD_ARGUMENT: "must have required properties: namespace, apikey" } ``` -------------------------------- ### Handle Initialization Errors for Adobe State Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/init-function.md Demonstrates how to catch and handle specific errors, such as ERROR_BAD_ARGUMENT, that may occur during SDK initialization. ```javascript const stateLib = require('@adobe/aio-lib-state') try { const state = await stateLib.init({ ow: { namespace: '', // Missing namespace auth: 'key' } }) } catch (error) { if (error.code === 'ERROR_BAD_ARGUMENT') { console.error('Invalid configuration:', error.message) console.error('Details:', error.sdkDetails) } } ``` -------------------------------- ### Build and Run E2E Tests with Docker Source: https://github.com/adobe/aio-lib-state/blob/main/e2e/e2e.md Build the Docker image for the e2e tests and run a container, passing environment variables via an .env file. ```sh # build the Docker image # multi-arch build: see https://docs.docker.com/build/building/multi-platform/#building-multi-platform-images docker buildx create --name mybuilder --bootstrap --use docker buildx build -f e2e.Dockerfile --platform linux/arm/v7,linux/arm64/v8,linux/amd64 -t aio-lib-state-e2e --load . # create and run a container based off the Docker image, pass in the environment file docker run --env-file e2e/.env -t aio-lib-state-e2e ``` -------------------------------- ### Initialize Adobe State using Environment Variables Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/init-function.md Use this snippet when OpenWhisk credentials are set as environment variables (__OW_NAMESPACE and __OW_API_KEY). ```javascript const stateLib = require('@adobe/aio-lib-state') // Uses __OW_NAMESPACE and __OW_API_KEY from environment const state = await stateLib.init() ``` -------------------------------- ### list(options?) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Returns an async generator to iterate over keys in the container. Scans 1000 keys per iteration. ```APIDOC ## list(options?) ### Description Returns an async generator to iterate over keys in the container. Scans 1000 keys per iteration. ### Method `list` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object) - Optional - List options - **options.match** (string) - Optional - Glob pattern to filter keys (supports `*` wildcard). If omitted, returns all keys ### Response #### Success Response - **keys** (string[]) - Array of key names from this iteration (up to 1000 keys per iteration) ### Throws - `ERROR_BAD_ARGUMENT` - Match pattern contains invalid characters - `ERROR_UNAUTHORIZED` - Credentials lack access - `ERROR_BAD_CREDENTIALS` - Credentials are invalid - `ERROR_INTERNAL` - Unexpected response from state service ### Example ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' } }) // Iterate all keys for await (const { keys } of state.list()) { console.log('Keys in this batch:', keys) // Process keys (typically 1000 per iteration) } // Iterate keys matching a pattern for await (const { keys } of state.list({ match: 'user-*' })) { console.log('User keys:', keys) } // Collect all keys into array const allKeys = [] for await (const { keys } of state.list({ match: 'session-*' })) { allKeys.push(...keys) } console.log(`Found ${allKeys.length} session keys`) ``` ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Initialize the SDK with 'debug' log level to capture all HTTP requests, responses, and retry attempts. This is useful for troubleshooting. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' }, logLevel: 'debug' }) // Logs all HTTP requests, responses, and retry attempts ``` -------------------------------- ### Initialize AdobeState Client Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Initializes the AdobeState client with OpenWhisk credentials and a specified region. This is a prerequisite for using other AdobeState methods. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'emea' }) ``` -------------------------------- ### Initialize State Library Configuration Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md Initialize the State library with an optional configuration object. Environment variables can be used as fallbacks for namespace and API key. ```typescript await init({ ow?: { namespace: string, // Or use __OW_NAMESPACE env var auth: string // Or use __OW_API_KEY env var }, region?: string, // 'amer' (default), 'emea', 'apac', 'aus' logLevel?: string, // For HTTP client logging logRetryAfterSeconds?: number // When to warn on retries (default: 10) }) ``` -------------------------------- ### Initialize State with Explicit OpenWhisk Credentials Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Use this snippet to explicitly provide OpenWhisk namespace and authentication key for state management. ```javascript const state = await init({ ow: { namespace: 'my-adobe-namespace-12345', auth: 'aAbBcCdDeEfF1234567890' } }) ``` -------------------------------- ### Perform Batch Operations Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Illustrates how to perform batch operations such as deleting all keys matching a pattern, listing all keys, and listing keys that match a specific pattern to process their data. ```javascript // Delete all matching keys const deleted = await state.deleteAll({ match: 'session-*' }) console.log(`Deleted ${deleted.keys} sessions`) // List all keys const allKeys = [] for await (const { keys } of state.list()) { allKeys.push(...keys) } console.log(`Found ${allKeys.length} total keys`) // List keys matching pattern for await (const { keys } of state.list({ match: 'user-*' })) { for (const key of keys) { const data = await state.get(key) // Process user data } } ``` -------------------------------- ### Initialize Adobe State with Explicit Credentials and Region Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/init-function.md Use this snippet to provide OpenWhisk credentials and specify a region directly during initialization. ```javascript const stateLib = require('@adobe/aio-lib-state') const state = await stateLib.init({ ow: { namespace: 'my-namespace', auth: 'my-api-key' }, region: 'emea' }) ``` -------------------------------- ### AdobeState.list Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Lists all state keys, returning an async generator. ```APIDOC ## AdobeState.list([options]) ### Description Lists all state keys. ### Method GET (Conceptual) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters None #### Query Parameters - **options** (object) - Optional - Options for list ### Request Example ```javascript const keysGenerator = adobeState.list(); for await (const page of keysGenerator) { console.log(page.keys); } ``` ### Response #### Success Response (200) - **AsyncGenerator**: An async generator yielding pages of keys. ``` -------------------------------- ### AdobeState.any() Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/README.md Checks if any keys exist in the Adobe State service. ```APIDOC ## AdobeState.any() ### Description Checks if there are any keys present in the state service. ### Method Instance Method ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters None ### Request Example ```javascript const hasKeys = await state.any(); ``` ### Response #### Success Response - **exists** (boolean) - True if at least one key exists, false otherwise. #### Response Example ```json { "exists": true } ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md This snippet shows the file structure for the Adobe I/O Lib State project. It helps in understanding where to find different types of documentation. ```text /output/ ├── 00-START-HERE.md ← You are here ├── INDEX.md ← Complete navigation guide ├── REFERENCE.md ← Overview and common patterns ├── types.md ← Type definitions and constraints ├── configuration.md ← Init options and env vars ├── errors.md ← Error codes and handling └── api-reference/ ├── init-function.md ← init() function reference └── adobestate-class.md ← All class methods ``` -------------------------------- ### adobeState.list Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Lists keys, returning an iterator. Each call scans up to 1000 keys. ```APIDOC ## adobeState.list(options) ### Description Lists keys, returning an iterator. Every call scans 1000 keys. ### Returns `AsyncGenerator<{keys: Array}>` - An async generator which yields a { keys } object at every iteration. ### Parameters #### options (object) * **options.match** (string) - A glob pattern that supports '*' to filter keys. ### Request Example ```js for await (const { keys } of state.list({ match: 'abc*' })) { console.log(keys) } ``` ``` -------------------------------- ### AdobeState.list(options) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/README.md Lists or iterates over keys stored in the Adobe State service, potentially with filtering or pagination options. ```APIDOC ## AdobeState.list(options) ### Description Lists keys stored in the state. Options can be used for filtering, pagination, or iteration. ### Method Instance Method ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object) - Optional - Options to control the listing behavior, such as prefix filtering or pagination tokens. ### Request Example ```javascript const keys = await state.list({ prefix: 'user_' }); ``` ### Response #### Success Response - **keys** (array) - An array of keys matching the criteria. #### Response Example ```json { "keys": ["user_123", "user_456"] } ``` ``` -------------------------------- ### Initialize AdobeState Instance Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Internal static method for creating and validating an AdobeState instance. This method is intended for internal use by the exported init() function and should not be called directly. ```javascript static async init(credentials?: AdobeStateCredentials): Promise ``` -------------------------------- ### adobeState.any Source: https://github.com/adobe/aio-lib-state/blob/main/doc/api.md Checks if any key-values exist in the region. ```APIDOC ## adobeState.any() ### Description Checks if any key-values exist in the region. ### Returns `Promise` - True if key-values exist, false if not. ``` -------------------------------- ### AdobeStateCredentials Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Credentials and configuration for initializing an AdobeState instance. ```APIDOC ## AdobeStateCredentials ### Description Credentials and configuration for initializing an AdobeState instance. ### Properties - **namespace** (string) - Yes - The state store namespace identifier - **apikey** (string) - Yes - The state store API key for authentication - **region** (enum) - No - Geographic region for the state store. Accepted values: `'amer'` (Americas, default), `'emea'` (Europe, Middle East, Africa), `'apac'` (Asia-Pacific), `'aus'` (Australia). Default: `'amer'` ### Notes - All properties are validated during `AdobeState.init()` - Region selection affects which endpoint is used for API calls - When running in Adobe Runtime with `AIO_CLI_ENV=stage`, only `'amer'` region is supported ### Used By - `AdobeState.init()` static method ``` -------------------------------- ### Initialize State for Europe (EMEA) Region Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Configure the state management service to use the EMEA region endpoint. Ensure your OpenWhisk credentials are provided. ```javascript const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'emea' }) ``` -------------------------------- ### Usage of MAX_TTL for State Entry TTL Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/types.md Demonstrates how to import and use the MAX_TTL constant when putting data into the state service, ensuring the entry's time-to-live is within the allowed maximum. ```javascript const { MAX_TTL } = require('@adobe/aio-lib-state') await state.put('archive', 'data', { ttl: MAX_TTL }) ``` -------------------------------- ### Initialize State in Adobe App Builder Action Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Initialize the state client within an Adobe App Builder action. Environment variables are automatically configured by the runtime. ```javascript // In an App Builder action const { init } = require('@adobe/aio-lib-state') async function main(params) { // Environment variables are automatically set by runtime const state = await init() const sessionId = params.sessionId const cachedData = await state.get(sessionId) if (!cachedData) { // Fetch fresh data const newData = await fetchData() await state.put(sessionId, JSON.stringify(newData), { ttl: 3600 }) return newData } return JSON.parse(cachedData.value) } ``` -------------------------------- ### Initialize State with Custom Endpoint for Testing Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Configures the state client to use a custom endpoint for testing by setting the AIO_STATE_ENDPOINT environment variable. This directs all requests to the specified local server. ```javascript const { init } = require('@adobe/aio-lib-state') process.env.AIO_STATE_ENDPOINT = 'http://localhost:4000' const state = await init({ ow: { namespace: 'test-namespace', auth: 'test-key' } }) // All requests go to http://localhost:4000 ``` -------------------------------- ### AdobeState Class Methods Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/REFERENCE.md Provides methods for CRUD, query, and utility operations on the state container. All methods are asynchronous and must be awaited. ```APIDOC ## AdobeState Class Methods All methods are asynchronous and must be awaited. ### CRUD Operations #### `get(key)` ##### Description Retrieve a value associated with the given key. ##### Returns - `{ value, expiration }` (object) - The stored value and its expiration time, or `undefined` if the key does not exist. #### `put(key, value, options?)` ##### Description Store a value associated with the given key. Optional options can specify the time-to-live (TTL). ##### Returns - `key` (string) - The key that was stored. #### `delete(key)` ##### Description Delete a key and its associated value. ##### Returns - `key` (string) - The key that was deleted, or `null` if the key did not exist. #### `deleteAll(options)` ##### Description Delete multiple keys based on a pattern. Returns the count of deleted keys. ##### Returns - `{ keys: count }` (object) - An object containing the number of keys deleted. ### Query Operations #### `list(options?)` ##### Description Iterate over keys in the state container. Returns keys in batches of 1000. ##### Returns - `AsyncGenerator` - An asynchronous generator that yields keys. #### `any()` ##### Description Check if the state container contains any keys. ##### Returns - `boolean` - `true` if the container has keys, `false` otherwise. #### `stats()` ##### Description Get statistics about the state container. ##### Returns - `{ keys, bytesKeys, bytesValues }` (object) - An object containing the number of keys, and the total bytes for keys and values. ### Utility Methods #### `getRegionalEndpoint(endpoint, region)` ##### Description Resolve the regional endpoint for a given service endpoint and region. ##### Returns - `string` - The resolved regional endpoint URL. ``` -------------------------------- ### Initialize State Client in Express.js Middleware Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/00-START-HERE.md Demonstrates how to attach the initialized state client to the request object in an Express.js application using middleware. This makes the state client available throughout the request lifecycle. ```javascript app.use(async (req, res, next) => { if (!req.state) { req.state = await init() } next() }) ``` -------------------------------- ### put(key, value, options?) Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/api-reference/adobestate-class.md Creates or updates a state key-value pair with an optional time-to-live (TTL). ```APIDOC ## put(key, value, options?) ### Description Creates or updates a state key-value pair with an optional time-to-live (TTL). ### Method `async put(key: string, value: string, options?: AdobeStatePutOptions): Promise` ### Parameters #### Path Parameters - **key** (string) - Required - State key identifier. Must match pattern `[a-zA-Z0-9-_.]{1,1024}` - **value** (string) - Required - The value to store. Must be a string - **options** (AdobeStatePutOptions) - Optional - Optional configuration for the key-value pair - **ttl** (number) - Optional - Time-to-live in seconds. Valid range: 0 to 31536000 (365 days). Defaults to 86400 (24 hours) if undefined or 0 ### Response #### Success Response - **key** (string) - The key that was stored ### Throws - `ERROR_BAD_ARGUMENT`: Key/value invalid or TTL out of range (must be 0 or between 1 and 31536000) - `ERROR_PAYLOAD_TOO_LARGE`: Key or value size exceeds allowed limits - `ERROR_UNAUTHORIZED`: Credentials lack access to the state service - `ERROR_BAD_CREDENTIALS`: Supplied credentials are invalid - `ERROR_REQUEST_RATE_TOO_HIGH`: Request rate limit exceeded (HTTP 429) - `ERROR_INTERNAL`: Unexpected response from state service ``` -------------------------------- ### Configure Adobe IO CLI Environment for State Service Source: https://github.com/adobe/aio-lib-state/blob/main/_autodocs/configuration.md Use AIO_CLI_ENV to select between production ('prod') and staging ('stage') endpoints for the state service. Staging requires the 'amer' region. ```bash # Use production endpoints export AIO_CLI_ENV="prod" # Use staging endpoints export AIO_CLI_ENV="stage" ``` ```javascript # Staging uses internal endpoints process.env.AIO_CLI_ENV = 'stage' const state = await init({ ow: { namespace: 'ns', auth: 'key' }, region: 'amer' // Must be 'amer' in stage }) ```