### Start Express Server Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/express-ex/README.md Use this command to start the Express server. Ensure you have npm installed. ```bash npm start ``` -------------------------------- ### Install Dependencies Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/typescript-ex/README.md Install the necessary Node.js dependencies for the project. ```bash npm install ``` -------------------------------- ### Install and Compile Project Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/mqtt-ex/README.md Install project dependencies and compile the TypeScript code. ```bash npm install npm run compile ``` -------------------------------- ### Usage Examples Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md A collection of practical usage examples demonstrating various features of the CloudEvents JavaScript SDK. ```APIDOC ## Usage Examples ### Description Practical examples showcasing how to use different aspects of the CloudEvents JavaScript SDK. ### Examples Covered - Event creation - HTTP sending (binary and structured) - HTTP receiving (Express.js) - Kafka producer and consumer integration - MQTT publishing and subscribing - Internal event emission - Custom transport function implementation - Event chaining for sequential processing - Batch processing of multiple events - Robust error handling scenarios - Utilizing type-safe events with generics - Handling extension attributes - Working with binary data payloads ``` -------------------------------- ### Start MQTT Broker with Docker Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/mqtt-ex/README.md Start a Mosquitto MQTT broker in a Docker container, exposing port 1883. ```bash docker run -it -d -p 1883:1883 eclipse-mosquitto:2.0 mosquitto -c /mosquitto-no-auth.conf ``` -------------------------------- ### Start Kafka Producer Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/kafka-ex/README.md Starts the Node.js CLI producer to send CloudEvents messages to Kafka. Requires npm. ```bash npm run start:producer ``` -------------------------------- ### Start Kafka Consumer Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/kafka-ex/README.md Starts the Node.js CLI consumer to receive CloudEvents messages from Kafka. Requires npm and a Kafka groupId. ```bash npm run start:consumer ${groupId} ``` -------------------------------- ### Example Headers Usage Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/06-types-and-interfaces.md Illustrates how to define and populate a Headers object with common CloudEvents and content-type information. ```typescript const headers: Headers = { "content-type": "application/json", "ce-type": "com.example.event", "ce-id": "123" }; ``` -------------------------------- ### Run Zookeeper Docker Image Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/kafka-ex/README.md Starts a Zookeeper Docker container for Kafka. Ensure Zookeeper is running before starting Kafka. ```bash docker run -d \ --name zookeeper \ -e ZOOKEEPER_CLIENT_PORT=2181 \ -e ZOOKEEPER_TICK_TIME=2000 \ confluentinc/cp-zookeeper:7.3.2 ``` -------------------------------- ### Install CloudEvents SDK Source: https://github.com/cloudevents/sdk-javascript/blob/main/README.md Install the CloudEvents SDK for JavaScript using npm. This requires a current LTS version of Node.js (16.x or 18.x). ```console npm install cloudevents ``` -------------------------------- ### Run Kafka Docker Image Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/kafka-ex/README.md Starts a Kafka Docker container, connecting it to Zookeeper. This makes Kafka accessible on localhost:9092. ```bash docker run -d \ --name kafka \ -p 9092:9092 \ -e KAFKA_BROKER_ID=1 \ -e KAFKA_ZOOKEEPER_CONNECT=localhost:2181 \ -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 \ -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \ -e KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 \ --link zookeeper:zookeeper \ confluentinc/cp-kafka:7.3.2 ``` -------------------------------- ### Example Git Log with Signed Commit Source: https://github.com/cloudevents/sdk-javascript/blob/main/pr_guidelines.md An example of how a git log entry appears after a commit has been signed. The 'Author' and 'Signed-off-by' lines must match to pass automated DCO checks. ```git Author: Joe Smith Date: Thu Feb 2 11:41:15 2018 -0800 Update README Signed-off-by: Joe Smith ``` -------------------------------- ### Clone Repository and Add Upstream Remote Source: https://github.com/cloudevents/sdk-javascript/blob/main/pr_guidelines.md Clone the forked repository and add the original repository as an upstream remote. This is the initial setup step before making changes. ```console git clone https://github.com/mygithuborg/sdk-javascript.git cd sdk-javascript git remote add upstream https://github.com/cloudevents/sdk-javascript.git ``` -------------------------------- ### Transitioning Emit.send to HTTP.binary or HTTP.structured with Axios Source: https://github.com/cloudevents/sdk-javascript/blob/main/API_TRANSITION_GUIDE.md Replace Emit.send with HTTP.binary or HTTP.structured for emitting events. This example shows how to use Axios for HTTP transport. ```javascript const axios = require('axios').default; const { HTTP } = require("cloudevents"); const ce = new CloudEvent({ type, source, data }) const message = HTTP.binary(ce); // Or HTTP.structured(ce) axios({ method: 'post', url: '...', data: message.body, headers: message.headers, }); ``` -------------------------------- ### HTTP Protocol Binding Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Documentation for the HTTP protocol binding, supporting binary, structured, and batch modes with examples. ```APIDOC ## HTTP Protocol Binding ### Description Handles CloudEvents over HTTP, supporting different encoding modes. ### Modes - **Binary Mode**: Event data and attributes are sent in separate HTTP parts. - **Structured Mode**: Event data and attributes are combined into a single JSON payload. - **Batch Mode**: Multiple events are sent in a single HTTP request, typically as a JSON array. ### Functions - **HTTP.binary(event)**: Serializes a CloudEvent into the HTTP binary format. - **HTTP.structured(event)**: Serializes a CloudEvent into the HTTP structured format. - **HTTP.toEvent(headers, body)**: Deserializes an HTTP request into a CloudEvent object. - **HTTP.isEvent(headers, body)**: Detects if an HTTP request represents a CloudEvent. ### Examples Refer to the 'Usage Examples' section for detailed HTTP sending and receiving examples. ``` -------------------------------- ### Run Kafka with Docker Compose Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/kafka-ex/README.md Starts Zookeeper and Kafka using a docker compose file. Navigate to the directory containing the docker compose file before running. ```bash cd ${directory of the docker compose file} docker compose up -d ``` -------------------------------- ### Sending and Receiving CloudEvents with MQTT Client Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/04-mqtt-binding.md Provides a complete example of using an MQTT client to publish a structured CloudEvent and subscribe to receive CloudEvents. It shows how to serialize the event for publishing and deserialize the payload upon receiving. ```typescript import { CloudEvent, MQTT } from "cloudevents"; import mqtt from "mqtt"; const client = mqtt.connect("mqtt://localhost:1883"); // Send a CloudEvent over MQTT const event = new CloudEvent({ source: "/myapp", type: "data.processed", data: { result: "success" } }); const message = MQTT.structured(event); client.publish("events/processed", JSON.stringify(message.body), { properties: { contentType: message.PUBLISH?.["Content Type"] } }); // Receive a CloudEvent over MQTT client.on("message", (topic, mqttPayload) => { const event = MQTT.toEvent({ headers: {}, body: JSON.parse(mqttPayload.toString()), PUBLISH: { "Content Type": "application/cloudevents+json" } }); console.log("Received event:", event.type); }); ``` -------------------------------- ### Configuration: Environment Variables Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/COMPLETION_REPORT.txt Supports configuration via environment variables. For example, CE_USE_BIG_INT can be set to enable BigInt support for numeric values. ```javascript # Set environment variable before running the application export CE_USE_BIG_INT=true # In your code: const useBigInt = process.env.CE_USE_BIG_INT === 'true'; ``` -------------------------------- ### CloudEvents SDK Base64 Data Decoding Example Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/09-parsers-and-formats.md Demonstrates how to create a CloudEvent with base64 encoded data and how the SDK automatically decodes it. Ensure the 'cloudevents' package is imported. ```typescript import { CloudEvent } from "cloudevents"; // Create event with base64-encoded data const base64Data = Buffer.from("Hello, World!").toString("base64"); const event = new CloudEvent({ source: "/app", type: "base64.data", data_base64: base64Data, datacontenttype: "text/plain" }); // Data is automatically decoded console.log(event.data); // Uint8Array ``` -------------------------------- ### Configure Emitter with HTTP Binding and Structured Mode Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/README.md Configure the emitter function with specific binding and mode options. This example shows how to use the HTTP binding with the structured message mode. ```typescript emitterFor(transport, { binding: HTTP, mode: Mode.STRUCTURED }) ``` -------------------------------- ### Transitioning Receiver.accept to HTTP.toEvent Source: https://github.com/cloudevents/sdk-javascript/blob/main/API_TRANSITION_GUIDE.md Use HTTP.toEvent to parse incoming HTTP requests into CloudEvents. This example demonstrates its usage with Express.js. ```javascript const app = require("express")(); const { HTTP } = require("cloudevents"); app.post("/", (req, res) => { // body and headers come from an incoming HTTP request, e.g. express.js const receivedEvent = HTTP.toEvent({ headers: req.headers, body: req.body }); console.log(receivedEvent); }); ``` -------------------------------- ### BigInt Support Example: Precision Comparison Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Compares JSON parsing with and without BigInt mode enabled, demonstrating precision loss in standard JavaScript numbers versus exact preservation with BigInt. ```typescript // Without BigInt mode - precision loss const data1 = JSON.parse('{"tweetId": 1234567890123456789}'); console.log(data1.tweetId); // 1.2345678901234568e+18 (precision lost) // With BigInt mode - full precision process.env.CE_USE_BIG_INT = "true"; const data2 = JSON.parse('{"tweetId": 1234567890123456789}'); console.log(data2.tweetId); // 1234567890123456789n (exact value) ``` -------------------------------- ### Publish CloudEvents to MQTT Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/10-usage-examples.md This snippet demonstrates publishing CloudEvents to an MQTT broker using structured mode. Ensure you have an MQTT broker running and the mqtt library installed. ```typescript import { CloudEvent, MQTT } from "cloudevents"; import mqtt from "mqtt"; const client = mqtt.connect("mqtt://broker.example.com"); async function publishMQTTEvent() { const event = new CloudEvent({ source: "/sensors/warehouse", type: "temperature.reading", subject: "warehouse/zone-a", datacontenttype: "application/json", data: { zone: "A", temperature: 22.5, humidity: 45 } }); // Use structured mode for MQTT const message = MQTT.structured(event); client.publish("events/temperature", message.body as string, { properties: { contentType: message.PUBLISH?.["Content Type"] } }, (err) => { if (err) { console.error("Failed to publish:", err); } else { console.log("Event published"); } }); } client.on("connect", publishMQTTEvent); ``` -------------------------------- ### CloudEvents SDK Date Normalization Example Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/09-parsers-and-formats.md Shows how date strings in CloudEvents are automatically normalized to ISO 8601 format upon event creation. The 'cloudevents' package must be imported. ```typescript import { CloudEvent } from "cloudevents"; // Date strings are automatically normalized const event = new CloudEvent({ source: "/app", type: "event", time: "2023-01-15T12:30:00Z" // Already ISO format }); console.log(event.time); // "2023-01-15T12:30:00.000Z" ``` -------------------------------- ### Implement Detector for CloudEvent Headers Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/06-types-and-interfaces.md Example implementation of the Detector interface to check for essential CloudEvent headers (ce-id and ce-type). ```typescript const detector: Detector = (message) => { return !!(message.headers["ce-id"] && message.headers["ce-type"]); }; ``` -------------------------------- ### Create Emitter with Custom Transport Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/05-emitter.md Example of defining a custom transport function using fetch and then creating an emitter with it using emitterFor. ```typescript import { Message, Options } from "cloudevents"; // Custom transport function using fetch const customTransport = async (message: Message, options: Options = {}): Promise => { const response = await fetch("https://api.example.com/events", { method: "POST", headers: message.headers as Record, body: message.body as string }); return response.json(); }; // Use with emitterFor import { emitterFor } from "cloudevents"; const emit = emitterFor(customTransport); ``` -------------------------------- ### Receive a CloudEvent using Express Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/README.md Sets up an Express.js server to receive incoming HTTP POST requests, parse them as CloudEvents, and log the event type. This snippet requires Express.js to be installed. ```typescript import express from "express"; import { HTTP } from "cloudevents"; const app = express(); app.use(express.json()); app.post("/", (req, res) => { const event = HTTP.toEvent({ headers: req.headers, body: req.body }); console.log("Received:", event.type); res.json({ ok: true }); }); app.listen(3000); ``` -------------------------------- ### Emit Internal CloudEvents with Multiple Handlers Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/10-usage-examples.md This example demonstrates how to register multiple handlers for a specific CloudEvent type and emit an event that all registered handlers will process. ```typescript import { CloudEvent, Emitter } from "cloudevents"; // Register event handlers Emitter.on("cloudevent", async (event: CloudEvent) => { console.log("Handler 1 - Received:", event.type); // Simulate async work await new Promise(resolve => setTimeout(resolve, 100)); }); Emitter.on("cloudevent", async (event: CloudEvent) => { console.log("Handler 2 - Received:", event.type); }); // Emit event from anywhere in the app async function processOrder(orderId: string) { // ... process order ... const orderEvent = new CloudEvent({ source: "/order-service", type: "order.completed", subject: `order/${orderId}`, data: { orderId, status: "completed" } }); // Emit - all handlers receive it await orderEvent.emit(true); // Wait for all handlers console.log("All handlers completed"); } processOrder("ORD-123").catch(console.error); ``` -------------------------------- ### CloudEvents SDK JavaScript - Technical Reference Documentation Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/COMPLETION_REPORT.txt This report summarizes the completion of the technical reference documentation for the CloudEvents JavaScript SDK. It details the scope, deliverables, and coverage analysis of the documentation, ensuring all exported symbols, public methods, return types, error cases, types, constants, and code examples are documented. ```APIDOC ## Project Completion Report: CloudEvents SDK JavaScript ### Description This document provides a comprehensive overview of the completion status for the technical reference documentation of the CloudEvents JavaScript SDK. It details the project's scope, the generated deliverables, and a thorough coverage analysis of the documented components, including classes, protocol bindings, functions, types, enumerations, configuration, error handling, and parsers. ### Deliverables The project successfully generated 12 markdown documentation files, totaling 5,026 lines and 152KB. These include primary reference documents for the CloudEvent class, HTTP, Kafka, and MQTT bindings, emitter, types and interfaces, errors and validation, constants and configuration, parsers and formats, and usage examples. Support documents include a master index (README.md) and coverage details (MANIFEST.md). ### Coverage Analysis **Exported Classes:** - CloudEvent (constructor, 7 methods) - ValidationError (with detailed documentation) - Emitter (3 static methods) **Protocol Bindings:** - HTTP (binary, structured, batch modes) - Kafka (with partition key mapping) - MQTT (with factory function) **Functions (15 total):** - emitterFor() - httpTransport() - HTTP.binary(), HTTP.structured(), HTTP.toEvent(), HTTP.isEvent() - Kafka.binary(), Kafka.structured(), Kafka.toEvent(), Kafka.isEvent() - MQTT.binary(), MQTT.structured(), MQTT.toEvent(), MQTT.isEvent() - MQTTMessageFactory() **Types & Interfaces (15 total):** - CloudEventV1 - CloudEventV1Attributes - CloudEventV1OptionalAttributes - Message - Headers - Binding - Serializer, Deserializer, Detector - KafkaMessage, KafkaEvent - MQTTMessage - TransportFunction, EmitterFunction, Options - TypeArray **Enumerations:** - Mode (BINARY, STRUCTURED, BATCH) - V1, V03 (Version constants) **Configuration:** - CONSTANTS object (40+ constants) - Environment variables (CE_USE_BIG_INT) - BigInt support configuration **Error Handling:** - ValidationError class - All error conditions (HTTP, Kafka, MQTT) - Recovery strategies (3 documented) - Common patterns (4 documented) **Parsers & Formats:** - JSONParser - PassThroughParser - Base64Parser - DateParser - Content type mapping - Encoding handling ### Documentation Quality Each major document includes full API signatures, parameter tables, return type documentation, error/exception documentation, multiple practical code examples, related type references, and source file citations. The documentation boasts over 100 code examples, 50+ parameter tables, complete type signatures, documented error cases, and bidirectional cross-references. Quality assurance confirms all exported symbols, public methods, return types, error cases, types, constants, and code examples are accurately documented and runnable, with consistent formatting and terminology. ``` -------------------------------- ### Example Conventional Commit Message Source: https://github.com/cloudevents/sdk-javascript/blob/main/pr_guidelines.md Follows the Conventional Commits specification for commit messages. The first line should be prefixed with a type, be a single sentence without a period, and succinctly describe the change. ```log docs: remove 0.1, 0.2 spec support from README ``` -------------------------------- ### Initialize WebSocket and Event Handling Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/websocket/index.html Sets up a WebSocket connection, defines message handlers for receiving CloudEvents, and configures an input listener to send weather query events. ```javascript const CloudEvent = window.cloudevents.CloudEvent; const Version = window.cloudevents.Version; const socket = new WebSocket("ws://localhost:8080"); function print(weather) { const data = weather; const summary = `

