### Build Managed Component (Bash) Source: https://github.com/managed-components/docs/blob/main/getting-started/quickstart.md Installs project dependencies and builds the managed component. This involves running 'npm install' to fetch necessary packages and 'npm run build' to compile the component. ```bash npm install npm run build ``` -------------------------------- ### Example Performance Entry Payload (JSON) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/performance-entries.md This is an example of the JSON payload structure for a 'resourcePerformanceEntry' event. It contains a list of resources, each with a URL and a timestamp indicating when the resource was recorded. ```json { "event": "resourcePerformanceEntry", "payload": { "resources": [ { "url": "http://localhost:1337/webcm/demoComponent/cheese", "timestamp": 1653921858149 }, { "url": "https://images.unsplash.com/photo-1458682760028-07c9d41d0cd1?ixid=MnwxMTI1OHwwfDF8cmFuZG9tfHx8fHx8fHx8MTY1MDQ1NDY4NA&ixlib=rb-1.2.1&q=85&w=2880", "timestamp": 1653921858149 } ] } } ``` -------------------------------- ### Manifest Configuration for ExampleTool Source: https://github.com/managed-components/docs/blob/main/specs/manifest/example.md This JSON manifest defines the configuration for the ExampleTool component. It includes metadata like name, description, namespace, icon, and permission settings required for its operation within the managed components framework. ```json { "name": "ExampleTool", "description": "ExampleTool is a great tool for X and Y!", "namespace": "example", "icon": "assets/icon.svg", "allowCustomFields": true, "permissions": { "provide_widget": { "description": "ExampleTool provides an widget you can use in your website", "required": true }, "client_network_requests": { "description": "ExampleTool uses cookies to attribute sessions more accurately", "required": false } } } ``` -------------------------------- ### Implement Managed Component Logic (JavaScript) Source: https://github.com/managed-components/docs/blob/main/getting-started/quickstart.md Defines the core logic for a managed component. This function is exported as default and accepts 'manager' and 'settings' as arguments, where the component's functionality is implemented. ```javascript export default async function (manager, settings) { // the Managed Component logic goes here } ``` -------------------------------- ### Scaffold a Managed Component Project (Bash) Source: https://github.com/managed-components/docs/blob/main/getting-started/quickstart.md Initializes a new managed component project using the 'npm init managed-component' command. This command sets up a project with TypeScript, Vitest, ESLint, and Prettier, providing a pre-configured environment for component development. ```bash npm init managed-component ``` -------------------------------- ### Page Show Event Payload Example (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/page-show.md This example illustrates the structure of the payload received when the 'pageShow' event is triggered. It includes properties like 'persisted' and 'timestamp', which can provide context about the page's state and when it was shown. ```javascript { event: 'pageShow', pageShow: [ { persisted: true, timestamp: 1655997128153 } ] } ``` -------------------------------- ### Example Visibility Change Event Payload (JSON) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/visibility-change.md This is an example of the JSON payload structure received when a 'visibilityChange' event is triggered. It includes the event type and details about the visibility change, such as the new state ('hidden' or 'visible') and a timestamp. ```json { "event": "visibilityChange", "payload": { "visibilityChange": [{ "state": "hidden", "timestamp": 1678816122984 }] } } ``` -------------------------------- ### Mouse Up Event Payload Example (JSON) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/mouseup.md This is an example of the payload structure that can be received when a 'mouseup' event occurs. It includes details about the event type and specific mouseup event properties such as button state, coordinates, and target element. ```json { "event": "mouseup", "mouseup": [ { "altKey": false, "button": 0, "clientX": 556, "clientY": 66, "pageX": 556, "pageY": 156, "relativeY": 55.9453, "relativeX": 38.4831, "target": "body", "timestamp": 1655997128153 } ] } ``` -------------------------------- ### client.get Source: https://github.com/managed-components/docs/blob/main/specs/client/get.md Retrieves the value associated with a given key. The key is scoped to the current tool by default, but can be explicitly retrieved from another tool. ```APIDOC ## client.get ### Description Retrieves the value of a key that was previously set using `client.set`. By default, keys are scoped to the current tool. ### Method `GET` (Conceptual - this is a client-side method, not a direct HTTP endpoint) ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Get a key scoped to the current tool client.get('uuid') // Get a key scoped to a different tool client.get('uuid', 'facebook-pixel') ``` ### Response #### Success Response - **value** (any) - The value associated with the specified key. #### Response Example ```json { "value": "some_value" } ``` ``` -------------------------------- ### Perform GET Request with Fetch Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/fetch.md This snippet demonstrates how to perform a simple GET HTTP request using the `manager.fetch` method. It retrieves data from a specified URL and parses the JSON response. No external dependencies are required beyond the `manager` object. ```javascript const response = await manager.fetch('https://api.example.com/api'); const result = await response.json(); ``` -------------------------------- ### Retrieve Key Value with client.get (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client/get.md Retrieves the value associated with a given key using the client.get method. Keys are scoped to the tool that set them. This function can also retrieve keys from other tools by providing the tool name as a second argument. ```javascript client.get('uuid') ``` ```javascript client.get('uuid', 'facebook-pixel') ``` -------------------------------- ### Example Payload for historyChange Event Source: https://github.com/managed-components/docs/blob/main/specs/client-events/spa-navigation.md This is an example of the JSON payload structure that might be generated or expected when the 'historyChange' event occurs. It includes event type and a history array with details about the navigation change. ```json { "event": "historyChange", "payload": { "history": [ { "url": "https://cheese.com", "title": "Cheese", "timestamp": 1653923753892 } ] } } ``` -------------------------------- ### Implement Caching with `useCache` in JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/cache/useCache.md The `useCache` method caches function results to avoid redundant computations. It checks for existing cached data and its expiry time before executing the provided function. This example demonstrates caching a compiled Pug template. ```javascript await manager.useCache( `widget-${tweet.id}`, pug.compile('templates/floating-widget.pug', { tweet }), 60 ) ``` -------------------------------- ### Example Mouse Down Event Payload - JSON Source: https://github.com/managed-components/docs/blob/main/specs/client-events/mousedown.md This is an example of the payload structure received when a 'mousedown' event is triggered and processed by the listener. It includes event details such as the target element, timestamp, modifier keys, and client coordinates. ```json { "event": "mousedown", "mousedown": [ { "target": "body", "timestamp": 1653923456438, "altKey": false, "clientX": 276, "clientY": 403 } ] } ``` -------------------------------- ### Perform Server-Side HTTP Requests with manager.fetch Source: https://context7.com/managed-components/docs/llms.txt Executes HTTP requests from the server environment, mirroring the standard DOM fetch API. This is crucial for securely handling API keys and sensitive data, as the requests do not originate from the client's browser. Supports GET, POST, and other HTTP methods with custom headers and bodies. ```javascript // Simple GET request const response = await manager.fetch('https://api.example.com/data') const data = await response.json() // POST request with authentication const result = await manager.fetch('https://api.example.com/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${settings.apiKey}` // API key from settings, never exposed to browser }, body: JSON.stringify({ event: 'conversion', value: 99.99, currency: 'USD' }) }) if (!result.ok) { console.error('API request failed:', result.status) } ``` -------------------------------- ### Example Scroll Event Payload - JSON Source: https://github.com/managed-components/docs/blob/main/specs/client-events/scroll.md This JSON object illustrates the structure of the payload received when a scroll event is triggered. It includes details such as scroll position (scrollTop, scrollLeft, scrollY, scrollX), the target element, and a timestamp. ```json { "event": "scroll", "payload": { "scroll": [ { "scrollLeft": 0, "scrollTop": 77.7272720336914, "scrollX": 0, "scrollY": 77.7272720336914, "target": "body", "timestamp": 1653923753892 } ] } } ``` -------------------------------- ### Example Page Hide Event Payload Source: https://github.com/managed-components/docs/blob/main/specs/client-events/page-hide.md This JSON object illustrates the typical structure of the payload received when the 'pageHide' event is triggered. It includes information about the event type and details specific to the page hide event, such as 'persisted' status and a 'timestamp'. ```json { "event": "pageHide", "pageHide": [ { "persisted": true, "timestamp": 1655997128153 } ] } ``` -------------------------------- ### Serve Static Assets with JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/serve.md The `serve` function takes a source directory and an optional asset path. It exposes the contents of the source directory under the same domain, mapped to the provided asset path. The function returns the final URL where the assets will be available. ```javascript const myURL = manager.serve('public', 'assets') ``` -------------------------------- ### User-Configured Event Handling Source: https://context7.com/managed-components/docs/llms.txt Demonstrates listening for custom 'event' types dispatched from the website. This allows access to server-side context and client information for flexible tracking, including conditional client-side actions. ```javascript manager.addEventListener('event', async ({ context, client }) => { // Server-side request with visitor context await manager.fetch('https://example.com/collect', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ip: context.system.device.ip, eventName: context.eventName, pageTitle: context.system.page.title, customData: context.payload }) }) // Conditional client-side actions if (client.userAgent.includes('Chrome')) { client.set('session-id', crypto.randomUUID(), { scope: 'session' }) client.fetch('https://example.com/pixel.gif') } }) ``` -------------------------------- ### Pageview Event Handling Source: https://context7.com/managed-components/docs/llms.txt Demonstrates how to listen for the 'pageview' event. This is useful for tracking page loads and sending analytics data to a server. It utilizes `manager.fetch` to send a POST request with page details. ```javascript manager.addEventListener('pageview', async event => { const { client } = event // Send server-side analytics request await manager.fetch('https://analytics.example.com/collect', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: client.url.href, title: client.title, referrer: client.referer, userAgent: client.userAgent, timestamp: Date.now() }) }) }) ``` -------------------------------- ### Serve Static Files with manager.serve Source: https://context7.com/managed-components/docs/llms.txt Serves static files that are bundled with your component. It returns a mapped URL path where these assets become available. This is useful for linking CSS, JavaScript, or other static resources within your component's HTML. ```javascript // Serve the component's 'public' directory at '/assets' const assetsUrl = manager.serve('public', 'assets') // Files in public/ available at /webcm/my-component/assets/ // Reference served assets in widgets or client code manager.registerWidget(async () => { return `
` }) ``` -------------------------------- ### Execute Fetch Requests from Client Browser with client.fetch Source: https://context7.com/managed-components/docs/llms.txt Allows executing fetch requests directly from the client's browser. This is useful for sending tracking data (like beacons) or loading resources that must originate from the client environment. Supports query parameters for dynamic requests. ```javascript manager.addEventListener('event', async ({ client, context }) => { // Simple tracking pixel client.fetch('https://analytics.example.com/pixel.gif') // Fetch with query parameters const params = new URLSearchParams({ event: context.eventName, timestamp: Date.now().toString(), page: client.url.pathname }) client.fetch(`https://tracking.example.com/collect?${params}`) }) ``` -------------------------------- ### manager.serve Source: https://context7.com/managed-components/docs/llms.txt Serves static files bundled with your component. It returns the mapped URL path where these assets become available. ```APIDOC ## POST /managed-components/docs/manager.serve ### Description Serve static files bundled with your component. Returns the mapped URL path where assets become available. ### Method POST ### Endpoint /managed-components/docs/manager.serve ### Parameters #### Query Parameters - **sourceDir** (string) - Required - The directory containing the static files within your component. - **targetPath** (string) - Required - The base path under which the static files will be served. ### Request Example ```javascript const assetsUrl = manager.serve('public', 'assets'); // Files in public/ available at /webcm/my-component/assets/ ``` ### Response #### Success Response (200) - **assetsUrl** (string) - The base URL path where the served assets can be accessed. #### Response Example ```json { "assetsUrl": "/webcm/my-component/assets/" } ``` ``` -------------------------------- ### Client Created Event Handling Source: https://context7.com/managed-components/docs/llms.txt Shows how to handle the 'clientcreated' event, which fires when a new visitor is detected. It demonstrates generating a unique client ID, storing it using `client.set`, and attaching client-side event listeners. ```javascript manager.addEventListener('clientcreated', async event => { const { client } = event // Generate and store a unique client identifier const clientId = crypto.randomUUID() client.set('clientId', clientId, { scope: 'infinite' }) // Attach client-side event listeners client.attachEvent('scroll') client.attachEvent('mousedown') }) ``` -------------------------------- ### Serve Static Assets Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/serve.md Serves static assets from a specified directory and returns the mapped URL. The assets will be available under the same domain as your component. ```APIDOC ## serve ### Description Serve static assets. Returns the final URL mapped to your destination. ### Method `serve` (This is a method call within the manager object, not a standard HTTP method) ### Endpoint N/A (This is a programmatic API call) ### Parameters #### Arguments - **directory** (string) - Required - The local directory containing the static assets (e.g., 'public'). - **assetPath** (string) - Required - The path segment under which the assets will be exposed (e.g., 'assets'). ### Request Example ```javascript const myURL = manager.serve('public', 'assets') ``` ### Response #### Success Response - **URL** (string) - The final URL where the static assets are served. For example, if the tool's `public` directory is exposed under `/webcm/component-name/assets`, this URL will reflect that mapping. ``` -------------------------------- ### Declare and Attach Client Event Listeners with manager.createEventListener Source: https://context7.com/managed-components/docs/llms.txt Sets up event listeners on the client-side. It involves two steps: first declaring the listener using `createEventListener` and then attaching it to specific clients using `attachEvent`. This pattern manages the asynchronous nature of client connections. ```javascript manager.createEventListener('scroll', async event => { console.log('Scroll event:', event.payload) // payload: { scrollLeft: 0, scrollTop: 77.72, scrollX: 0, scrollY: 77.72, target: "body", timestamp: 1653923753892 } }) manager.createEventListener('mousedown', async event => { console.log('Click at:', event.payload.clientX, event.payload.clientY) // payload: { target: "body", timestamp: 1653923456438, altKey: false, clientX: 276, clientY: 403 } }) // Step 2: Attach events when client is created manager.addEventListener('clientcreated', ({ client }) => { client.attachEvent('scroll') client.attachEvent('mousedown') }) ``` -------------------------------- ### Handle Client Creation Event with JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/manager-events/clientcreated.md This snippet demonstrates how to listen for the 'clientcreated' event using JavaScript. When a new client is created, this event listener will execute, allowing you to access the client object and set custom properties like 'clientNumber'. This is useful for tracking or initializing client-specific data. ```javascript manager.addEventListener('clientcreated', async event => { const { client } = event const num = Math.random() client.set('clientNumber', num.toString()) }) ``` -------------------------------- ### Component Structure and Initialization Source: https://context7.com/managed-components/docs/llms.txt Defines the basic structure of a Managed Component. It exports a default async function that receives a manager object and settings, used to register event listeners, proxy server-side requests, and register UI widgets. ```javascript export default async function (manager, settings) { // Register event listeners manager.addEventListener('pageview', async event => { const { client } = event console.log('Page viewed:', client.url.href) }) // Set up server-side functionality manager.proxy('/api', 'https://api.example.com') // Register widgets manager.registerWidget(async () => { return '' }) } ``` -------------------------------- ### Create Performance Event Listener (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/performance-entries.md This snippet demonstrates how to create an event listener for 'performance' events using the manager object. It logs new performance entries to the console. No external dependencies are required beyond the manager object. ```javascript manager.createEventListener('performance', async event => { console.info('New performance entries!', event.payload) }) ``` -------------------------------- ### Proxy API Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/proxy.md Creates a reverse proxy from a specified path to another server. This is useful for accessing external tool vendor servers without browser domain restrictions. It also supports optional caching configurations for static assets. ```APIDOC ## `proxy` API ### Description Creates a reverse proxy from a specified path to another server. This is useful for accessing external tool vendor servers without browser domain restrictions. It also supports optional caching configurations for static assets. ### Method POST ### Endpoint `/managed-components/docs/proxy` ### Parameters #### Query Parameters - **path** (string) - Required - The local path to proxy from. - **targetUrl** (string) - Required - The external URL to proxy to. - **options** (object) - Optional - Configuration options for the proxy. - **cache** (string) - Optional - Caching strategy. Can be 'never', 'always', or 'auto'. Defaults to 'auto'. ### Request Example ```js const myURL = manager.proxy('/api', 'https://api.example.com') // With caching options manager.proxy('/assets', 'https://assets.example.com', { cache: 'always' }) ``` ### Response #### Success Response (200) - **proxyUrl** (string) - The URL of the created proxy endpoint. #### Response Example ```json { "proxyUrl": "/webcm/component-name/api" } ``` ``` -------------------------------- ### Listen for Visibility Change Events (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/visibility-change.md This snippet demonstrates how to create an event listener for 'visibilityChange' events using the manager object. It logs the event payload to the console when the page's visibility state changes. No external dependencies are required beyond the manager object. ```javascript manager.createEventListener('visibilityChange', async event => { console.info('Page visibility toggled!', event.payload) }) ``` -------------------------------- ### Ecommerce Event Handling Source: https://context7.com/managed-components/docs/llms.txt Illustrates handling the 'ecommerce' event for tracking e-commerce actions like purchases. It checks the event name and sends transaction details to a server-side endpoint using `manager.fetch`. ```javascript manager.addEventListener('ecommerce', async event => { const { name, payload, client } = event if (name === 'Purchase') { await manager.fetch('https://conversions.example.com/track', { method: 'POST', body: JSON.stringify({ event: 'purchase', transactionId: payload.transactionId, value: payload.total, currency: payload.currency, items: payload.items, clientId: await client.get('clientId') }) }) } }) ``` -------------------------------- ### Perform POST Request with Fetch Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/fetch.md This snippet illustrates how to execute a POST HTTP request using `manager.fetch`. It includes sending a JSON payload in the request body. Ensure the data is correctly stringified before sending. ```javascript await manager.fetch("https://api.example.com/api", { method: "POST", body: JSON.stringify({ data: "my data" }), }); ``` -------------------------------- ### Handle Pageview Event with JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/manager-events/pageview.md This snippet listens for the 'pageview' event and sends a server-side POST request to 'https://example.com/collect'. The request includes the current page's URL and title. It requires a 'manager' object with an 'addEventListener' method. ```javascript manager.addEventListener('pageview', async event => { const { client } = event // Send server-side request fetch('https://example.com/collect', { method: 'POST', data: { url: client.url.href, title: client.title, }, }) }) ``` -------------------------------- ### Server-Side Fetch API Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/fetch.md This section details how to use the `fetch` method provided by the managed components environment to make server-side HTTP requests. It supports standard Fetch API options. ```APIDOC ## Server-Side Fetch API ### Description Perform an HTTP request server-side. It follows the [DOM `fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) argument structure. ### Method GET, POST, PUT, DELETE, etc. (Any valid HTTP method supported by the Fetch API) ### Endpoint This method is called directly on the `manager` object, not a specific endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - An object containing fetch options such as `method`, `headers`, `body`, etc. (See MDN Fetch API documentation for details). ### Request Example ```javascript // a simple GET request const response = await manager.fetch('https://api.example.com/api'); const result = await response.json(); ``` ```javascript await manager.fetch("https://api.example.com/api", { method: "POST", body: JSON.stringify({ data: "my data" }), }); ``` ### Response #### Success Response (200) The response object conforms to the standard `Response` object from the Fetch API. #### Response Example ```javascript // Example for a JSON response { "key": "value" } ``` #### Error Handling Errors during the fetch operation (e.g., network errors, non-2xx status codes) will typically throw an exception or be reflected in the `response.ok` property and `response.status`. ``` -------------------------------- ### Create Reverse Proxy with `proxy` Component (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/proxy.md Creates a reverse proxy from a given path to a target server URL. This is useful for accessing external APIs or resources without exposing the original domain. The `manager.proxy` function takes the local path, the target URL, and an optional caching configuration object. ```javascript const myURL = manager.proxy('/api', 'https://api.example.com') ``` ```javascript manager.proxy('/assets', 'https://assets.example.com', { cache: 'always' }) ``` ```javascript { cache: 'auto' // `never`, `always`, or `auto`. `auto` will cache based on the cache-control header of the responses. } ``` -------------------------------- ### Run Arbitrary JavaScript in Client Browser with client.execute Source: https://context7.com/managed-components/docs/llms.txt Enables running arbitrary JavaScript code within the client's browser environment. Due to security considerations, this requires the `execute_unsafe_scripts` permission. It can be used for logging or injecting custom tracking scripts. ```javascript manager.addEventListener('event', async ({ client, context }) => { // Log to browser console client.execute("console.log('Managed Component loaded successfully');") // Inject custom tracking client.execute(` window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: '${context.eventName}', timestamp: ${Date.now()} }); `) }) ``` -------------------------------- ### Store and Retrieve Client-Side Data with client.set and client.get Source: https://context7.com/managed-components/docs/llms.txt Enables storing and retrieving data on the client-side, typically mapping to browser cookies or localStorage. Data can be scoped to the current page, the browser session, or persist indefinitely. Expiry times can also be specified. ```javascript // Store data with different persistence scopes client.set('viewCount', '1', { scope: 'page' }) // Page session only client.set('sessionId', 'abc123', { scope: 'session' }) // Browser session client.set('userId', 'user-456', { scope: 'infinite' }) // Persistent // Set with explicit expiry (30 days in milliseconds) client.set('campaign', 'summer2024', { scope: 'infinite', expiry: 30 * 24 * 60 * 60 * 1000 }) // Retrieve stored values const userId = await client.get('userId') // Get value from another tool's namespace const fbPixelId = await client.get('uuid', 'facebook-pixel') ``` -------------------------------- ### Define Custom Route Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/route.md This section details how to define a custom server-side route using the `manager.route` function. This allows for direct execution of logic without a proxy, enhancing performance and reliability. ```APIDOC ## POST /managed-components/docs/route ### Description Defines custom server-side logic for a managed component. The returned string is the final URL that will be mapped. These routes run directly on the server without a proxy, offering increased speed and reliability. ### Method POST ### Endpoint `/managed-components/docs/route` ### Parameters #### Request Body - **path** (string) - Required - The path for the route (e.g., '/ping'). - **handler** (function) - Required - A function that takes a `request` object and returns a `Response` object. ### Request Example ```json { "path": "/ping", "handler": "(request) => new Response(204)" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the route has been defined. - **mappedUrl** (string) - The final URL path that has been mapped by this route. #### Response Example ```json { "message": "Route defined successfully.", "mappedUrl": "/webcm/component-name/ping" } ``` #### Error Response (400) - **error** (string) - An error message if the request body is invalid or missing required fields. ``` -------------------------------- ### Create Reverse Proxy with manager.proxy Source: https://context7.com/managed-components/docs/llms.txt Sets up a reverse proxy to forward requests from a specified path on your domain to an external server. This can improve performance and privacy by making external requests appear to originate from your domain. Options include caching behavior ('always', 'never', 'auto'). ```javascript // Basic proxy setup const apiUrl = manager.proxy('/api', 'https://api.example.com') // Requests to /webcm/my-component/api/* proxy to api.example.com/* // Proxy with aggressive caching for static assets manager.proxy('/assets', 'https://cdn.example.com', { cache: 'always' }) // Proxy with no caching for dynamic content manager.proxy('/realtime', 'https://live.example.com', { cache: 'never' }) // Default caching respects origin cache-control headers manager.proxy('/content', 'https://content.example.com', { cache: 'auto' }) ``` -------------------------------- ### Key-Value Storage with manager.set and manager.get Source: https://context7.com/managed-components/docs/llms.txt Provides server-side persistent storage for key-value data, enabling the persistence of component state across requests. This is ideal for storing configuration, counters, or other stateful information. ```javascript // Store server-side configuration manager.set('lastSync', Date.now().toString()) manager.set('totalEvents', '0') // Retrieve stored values const lastSync = await manager.get('lastSync') let eventCount = parseInt(await manager.get('totalEvents') || '0') // Increment counter manager.addEventListener('event', async () => { eventCount++ manager.set('totalEvents', eventCount.toString()) }) ``` -------------------------------- ### Instantiate and Attach Client Event Listener (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/index.md This snippet demonstrates how to create a client event listener for 'mousedown' using `manager.createEventListener` and then attach it to a client when it's created using `client.attachEvent`. It logs the event payload to the console. ```javascript manager.createEventListener('mousedown', async event => { console.info('🐁 ⬇️ Mousedown:', event.payload) }) manager.addEventListener('clientcreated', ({ client }) => { client.attachEvent('mousedown') }) ``` -------------------------------- ### manager.route Source: https://context7.com/managed-components/docs/llms.txt Defines custom server-side endpoints with full control over request handling. Logic runs locally, making it faster than proxying. ```APIDOC ## POST /managed-components/docs/manager.route ### Description Define custom server-side endpoints with full control over request handling. Faster than proxying since logic runs locally. ### Method POST ### Endpoint /managed-components/docs/manager.route ### Parameters #### Query Parameters - **path** (string) - Required - The endpoint path to define. - **handler** (function) - Required - A function that handles incoming requests and returns a Response object. ### Request Example ```javascript manager.route('/ping', request => { return new Response('pong', { status: 200 }) }); manager.route('/config', request => { return new Response(JSON.stringify({ version: '1.0.0', features: ['analytics', 'widgets'] }), { status: 200, headers: { 'Content-Type': 'application/json' } }); }); manager.route('/webhook', async request => { const body = await request.json(); await processWebhook(body); return new Response(null, { status: 204 }); }); ``` ### Response #### Success Response (200) Indicates that the route was successfully registered. #### Response Example (No specific response body, success is indicated by status code) ``` -------------------------------- ### manager.set and manager.get (KV Storage) Source: https://context7.com/managed-components/docs/llms.txt Store and retrieve persistent key-value data on the server side. This is useful for component state that persists across requests. ```APIDOC ## POST /managed-components/docs/manager.set & POST /managed-components/docs/manager.get ### Description Store and retrieve persistent key-value data on the server side. Useful for component state that persists across requests. ### Method POST ### Endpoint /managed-components/docs/manager.set /managed-components/docs/manager.get ### Parameters #### manager.set - **key** (string) - Required - The key under which to store the value. - **value** (string) - Required - The value to store. #### manager.get - **key** (string) - Required - The key of the value to retrieve. ### Request Example ```javascript // Store server-side configuration manager.set('lastSync', Date.now().toString()); manager.set('totalEvents', '0'); // Retrieve stored values const lastSync = await manager.get('lastSync'); let eventCount = parseInt(await manager.get('totalEvents') || '0'); // Increment counter manager.addEventListener('event', async () => { eventCount++; manager.set('totalEvents', eventCount.toString()); }); ``` ### Response #### Success Response (200) for manager.set Indicates that the key-value pair was successfully stored. #### Success Response (200) for manager.get - **value** (string) - The retrieved value associated with the key, or null if the key does not exist. #### Response Example (manager.get) ```json { "value": "1678886400000" } ``` ``` -------------------------------- ### manager.addEventListener - Pageview Event Source: https://context7.com/managed-components/docs/llms.txt Handles the 'pageview' event, which fires on each new page request. Useful for analytics and client-specific state initialization. ```APIDOC ## manager.addEventListener - Pageview Event The `pageview` event fires whenever a request for a new page is made. Use this to track page loads, send analytics data, or initialize client-specific state. ### Code Example ```javascript manager.addEventListener('pageview', async event => { const { client } = event // Send server-side analytics request await manager.fetch('https://analytics.example.com/collect', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: client.url.href, title: client.title, referrer: client.referer, userAgent: client.userAgent, timestamp: Date.now() }) }) }) ``` ``` -------------------------------- ### Dispatch and Handle Events with JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/manager-events/user-events.md This JavaScript snippet demonstrates how to add an event listener to a manager. The listener handles an event by making a server-side POST request and conditionally performing client-side actions based on the user's browser agent. It requires the 'fetch' API and a 'uuidv4' function. ```javascript manager.addEventListener('event', async ({ context, client }) => { // Send server-side request fetch('https://example.com/collect', { method: 'POST', data: { ip: context.system.device.ip, eventName: context.eventName, }, }) // Check client browser if (client.userAgent.includes('Chrome')) { client.set('example-uuid', uuidv4()) client.fetch( `https://example.com/collectFromBrowser?dt=${system.page.title}` ) } }) ``` -------------------------------- ### Return Values from Component to Client with client.return Source: https://context7.com/managed-components/docs/llms.txt Facilitates bidirectional communication by allowing a component to return a value that can be accessed by the client-side website code. This is useful for scenarios like calculations or retrieving user segment information. ```javascript // In the Managed Component manager.addEventListener('event', async ({ context, client }) => { if (context.eventName === 'calculate') { const result = context.x * context.y client.return(result) } if (context.eventName === 'getUserSegment') { const segment = await determineUserSegment(client) client.return({ segment, confidence: 0.95 }) } }) // On the website (client-side) const response = await manager.track('calculate', { x: 21, y: 2 }) const result = response.return['myTool'] // = 42 ``` -------------------------------- ### Run JavaScript in Browser Console using client.execute Source: https://github.com/managed-components/docs/blob/main/specs/client/execute.md This snippet demonstrates how to use `client.execute` to run a simple JavaScript command, like logging a message to the browser's developer console. It's typically used within an event listener to react to specific triggers. ```javascript manager.addEventListener('event', async ({ context, payload, client }) => { client.execute("console.log('Hello World');") }) ``` -------------------------------- ### Define Custom Server-Side Endpoints with manager.route Source: https://context7.com/managed-components/docs/llms.txt Allows the definition of custom server-side endpoints with complete control over request handling. This is generally faster than proxying as the logic executes locally. Supports handling various request types, including JSON payloads. ```javascript // Simple health check endpoint manager.route('/ping', request => { return new Response('pong', { status: 200 }) }) // JSON API endpoint manager.route('/config', request => { return new Response(JSON.stringify({ version: '1.0.0', features: ['analytics', 'widgets'] }), { status: 200, headers: { 'Content-Type': 'application/json' } }) }) // Handle POST data manager.route('/webhook', async request => { const body = await request.json() // Process webhook payload await processWebhook(body) return new Response(null, { status: 204 }) }) ``` -------------------------------- ### client.return Source: https://github.com/managed-components/docs/blob/main/specs/client/return.md This method is used within an event listener to return a value to the client. The client can then access this returned value. ```APIDOC ## client.return ### Description Return a value to the client so that it can use it. ### Method Not applicable (This is a method call within an event listener). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript manager.addEventListener('event', async ({ context, payload, client }) => { if (context.eventName === 'multiply') { client.return(context.x * context.y) } }) ``` ### Response #### Success Response (200) Returns the value passed to the `client.return` method. #### Response Example ```javascript // On the browser side: const value = await manager.track('multiply', { x: 21, y: 2 }) const result = value.return['exampleTool'] // = 42 ``` ``` -------------------------------- ### Register Weather Widget using JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/embed-and-widgets/widgets.md Registers a weather widget that fetches and displays temperature data for a specified location. It utilizes the manager.useCache function for caching weather data and manager.fetch for API requests. Error handling for the fetch operation is included. ```javascript manager.registerWidget(async () => { const location = "Colombia"; const widget = await manager.useCache("weather-" + location, async () => { try { const response = await manager.fetch( `https://wttr.in/${location}?format=j1` ); const data = await response.json(); const [summary] = data.current_condition; const { temp_C } = summary; return `Temperature in ${location} is: ${temp_C} ℃
`; } catch (error) { console.error("error fetching weather for widget:", error); } }); return widget; }); ``` -------------------------------- ### manager.addEventListener - User-Configured Events Source: https://context7.com/managed-components/docs/llms.txt Listens for custom events dispatched from the website, allowing access to both server-side context and client information for flexible tracking. ```APIDOC ## manager.addEventListener - User-Configured Events Listen for custom events dispatched from the website. These events provide access to both server-side context and client information for flexible tracking scenarios. ### Code Example ```javascript manager.addEventListener('event', async ({ context, client }) => { // Server-side request with visitor context await manager.fetch('https://example.com/collect', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ip: context.system.device.ip, eventName: context.eventName, pageTitle: context.system.page.title, customData: context.payload }) }) // Conditional client-side actions if (client.userAgent.includes('Chrome')) { client.set('session-id', crypto.randomUUID(), { scope: 'session' }) client.fetch('https://example.com/pixel.gif') } }) ``` ``` -------------------------------- ### Add Custom Event Listener to Manager Source: https://github.com/managed-components/docs/blob/main/specs/manager-events/index.md Demonstrates how to add a custom event listener to the manager object. This allows tools to react to specific events emitted by the manager, such as a 'hello' event. No external dependencies are required beyond the manager object itself. ```javascript manager.addEventListener('hello', event => { console.log("Hello") }) ``` -------------------------------- ### Create Resize Event Listener in JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/client-events/resize.md This snippet demonstrates how to create an event listener for the 'resize' event using the manager object. It logs the new window dimensions to the console when the event is triggered. No external dependencies are required beyond the manager object. ```javascript manager.createEventListener('resize', async event => { console.info('New window size!', event.payload) }) ``` -------------------------------- ### manager.proxy Source: https://context7.com/managed-components/docs/llms.txt Creates a reverse proxy to an external server. Requests to a specified path on your domain are forwarded to the external server, appearing to originate from your domain for performance and privacy benefits. ```APIDOC ## POST /managed-components/docs/manager.proxy ### Description Creates a reverse proxy from a path on your domain to an external server. Requests appear to originate from the same domain, improving performance and privacy. ### Method POST ### Endpoint /managed-components/docs/manager.proxy ### Parameters #### Query Parameters - **path** (string) - Required - The path on your domain to proxy requests from. - **url** (string) - Required - The external server URL to proxy requests to. - **options** (object) - Optional - Configuration options for the proxy. - **cache** (string) - Optional - Caching strategy ('always', 'never', 'auto'). Defaults to 'auto'. ### Request Example ```json { "path": "/api", "url": "https://api.example.com", "options": { "cache": "always" } } ``` ### Response #### Success Response (200) - **proxyUrl** (string) - The URL where the proxy is accessible. #### Response Example ```json { "proxyUrl": "/webcm/my-component/api/*" } ``` ``` -------------------------------- ### manager.addEventListener - Ecommerce Event Source: https://context7.com/managed-components/docs/llms.txt Handles 'ecommerce' events for actions like purchases and cart updates. Includes event name and payload for transaction details. ```APIDOC ## manager.addEventListener - Ecommerce Event The `ecommerce` event handles e-commerce specific actions like purchases, cart updates, and product views. The event includes a `name` property indicating the action type and a `payload` with transaction details. ### Code Example ```javascript manager.addEventListener('ecommerce', async event => { const { name, payload, client } = event if (name === 'Purchase') { await manager.fetch('https://conversions.example.com/track', { method: 'POST', body: JSON.stringify({ event: 'purchase', transactionId: payload.transactionId, value: payload.total, currency: payload.currency, items: payload.items, clientId: await client.get('clientId') }) }) } }) ``` ``` -------------------------------- ### Return Value from Event Listener (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client/return.md This snippet shows how to use `client.return` inside an event listener to send a computed value back to the client. The value is calculated based on input `context.x` and `context.y` when the event name is 'multiply'. ```javascript manager.addEventListener('event', async ({ context, payload, client }) => { if (context.eventName === 'multiply') { client.return(context.x * context.y) } }) ``` -------------------------------- ### Listen for Page Show Event (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/page-show.md This snippet demonstrates how to create an event listener for the 'pageShow' event using the manager.createEventListener function. It logs the event payload to the console. This listener is useful for reacting to when a page is shown, potentially after being hidden or navigated away from. ```javascript manager.createEventListener('pageShow', async (event) => { console.info('pageShow payload:', event.payload) }) ``` -------------------------------- ### Define Custom Route with JavaScript Source: https://github.com/managed-components/docs/blob/main/specs/server-functionality/route.md Defines a custom server-side route for a managed component using JavaScript. It takes a path and a request handler function. The handler function receives the request object and should return a Response object. This logic runs directly on the server without a proxy. ```javascript const myURL = manager.route('/ping', request => { return new Response(204) }) ``` -------------------------------- ### Create Mouse Up Event Listener (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/mouseup.md This snippet demonstrates how to create an event listener for the 'mouseup' event using the `manager.createEventListener` function. It logs the event payload to the console. No external dependencies are required beyond the `manager` object. ```javascript manager.createEventListener('mouseup', async (event) => { console.info('🐁 ⬆️ Mouseup payload:', event.payload) }) ``` -------------------------------- ### Register Floating Widget with Cache - JavaScript Source: https://context7.com/managed-components/docs/llms.txt Registers a floating widget that appends to the page body. It utilizes a cache for promotional data fetched from an API, with a specified TTL. The widget's HTML content is dynamically generated. ```javascript manager.registerWidget(async () => { const notification = await manager.useCache('promo-banner', async () => { const response = await manager.fetch('https://api.example.com/promo') const promo = await response.json() return ` ` }, 3600) return notification }) ``` -------------------------------- ### Listen for SPA Navigation Changes and Send Data (JavaScript) Source: https://github.com/managed-components/docs/blob/main/specs/client-events/spa-navigation.md This snippet demonstrates how to create an event listener for the 'historyChange' event. When the event fires, it sends a POST request to a specified URL with the client's current URL and title as payload. This is useful for tracking user navigation within SPAs. ```javascript manager.createEventListener('historyChange', async event => { const { client } = event // Send server-side request fetch('https://example.com/collect', { method: 'POST', data: { url: client.url.href, title: client.title, }, }) }) ``` -------------------------------- ### HTML Embed Placeholder Source: https://github.com/managed-components/docs/blob/main/specs/embed-and-widgets/embeds.md Defines a placeholder div element on a webpage to indicate where an embed should be placed. It uses custom data attributes to specify the embed type and its configuration, such as theme and location. ```html ```