### Install Datastar SDK Source: https://context7.com/starfederation/datastar-typescript/llms.txt Install the Datastar SDK using npm for Node.js or bun add for Bun. ```bash # Node.js npm install @starfederation/datastar-sdk # Bun bun add @starfederation/datastar-sdk ``` -------------------------------- ### Install Datastar SDK for Bun Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Use bun add to install the Datastar SDK for Bun environments. ```bash bun add @starfederation/datastar-sdk ``` -------------------------------- ### Install Datastar SDK for Node.js Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Use npm to install the Datastar SDK for Node.js environments. ```bash npm install @starfederation/datastar-sdk ``` -------------------------------- ### Basic Datastar SDK Usage in Node.js Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Example demonstrating how to read client signals and send back element patches using the Node.js runtime. Ensure the ServerSentEventGenerator is imported for Node.js. ```javascript import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/node"; // Read signals from the client request const reader = await ServerSentEventGenerator.readSignals(req); if (!reader.success) { console.error('Error reading signals:', reader.error); return; } // Stream updates back to the client ServerSentEventGenerator.stream(req, res, (stream) => { // Patch signals stream.patchSignals(JSON.stringify({ foo: reader.signals.foo })); // Patch DOM elements stream.patchElements(`
Hello ${reader.signals.foo}
`); }); ``` -------------------------------- ### Run All Tests Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Executes all tests for Node.js, Deno, and Bun, mirroring the CI environment. This script checks for required tools, clones/updates the core datastar repo, builds the SDK, starts test servers, and runs the Go test suite. ```bash bash test/run-all.sh ``` -------------------------------- ### Import ServerSentEventGenerator for Deno Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Import the ServerSentEventGenerator class directly from npm for Deno runtime. No installation is needed. ```typescript // No installation needed, import directly from npm import { ServerSentEventGenerator } from "npm:@starfederation/datastar-sdk/web"; ``` -------------------------------- ### Implement Custom SSE Generator in TypeScript Source: https://context7.com/starfederation/datastar-typescript/llms.txt Extend the abstract ServerSentEventGenerator to create a custom runtime implementation. This example shows how to integrate with a WritableStreamDefaultWriter for sending events. ```typescript import { ServerSentEventGenerator as AbstractSSEGenerator } from "@starfederation/datastar-sdk/abstract"; import type { DatastarEventOptions, EventType, StreamOptions } from "@starfederation/datastar-sdk"; export class MyRuntimeSSEGenerator extends AbstractSSEGenerator { private writer: WritableStreamDefaultWriter; private encoder = new TextEncoder(); protected constructor(writer: WritableStreamDefaultWriter) { super(); this.writer = writer; } protected override send( event: EventType, dataLines: string[], options: DatastarEventOptions, ): string[] { const lines = super.send(event, dataLines, options) as string[]; // Write all lines as a single encoded chunk this.writer.write(this.encoder.encode(lines.join(""))); return lines; } public override close(): void { this.writer.close(); } // Required static factory method static stream( onStart: (stream: MyRuntimeSSEGenerator) => Promise | void, options?: StreamOptions, ): Response { let generatorRef: MyRuntimeSSEGenerator; const {readable, writable} = new TransformStream(); const writer = writable.getWriter(); (async () => { const generator = new MyRuntimeSSEGenerator(writer); try { const result = onStart(generator); if (result instanceof Promise) await result; if (!options?.keepalive) generator.close(); } catch (err) { if (options?.onError) await options.onError(err); generator.close(); } })(); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }, }); } static async readSignals(request: Request) { // Delegate to web implementation or implement custom parsing const { ServerSentEventGenerator: WebSSE } = await import("@starfederation/datastar-sdk/web"); return WebSSE.readSignals(request); } } ``` -------------------------------- ### Bun Full Server with Datastar Source: https://context7.com/starfederation/datastar-typescript/llms.txt Create a Bun server for serving HTML and handling Server-Sent Events. Leverages the '@starfederation/datastar-sdk/web' package. ```typescript import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/web"; Bun.serve({ port: 3000, routes: { "/": () => new Response( `
Hello
`, { headers: { "Content-Type": "text/html" } } ), "/merge": async (req: Request) => { const reader = await ServerSentEventGenerator.readSignals(req); if (!reader.success) { return new Response(`Error: ${reader.error}`, { status: 400 }); } return ServerSentEventGenerator.stream((stream) => { stream.patchElements( `
Hello ${reader.signals.foo}
` ); }); }, }, fetch(req) { return new Response("Not found", { status: 404 }); }, }); ``` -------------------------------- ### Node.js Full Server with Datastar Source: https://context7.com/starfederation/datastar-typescript/llms.txt Set up a Node.js HTTP server to serve an HTML page and handle Server-Sent Events for dynamic updates. Requires the '@starfederation/datastar-sdk/node' package. ```javascript import { createServer } from "node:http"; import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/node"; createServer(async (req, res) => { if (req.url === "/") { res.setHeader("Content-Type", "text/html"); res.end( `
Hello
` ); } else if (req.url?.includes("/merge")) { const reader = await ServerSentEventGenerator.readSignals(req); if (!reader.success) { res.end(`Error: ${reader.error}`); return; } await ServerSentEventGenerator.stream(req, res, (stream) => { stream.patchElements( `
Hello ${reader.signals.foo}
` ); }, { onError: (err) => console.error("SSE error:", err), }); } }).listen(3000, "127.0.0.1", () => console.log("Server running at http://127.0.0.1:3000/") ); ``` -------------------------------- ### Using DataStar SDK with Bun Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Instructions for importing and using the DataStar SDK within a Bun environment. Requires Bun version 1.0 or higher and utilizes Web Standards APIs. ```APIDOC ## Bun Usage ### Import `@starfederation/datastar-sdk/web` ### Requirements - Bun 1.0+ - Uses Web Standards APIs ``` -------------------------------- ### Deno Full Server with Datastar Source: https://context7.com/starfederation/datastar-typescript/llms.txt Implement a Deno server to serve an HTML page and manage Server-Sent Events. Uses the 'npm:@starfederation/datastar-sdk/web' package. ```typescript import { ServerSentEventGenerator } from "npm:@starfederation/datastar-sdk/web"; Deno.serve(async (req: Request) => { const url = new URL(req.url); if (url.pathname === "/") { return new Response( `
Hello
`, { headers: { "Content-Type": "text/html" } } ); } if (url.pathname.includes("/merge")) { const reader = await ServerSentEventGenerator.readSignals(req); if (!reader.success) { return new Response(`Error: ${reader.error}`, { status: 400 }); } return ServerSentEventGenerator.stream((stream) => { stream.patchElements( `
Hello ${reader.signals.foo}
` ); }); } return new Response("Not found", { status: 404 }); }); ``` -------------------------------- ### Import ServerSentEventGenerator for Bun Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Import the ServerSentEventGenerator class for Bun runtime. This is the same import path as for Deno. ```javascript import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/web"; ``` -------------------------------- ### Build NPM Package Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Builds the npm package for the SDK. Specify a version number as an argument to override the version defined in `src/consts.ts`. ```bash deno run -A build.ts ``` ```bash deno run -A build.ts VERSION ``` -------------------------------- ### Import ServerSentEventGenerator Source: https://context7.com/starfederation/datastar-typescript/llms.txt Import the ServerSentEventGenerator class for Node.js, Deno, or Bun environments. ```typescript // Node.js import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/node"; // Deno (no install needed) import { ServerSentEventGenerator } from "npm:@starfederation/datastar-sdk/web"; // Bun import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/web"; ``` -------------------------------- ### ServerSentEventGenerator.stream() Source: https://context7.com/starfederation/datastar-typescript/llms.txt Opens a Server-Sent Events stream and executes the onStart callback with a live ServerSentEventGenerator instance. The stream closes automatically when onStart returns unless keepalive: true is set. ```APIDOC ## `ServerSentEventGenerator.stream(...)` — Open an SSE Stream Opens a Server-Sent Events stream and executes the `onStart` callback with a live `ServerSentEventGenerator` instance. The stream closes automatically when `onStart` returns unless `keepalive: true` is set. The Node.js variant takes `(req, res, onStart, options?)` and writes directly to `ServerResponse`; the Web Standards variant takes `(onStart, options?)` and returns a `Response`. ```typescript // Node.js — basic stream with error handling import { createServer } from "node:http"; import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/node"; createServer(async (req, res) => { await ServerSentEventGenerator.stream(req, res, async (stream) => { stream.patchElements('
Processing…
'); await new Promise((r) => setTimeout(r, 1000)); stream.patchElements('
Done!
'); stream.patchSignals(JSON.stringify({ done: true })); }, { onError: (err) => console.error("Stream error:", err), onAbort: () => console.log("Client disconnected"), }); }).listen(3000); // Web Standards — keepalive stream closed manually import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/web"; async function liveHandler(req: Request): Promise { let streamRef: typeof ServerSentEventGenerator.prototype; return ServerSentEventGenerator.stream((stream) => { // Non-blocking: stream stays open because keepalive: true const interval = setInterval(() => { stream.patchSignals(JSON.stringify({ tick: Date.now() })); }, 500); // Store ref to close later from outside (e.g., on some event) setTimeout(() => { clearInterval(interval); stream.close(); // manually close when keepalive is true }, 5000); }, { keepalive: true, onAbort: (reason) => console.log("Aborted:", reason), responseInit: { headers: { "X-Custom": "header" } }, }); } ``` ``` -------------------------------- ### Extending ServerSentEventGenerator Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Guidance on how to extend the abstract `ServerSentEventGenerator` class to support additional runtimes or frameworks. This involves implementing specific methods to handle runtime-specific logic. ```APIDOC ## Custom Implementations To support additional runtimes or frameworks, extend the abstract `ServerSentEventGenerator` class from `./src/abstractServerSentEventGenerator.ts`. You'll need to implement: - `constructor`: Initialize runtime-specific components - `readSignals`: Parse signals from requests - `stream`: Create SSE streams - `send`: Send data to clients The abstract class provides these public methods: - `patchElements(elements, options?)`: Patch HTML elements - `patchSignals(signals, options?)`: Patch signal data - `removeElements(selector?, elements?, options?)`: Remove elements by selector or HTML string - `removeSignals(signalKeys, options?)`: Remove one or more signals - `executeScript(script, options?)`: Execute a script on the client ``` -------------------------------- ### Import ServerSentEventGenerator for Node.js Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Import the ServerSentEventGenerator class specifically for Node.js runtime. ```javascript import { ServerSentEventGenerator } from "@starfederation/datastar-sdk/node"; ``` -------------------------------- ### executeScript Source: https://github.com/starfederation/datastar-typescript/blob/main/README.md Executes a script on the client by sending a