Current weather for ${data.name}: ${data.weather[0].main}


With ${data.weather[0].description}, the temperature is ${Math.round(data.main.temp)}F and the wind is blowing at ${Math.round(data.wind.speed)}mph.

`; console.log(summary); const node = document.getElementById("summary"); node.innerHTML = summary; } function initialize() { socket.onmessage = function(message) { console.log(message.data); const event = new CloudEvent(JSON.parse(message.data)); if (event.type === "weather.error") { console.error(`Error: ${event.data}`); alert(`Error: ${event.data}`); } else { print(event.data); } } const input = document.getElementById("zip"); input.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); const ce = new CloudEvent({ type: "weather.query", source: "/weather.client", data: { zip: input.value } }); console.log(ce); socket.send(JSON.stringify(ce)); } }); } ``` -------------------------------- ### Publish to npm Source: https://github.com/cloudevents/sdk-javascript/blob/main/RELEASING.md Run this command to publish the new version to npm after it has been created. Ensure you have the necessary permissions. ```bash npm publish ``` -------------------------------- ### Example Fix Commit Message Source: https://github.com/cloudevents/sdk-javascript/blob/main/pr_guidelines.md An example of a 'fix' type commit message. This type is used for bug fixes and will appear in the 'Bug Fixes' section of the changelog. ```log fix: removed a bug that was causing the rotation of the earth to change ``` -------------------------------- ### Get Emitter Singleton Instance Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/05-emitter.md Retrieves the singleton instance of the internal EventEmitter. Creates it if it does not exist. ```typescript import { Emitter } from "cloudevents"; const emitter = Emitter.getInstance(); console.log(emitter instanceof require("events").EventEmitter); // true ``` -------------------------------- ### Configuration Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Details on SDK configuration, including constants, environment variables, and BigInt support. ```APIDOC ## Configuration ### Description Information on how to configure the CloudEvents JavaScript SDK. ### Constants - **CONSTANTS**: Access to over 40 predefined constants used within the SDK. ### Environment Variables - **CE_USE_BIG_INT**: Configuration option to enable BigInt support for event IDs and timestamps. ### BigInt Support Provides a full explanation of how to use and manage BigInt values for event identifiers and timestamps. ``` -------------------------------- ### Implement Deserializer for JSON Message Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/06-types-and-interfaces.md Example implementation of the Deserializer interface to parse a JSON Message into a CloudEvent. ```typescript const deserializer: Deserializer = (message) => { const data = JSON.parse(message.body as string); return new CloudEvent(data); }; ``` -------------------------------- ### Handling Binary and Structured Data with MQTT Binding Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/04-mqtt-binding.md Demonstrates how to create CloudEvents with binary data and convert them into both binary and structured MQTT messages. ```typescript import { CloudEvent, MQTT } from "cloudevents"; const binaryData = Buffer.from([0x01, 0x02, 0x03]); const event = new CloudEvent({ source: "/app", type: "binary.data", data: binaryData }); // Binary mode: data is passed as-is or base64-encoded const binaryMessage = MQTT.binary(event); // Structured mode: data_base64 field contains base64-encoded data const structuredMessage = MQTT.structured(event); ``` -------------------------------- ### Implement Serializer for JSON Message Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/06-types-and-interfaces.md Example implementation of the Serializer interface to convert a CloudEvent into a JSON Message. ```typescript const serializer: Serializer = (event) => { return { headers: { "content-type": "application/json" }, body: JSON.stringify(event) }; }; ``` -------------------------------- ### Create Basic CloudEvents Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/10-usage-examples.md Demonstrates how to create minimal CloudEvents and events with data using the CloudEvent constructor. Auto-generated fields like ID and timestamp are included. ```typescript import { CloudEvent } from "cloudevents"; // Minimal event const event = new CloudEvent({ source: "/myapp", type: "user.created" }); console.log(event.id); // auto-generated UUID console.log(event.time); // current timestamp console.log(event.specversion); // "1.0" // Event with data const eventWithData = new CloudEvent({ source: "/users", type: "user.registered", subject: "user/123", data: { userId: 123, email: "user@example.com", registeredAt: "2023-01-15T12:30:00Z" } }); ``` -------------------------------- ### Factory Function: emitterFor() Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Factory function for creating an event emitter, detailing its parameters, options, and usage examples. ```APIDOC ## Function: emitterFor() ### Description Factory function to create and configure an event emitter instance. ### Parameters - `options` (Options): Configuration options for the emitter. ### Options - `transport` (TransportFunction): The transport function to use for emitting events. - `mode` (Mode): The protocol binding mode (e.g., 'binary', 'structured'). ### Examples Refer to the 'Usage Examples' section for detailed examples of using `emitterFor()`. ``` -------------------------------- ### Using the Emitter Singleton with emitterFor Source: https://github.com/cloudevents/sdk-javascript/blob/main/API_TRANSITION_GUIDE.md Demonstrates how to set up the Emitter singleton to automatically emit CloudEvents using a pre-configured sending function. This allows emitting events from anywhere in the code. ```javascript const axios = require("axios").default; const { emitterFor, Mode, CloudEvent, Emitter } = require("cloudevents"); function sendWithAxios(message) { // Do what you need with the message headers // and body in this function, then send the // event axios({ method: "post", url: "...", data: message.body, headers: message.headers, }); } const emit = emitterFor(sendWithAxios, { mode: Mode.BINARY }); // Set the emit Emitter.on("cloudevent", emit); ... // In any part of the code will send the event new CloudEvent({ type, source, data }).emit(); // You can also have several listener to send the event to several endpoint ``` -------------------------------- ### MQTT Protocol Binding Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Documentation for the MQTT protocol binding, supporting binary and structured modes with a factory function. ```APIDOC ## MQTT Protocol Binding ### Description Handles CloudEvents over MQTT, supporting binary and structured modes. ### Modes - **Binary Mode**: Event data and attributes are sent as MQTT message properties and payload. - **Structured Mode**: Event data and attributes are combined into a single JSON payload as the MQTT message payload. ### Functions - **MQTT.binary(event)**: Serializes a CloudEvent into the MQTT binary format. - **MQTT.structured(event)**: Serializes a CloudEvent into the MQTT structured format. - **MQTT.toEvent(message)**: Deserializes an MQTT message into a CloudEvent object. - **MQTT.isEvent(message)**: Detects if an MQTT message represents a CloudEvent. ### Helper Function - **MQTTMessageFactory()**: A helper function for creating MQTT messages. ``` -------------------------------- ### Subscribe to MQTT and Convert to CloudEvent Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/10-usage-examples.md This snippet shows how to connect to an MQTT broker, subscribe to a topic, and convert incoming JSON messages into CloudEvents. ```typescript import { CloudEvent, MQTT } from "cloudevents"; import mqtt from "mqtt"; const client = mqtt.connect("mqtt://broker.example.com"); client.on("connect", () => { client.subscribe("events/temperature", (err) => { if (err) console.error("Subscribe failed:", err); }); }); client.on("message", (topic, payload) => { try { // Parse incoming MQTT message const data = JSON.parse(payload.toString()); // Convert to CloudEvent const event = MQTT.toEvent({ headers: data, body: data, PUBLISH: { "Content Type": "application/cloudevents+json" } }); console.log(`Received event: ${event.type}`); console.log("Data:", event.data); } catch (err) { console.error("Failed to process message:", err); } }); ``` -------------------------------- ### Send CloudEvent with HTTP Transport Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/05-emitter.md Example of creating an emitter using httpTransport and sending a CloudEvent. Demonstrates sending with and without additional options. ```typescript import { CloudEvent, emitterFor, httpTransport } from "cloudevents"; const emit = emitterFor(httpTransport("https://receiver.example.com")); const event = new CloudEvent({ source: "/myapp", type: "event.occurred", data: { message: "hello" } }); // Send the event const response = await emit(event); // Send with additional options const response2 = await emit(event, { headers: { "Authorization": "Bearer token123" } }); ``` -------------------------------- ### Enable BigInt Support Programmatically Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Illustrates how to enable BigInt support by setting the environment variable before importing the SDK. This ensures large integers are preserved with full precision. ```typescript process.env.CE_USE_BIG_INT = "true"; import { CloudEvent, HTTP } from "cloudevents"; // Now large integers are preserved with full precision const event = new CloudEvent({ source: "/api", type: "event", data: { tweetId: 1234567890123456789n } }); ``` -------------------------------- ### Consume CloudEvents from Kafka Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/10-usage-examples.md This snippet shows how to consume Kafka messages and convert them into CloudEvents using the Kafka integration. Ensure you have Kafka and kafkajs installed. ```typescript import { CloudEvent, Kafka } from "cloudevents"; import { Kafka as KafkaClient } from "kafkajs"; const kafka = new KafkaClient({ brokers: ["localhost:9092"] }); const consumer = kafka.consumer({ groupId: "my-group" }); async function receiveKafkaEvent() { await consumer.connect(); await consumer.subscribe({ topic: "billing-events" }); await consumer.run({ eachMessage: async ({ topic, partition, message }) => { try { // Convert Kafka message to CloudEvent const event = Kafka.toEvent({ headers: message.headers, key: message.key, value: message.value }); console.log(`Received event: ${event.type}`); console.log(`Data:`, event.data); console.log(`Partition key:`, event.partitionkey); } catch (err) { console.error("Failed to process Kafka message:", err); } } }); } receiveKafkaEvent().catch(console.error); ``` -------------------------------- ### Setting HTTP Headers with Constants Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Shows how to construct HTTP headers using SDK constants, particularly for setting the Content-Type for CloudEvents. This ensures correct formatting and adherence to standards. ```typescript import { CONSTANTS } from "cloudevents"; const headers = { [CONSTANTS.HEADER_CONTENT_TYPE]: CONSTANTS.DEFAULT_CE_CONTENT_TYPE }; // { "content-type": "application/cloudevents+json; charset=utf-8" } ``` -------------------------------- ### Protocol Bindings (HTTP, Kafka, MQTT) Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/README.md The SDK provides protocol bindings for common messaging systems like HTTP, Kafka, and MQTT, enabling CloudEvents to be sent and received over these protocols. ```APIDOC ## Protocol Bindings ### Description Support for sending and receiving CloudEvents over various protocols. ### Bindings - `HTTP`: HTTP protocol binding. - `Kafka`: Kafka protocol binding. - `MQTT`: MQTT protocol binding. ``` -------------------------------- ### Using emitterFor with a Custom Sender Function Source: https://github.com/cloudevents/sdk-javascript/blob/main/API_TRANSITION_GUIDE.md The emitterFor function provides a convenient way to create an emitter with a custom sending function. This example uses Axios. ```javascript const axios = require('axios').default; const { emitterFor, Mode } = require("cloudevents"); function sendWithAxios(message) { // Do what you need with the message headers // and body in this function, then send the // event axios({ method: 'post', url: '...', data: message.body, headers: message.headers, }); } const emit = emitterFor(sendWithAxios, { mode: Mode.BINARY }); emit(new CloudEvent({ type, source, data })); ``` -------------------------------- ### Send Binary CloudEvent with Extension (v1.0) Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/express-ex/README.md Send a binary CloudEvent including a custom extension. The extension is provided as an additional 'ce-' prefixed header. ```bash curl -X POST \ -d'@../payload/data-0.json' \ -H'Content-Type:application/json' \ -H'ce-specversion:1.0' \ -H'ce-type:com.github.pull.create' \ -H'ce-source:https://github.com/cloudevents/spec/pull/123' \ -H'ce-id:45c83279-c8a1-4db6-a703-b3768db93887' \ -H'ce-time:2019-11-06T11:17:00Z' \ -H'ce-myextension:extension value' \ http://localhost:3000/ ``` -------------------------------- ### Creating a CloudEvent with Extension Attributes Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/01-cloudevent-class.md Demonstrates how to instantiate a CloudEvent object and include custom extension attributes like 'myextension' and 'trackingid'. ```typescript const event = new CloudEvent({ source: "/app", type: "event", myextension: "value", trackingid: "123" }); ``` -------------------------------- ### Parse JSON Event Data Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/09-parsers-and-formats.md Demonstrates parsing JSON event data using the HTTP.toEvent method. This example shows how the SDK automatically handles JSON strings. ```typescript import { CloudEvent, HTTP } from "cloudevents"; // Parse JSON event data const message = { headers: { "content-type": "application/json" }, body: '{"orderId": 123, "amount": 99.99}' }; const event = HTTP.toEvent(message); console.log(event.data); // { orderId: 123, amount: 99.99 } // Automatically handles JSON strings const message2 = { headers: { "content-type": "application/json" }, body: '"simple string"' // JSON-encoded string }; const event2 = HTTP.toEvent(message2); console.log(event2.data); // "simple string" ``` -------------------------------- ### Using MIME Type Constants Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Demonstrates how to access and use predefined MIME type constants from the SDK. These are useful for setting the Content-Type header for event data. ```typescript import { CONSTANTS } from "cloudevents"; const contentType = CONSTANTS.MIME_CE_JSON; // "application/cloudevents+json" const isJsonEvent = contentType.startsWith(CONSTANTS.MIME_CE); // true ``` -------------------------------- ### Handle Binary Data with HTTP Binding Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/02-http-binding.md Demonstrates how to create a CloudEvent with binary data and send it using the HTTP binding in binary mode. The SDK handles base64 encoding and content-type headers automatically. ```typescript const binaryData = Buffer.from([0x01, 0x02, 0x03]); const event = new CloudEvent({ source: "/app", type: "binary.data", data: binaryData }); const message = HTTP.binary(event); // Binary data is properly handled in both modes ``` -------------------------------- ### Send Binary CloudEvent (v0.3) Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/express-ex/README.md Send a binary CloudEvent for spec v0.3. Metadata is sent as 'ce-' prefixed headers. ```bash curl -X POST \ -d'@../payload/data-0.json' \ -H'Content-Type:application/json' \ -H'ce-specversion:0.3' \ -H'ce-type:com.github.pull.create' \ -H'ce-source:https://github.com/cloudevents/spec/pull/123' \ -H'ce-id:45c83279-c8a1-4db6-a703-b3768db93887' \ -H'ce-time:2019-06-21T17:31:00Z' \ http://localhost:3000/ ``` -------------------------------- ### Create CloudEvent in TypeScript Source: https://github.com/cloudevents/sdk-javascript/blob/main/README.md Demonstrates creating CloudEvent objects in TypeScript, showing initialization with different attribute sets. ```typescript import { CloudEvent, CloudEventV1, CloudEventV1Attributes } from "cloudevents"; const ce: CloudEventV1 = { specversion: "1.0", source: "/some/source", type: "example", id: "1234" }; const event = new CloudEvent(ce); const ce2: CloudEventV1Attributes = { specversion: "1.0", source: "/some/source", type: "example", }; const event2 = new CloudEvent(ce2); const event3 = new CloudEvent({ source: "/some/source", type: "example", }); ``` -------------------------------- ### Send Structured CloudEvent with Extension (v0.3) Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/express-ex/README.md Send a structured CloudEvent for spec v0.3 with an added extension. The extension is passed as a header. ```bash curl -X POST \ -d'@../payload/v03/structured-event-1.json' \ -H'Content-Type:application/cloudevents+json' \ http://localhost:3000/ ``` -------------------------------- ### Constructing Binary CloudEvent HTTP Headers Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Illustrates how to create HTTP headers for binary CloudEvents using the `CE_HEADERS` constant object. This is essential for sending CloudEvents in a binary format over HTTP. ```typescript import { CONSTANTS } from "cloudevents"; const binaryHeaders = { [CONSTANTS.CE_HEADERS.TYPE]: "com.example.event", [CONSTANTS.CE_HEADERS.ID]: "123", [CONSTANTS.CE_HEADERS.SOURCE]: "/myapp", [CONSTANTS.CE_HEADERS.SPEC_VERSION]: "1.0" }; ``` -------------------------------- ### Kafka Protocol Binding Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Documentation for the Kafka protocol binding, supporting binary, structured, and batch modes with partition key mapping. ```APIDOC ## Kafka Protocol Binding ### Description Handles CloudEvents over Kafka, supporting different encoding modes and partition key mapping. ### Modes - **Binary Mode**: Event data and attributes are sent as Kafka message headers and value. - **Structured Mode**: Event data and attributes are combined into a single JSON payload as the Kafka message value. - **Batch Mode**: Multiple events are sent in a single Kafka message, typically as a JSON array. ### Functions - **Kafka.binary(event)**: Serializes a CloudEvent into the Kafka binary format. - **Kafka.structured(event)**: Serializes a CloudEvent into the Kafka structured format. - **Kafka.toEvent(message)**: Deserializes a Kafka message into a CloudEvent object. - **Kafka.isEvent(message)**: Detects if a Kafka message represents a CloudEvent. ### Partition Key Mapping Allows specifying a partition key for routing Kafka messages. ``` -------------------------------- ### Send Binary CloudEvent with Extension (v0.3) Source: https://github.com/cloudevents/sdk-javascript/blob/main/examples/express-ex/README.md Send a binary CloudEvent for spec v0.3 with a custom extension. The extension is added as a 'ce-' prefixed header. ```bash curl -X POST \ -d'@../payload/data-0.json' \ -H'Content-Type:application/json' \ -H'ce-specversion:0.3' \ -H'ce-type:com.github.pull.create' \ -H'ce-source:https://github.com/cloudevents/spec/pull/123' \ -H'ce-id:45c83279-c8a1-4db6-a703-b3768db93887' \ -H'ce-time:2019-06-21T17:31:00Z' \ -H'ce-myextension:extension value' \ http://localhost:3000/ ``` -------------------------------- ### Accessing and Verifying Frozen Constants Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/08-constants-and-configuration.md Demonstrates how to access predefined constants like MIME types from the SDK's CONSTANTS object. It also shows that attempts to modify these constants or add new ones will fail, as the object is frozen. ```typescript import { CONSTANTS } from "cloudevents"; // This works const contentType = CONSTANTS.MIME_JSON; // This fails silently (strict mode throws error) CONSTANTS.MIME_JSON = "text/plain"; // No effect // This also fails CONSTANTS.NEW_CONSTANT = "value"; // No effect // CONSTANTS remains unchanged console.log(CONSTANTS.MIME_JSON); // "application/json" ``` -------------------------------- ### Emit CloudEvents using Emitter Singleton and Event Listener Source: https://github.com/cloudevents/sdk-javascript/blob/main/README.md Utilize the `Emitter` singleton to send CloudEvents. Register an `emit` function as a listener for 'cloudevent' events, allowing any `CloudEvent` instance to trigger sending. ```javascript const { emitterFor, httpTransport, Mode, CloudEvent, Emitter } = require("cloudevents"); // Create a CloudEvent emitter function to send events to our receiver const emit = emitterFor(httpTransport("https://example.com/receiver")); // Use the emit() function to send a CloudEvent to its endpoint when a "cloudevent" event is emitted // (see: https://nodejs.org/api/events.html#class-eventemitter) Emitter.on("cloudevent", emit); ... // In any part of the code, calling `emit()` on a `CloudEvent` instance will send the event new CloudEvent({ type, source, data }).emit(); // You can also have several listeners to send the event to several endpoints ``` -------------------------------- ### Map CloudEvent Partition Key to Kafka Message Key Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/03-kafka-binding.md Demonstrates how the CloudEvent 'partitionkey' attribute is automatically mapped to the Kafka message 'key' when sending, and vice-versa when receiving. This ensures proper Kafka partitioning based on CloudEvent semantics. ```typescript import { CloudEvent, Kafka } from "cloudevents"; // Create event with partition key const event = new CloudEvent({ source: "/inventory", type: "stock.updated", partitionkey: "product-789", // Controls Kafka partitioning data: { productId: 789, quantity: 50 } }); const kafkaMessage = Kafka.binary(event); console.log(kafkaMessage.key); // "product-789" // On deserialization const receivedEvent = Kafka.toEvent(kafkaMessage); console.log(receivedEvent.partitionkey); // "product-789" ``` -------------------------------- ### CloudEvent Class Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Documentation for the CloudEvent class, including its constructor, properties, and all methods for creating and manipulating CloudEvents. ```APIDOC ## Class: CloudEvent ### Description Represents a CloudEvent object. Provides methods for creating, accessing, and manipulating CloudEvent data. ### Constructor `new CloudEvent(attributes, data)` - `attributes` (CloudEventV1Attributes | CloudEventV1OptionalAttributes): The attributes of the CloudEvent. - `data` (any): The data payload of the CloudEvent. ### Properties - `id` (string): The unique identifier for the event. - `source` (string): Identifies the event producer. - `type` (string): The event type. - `specversion` (string): The CloudEvents specification version. - `time` (string): Timestamp of when the event was generated. - `datacontenttype` (string): The MIME type of the `data` attribute. - `dataschema` (string): Identifies the schema used for `data`. - `subject` (string): Describes the subject of the event in the context of the event producer. - `data` (any): The event payload. ### Methods - `clone()`: Creates a deep copy of the CloudEvent. - `toString()`: Returns a string representation of the CloudEvent. ``` -------------------------------- ### User Properties and Aliases Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/04-mqtt-binding.md Demonstrates how MQTT messages support dual property access patterns for headers and body, allowing access via direct property names or MQTT-specific conventions like 'User Properties' and 'payload'. ```APIDOC ## User Properties and Aliases ### Description MQTT messages support dual property access patterns for headers and body, allowing access via direct property names or MQTT-specific conventions like 'User Properties' and 'payload'. ### Example ```typescript import { MQTT } from "cloudevents"; const mqttMessage = MQTT.binary(event); // Access headers directly console.log(mqttMessage.headers); // OR use MQTT convention - "User Properties" console.log(mqttMessage["User Properties"]); // Same object // Access body directly console.log(mqttMessage.body); // OR use MQTT convention - "payload" console.log(mqttMessage.payload); // Same value ``` ``` -------------------------------- ### Emitter Class Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/MANIFEST.md Singleton class with all static methods for emitting CloudEvents. ```APIDOC ## Class: Emitter ### Description Provides static methods for emitting CloudEvents. This is a singleton class. ### Methods - `emit(event)`: Emits a CloudEvent. - `on(event, listener)`: Registers a listener for a specific event. - `off(event, listener)`: Removes a listener for a specific event. ``` -------------------------------- ### Complete CloudEvents Workflow with Emitters Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/05-emitter.md This snippet demonstrates sending events to an external HTTP endpoint and handling events internally. It shows how to create an HTTP emitter, send structured events, register internal listeners, and combine internal handling with external forwarding. ```typescript import { CloudEvent, emitterFor, httpTransport, Emitter, Mode } from "cloudevents"; // ===== External Emitter (HTTP) ===== // Create an emitter to send events to external endpoint const httpEmit = emitterFor( httpTransport("https://events.example.com/api"), { mode: Mode.STRUCTURED } ); // Send event externally const event1 = new CloudEvent({ source: "/myapp", type: "order.created", data: { orderId: 123 } }); await httpEmit(event1); // ===== Internal Emitter ===== // Register internal listener Emitter.on("cloudevent", (event: CloudEvent) => { console.log("Internal listener received:", event.type); }); // Create and emit event internally const event2 = new CloudEvent({ source: "/myapp", type: "order.shipped", data: { orderId: 123 } }); await event2.emit(); // ===== Combined Pattern ===== // Create internal handler that forwards to external endpoint Emitter.on("cloudevent", async (event: CloudEvent) => { try { await httpEmit(event); console.log("Event forwarded externally"); } catch (err) { console.error("Failed to forward event:", err); } }); // Now events can be emitted internally and forwarded automatically const event3 = new CloudEvent({ source: "/myapp", type: "notification.sent" }); await event3.emit(); ``` -------------------------------- ### Create and Send a CloudEvent via HTTP Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/README.md Demonstrates how to create a CloudEvent object and send it to a specified HTTP endpoint using the SDK's emitter functionality. Ensure the receiver endpoint is correctly configured. ```typescript import { CloudEvent, emitterFor, httpTransport } from "cloudevents"; // Create emitter const emit = emitterFor(httpTransport("https://receiver.example.com")); // Create event const event = new CloudEvent({ source: "/myapp", type: "com.example.event", data: { message: "hello" } }); // Send event await emit(event); ``` -------------------------------- ### Create CloudEvent with All Optional Attributes Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/01-cloudevent-class.md Demonstrates the creation of a CloudEvent including all standard optional attributes such as 'subject', 'datacontenttype', 'dataschema', and 'time'. ```typescript import { CloudEvent } from "cloudevents"; // Event with all optional attributes const event3 = new CloudEvent({ source: "/orders", type: "order.placed", subject: "order/12345", datacontenttype: "application/json", dataschema: "https://schema.example.com/order.json", time: "2023-01-15T12:30:00Z", data: { orderId: 12345, total: 99.99 } }); ``` -------------------------------- ### Partition Key Mapping Source: https://github.com/cloudevents/sdk-javascript/blob/main/_autodocs/03-kafka-binding.md Explains how the CloudEvent's `partitionkey` attribute maps to the Kafka message `key` for both sending and receiving, ensuring proper Kafka partitioning. ```APIDOC ## Partition Key Mapping ### Description The Kafka binding includes special handling for the `partitionkey` attribute. When sending, the CloudEvent's `partitionkey` attribute maps to the Kafka message `key`. When receiving, the Kafka message `key` maps back to the CloudEvent's `partitionkey` attribute. This ensures events are correctly partitioned in Kafka based on CloudEvent semantics. ### Example ```typescript import { CloudEvent, Kafka } from "cloudevents"; // Create event with partition key const event = new CloudEvent({ source: "/inventory", type: "stock.updated", partitionkey: "product-789", // Controls Kafka partitioning data: { productId: 789, quantity: 50 } }); const kafkaMessage = Kafka.binary(event); console.log(kafkaMessage.key); // "product-789" // On deserialization const receivedEvent = Kafka.toEvent(kafkaMessage); console.log(receivedEvent.partitionkey); // "product-789" ``` ```