Browser-compatible polyfill for Node.js's diagnostics_channel API. This package provides the core diagnostics channel functionality that works in browser environments, including integration with AsyncLocalStorage via als-browser.
import { channel } from 'dc-browser';const requestChannel = channel('http.request');// Subscribe to messagesrequestChannel.subscribe((message, name) => { console.log(`Received on ${name}:`, message);});// Publish a messagerequestChannel.publish({ url: '/api/data', method: 'GET' });
TracingChannel
TracingChannel provides structured tracing with start, end, asyncStart, asyncEnd, and error events:
import { tracingChannel } from 'dc-browser';const httpChannel = tracingChannel('http.request');// Subscribe to eventshttpChannel.subscribe({ start: (context) => { console.log('Request started:', context); }, end: (context) => { console.log('Request ended:', context); }, error: (context) => { console.error('Request error:', context.error); }});// Trace a synchronous operationconst result = httpChannel.traceSync(() => { // Your sync code here return fetchData();}, { requestId: 'req-123' });// Trace a promise-based operationconst data = await httpChannel.tracePromise(async () => { // Your async code here return await fetch('/api/data');}, { requestId: 'req-456' });
AsyncLocalStorage Integration
Channels can be bound to AsyncLocalStorage instances to transform events into stored context:
import { channel } from 'dc-browser';import { AsyncLocalStorage } from 'als-browser';const requestChannel = channel('http.request');const requestContext = new AsyncLocalStorage();// Bind the store to the channelrequestChannel.bindStore(requestContext);// Now runStores will propagate context to the storerequestChannel.runStores({ requestId: 'req-789' }, () => { console.log(requestContext.getStore()); // { requestId: 'req-789' } // Context is available in the callback doWork();});function doWork() { const context = requestContext.getStore(); console.log('Current request:', context.requestId);}
Transform Function
You can provide a transform function when binding a store to extract/transform the message:
import { channel } from 'dc-browser';import { AsyncLocalStorage } from 'als-browser';const requestChannel = channel('http.request');const userIdStore = new AsyncLocalStorage<string>();// Extract just the userId from messagesrequestChannel.bindStore( userIdStore, (message) => message.userId);requestChannel.runStores({ userId: 'user-123', url: '/api/data' }, () => { console.log(userIdStore.getStore()); // 'user-123'});
Multiple Stores
You can bind multiple AsyncLocalStorage instances to a single channel: