### Run Examples with S2 SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Executes example TypeScript files using tsx. Requires S2_ACCESS_TOKEN, S2_BASIN, and optionally S2_STREAM environment variables to be set. ```bash export S2_ACCESS_TOKEN="" export S2_BASIN="" export S2_STREAM="" # optional per example npx tsx examples/.ts ``` -------------------------------- ### Run read-write example Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/media/README.md Executes a TypeScript example that synchronously writes a message to an S2 stream and reads it back. Requires setting DEBUG, S2_ACCESS_TOKEN, S2_BASIN, and S2_STREAM environment variables. ```bash export DEBUG="patterns:*" export S2_ACCESS_TOKEN="token" export S2_BASIN="your-basin" S2_STREAM="test/read-write/0001" npx tsx packages/patterns/examples/read-write.ts ``` -------------------------------- ### Run Browser Example for S2 SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Builds and runs a basic browser example for the S2 SDK from the packages/streamstore directory. This allows testing SDK functionality directly in a web environment. ```bash bun run --cwd packages/streamstore example:browser ``` -------------------------------- ### Run AI SDK example Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/media/README.md Executes a TypeScript example that uses the AI SDK to generate a response, tees the text stream to the console and an S2 stream, and then replays the S2 stream. Requires setting DEBUG, S2_ACCESS_TOKEN, and S2_BASIN environment variables. ```bash export DEBUG="patterns:*" export S2_ACCESS_TOKEN="token" export S2_BASIN="your-basin" S2_STREAM="agent/session/0001" npx tsx packages/patterns/examples/ai-sdk.ts ``` -------------------------------- ### Run Examples and Tests for S2 TypeScript SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/index.html Commands to run TypeScript examples using tsx and to execute tests for the SDK. Requires environment variables for access token and basin. ```bash export S2_ACCESS_TOKEN="" export S2_BASIN="" export S2_STREAM="" # optional per example npx tsx examples/.ts ``` ```bash bun run test ``` ```bash bun run --cwd packages/streamstore example:browser ``` -------------------------------- ### Install @s2-dev/streamstore-patterns Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/media/README.md Installs the s2-dev/streamstore-patterns package and its peer dependency @s2-dev/streamstore using npm, pnpm, or yarn. ```bash npm install @s2-dev/streamstore-patterns @s2-dev/streamstore # or: pnpm add @s2-dev/streamstore-patterns @s2-dev/streamstore # or: yarn add @s2-dev/streamstore-patterns @s2-dev/streamstore ``` -------------------------------- ### Example: List All Streams with Prefix (TypeScript) Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Streams.html Demonstrates how to use the listAll method to iterate through streams that match a specific prefix, logging each stream's name. ```typescript for await (const stream of basin.streams.listAll({ prefix: "events-" })) { console.log(stream.name); } ``` -------------------------------- ### Install S2 Streamstore SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Installs the S2 Streamstore SDK using npm, yarn, or bun package managers. This is the first step to integrating S2 into your TypeScript project. ```bash npm add @s2-dev/streamstore # or yarn add @s2-dev/streamstore # or bun add @s2-dev/streamstore ``` -------------------------------- ### GET /basins/:basin/config (Get Basin Config) Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Basins.html Retrieves the configuration for a specific basin. ```APIDOC ## GET /basins/:basin/config ### Description Get basin configuration. ### Method GET ### Endpoint /basins/:basin/config ### Parameters #### Path Parameters * **basin** (string) - Required - The name of the basin whose configuration to retrieve. #### Request Body * **options** ([S2RequestOptions](../types/S2RequestOptions.html)) - Optional - Request options. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) * **BasinConfig** (object) - The configuration of the basin. * *(See [BasinConfig](../interfaces/BasinConfig.html) for details)* #### Response Example ```json { "retention": "7d" } ``` ``` -------------------------------- ### ReadStart Interface Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/interfaces/ReadStart.html Defines the starting point for reading data from the streamstore. It includes optional properties to control the reading behavior. ```APIDOC ## Interface: ReadStart ### Description Where to start reading. This interface defines the parameters for initiating a read operation from the streamstore. ### Properties #### `clamp` (boolean) - Optional If true, the read operation will start from the tail of the stream if the requested position is beyond it. * Defined in `packages/streamstore/src/types.ts:255` #### `from` (ReadFrom) - Optional Specifies the starting point for the read operation using the `ReadFrom` type. * Defined in `packages/streamstore/src/types.ts:253` ``` -------------------------------- ### BatchTransform Usage Example - TypeScript Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/BatchTransform.html Demonstrates how to instantiate and use the BatchTransform class. It shows piping the batcher through a session and writable stream, as well as manual writing and reading of batches. This example requires the AppendRecord type and a session object. ```typescript const batcher = new BatchTransform<"string">({ lingerDurationMillis: 20, maxBatchRecords: 100, maxBatchBytes: 256 * 1024, matchSeqNum: 0 // Optional: auto-increments per batch }); // Pipe through the batcher and session to get acks readable.pipeThrough(batcher).pipeThrough(session).pipeTo(writable); // Or use manually const writer = batcher.writable.getWriter(); writer.write(AppendRecord.string({ body: "foo" })); await writer.close(); for await (const batch of batcher.readable) { console.log(`Got batch of ${batch.records.length} records`); } ``` -------------------------------- ### Run Tests for S2 SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Executes the test suite for the S2 SDK using the bun runtime. Ensure you have bun installed to run this command. ```bash bun run test ``` -------------------------------- ### Initialize S2 Client and Get Stream Access (TypeScript) Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Demonstrates how to initialize the S2 client using environment variables or a direct access token. It shows how to create basin-scoped and stream-scoped clients for subsequent data operations. Includes configuration for retry policies and timeouts. ```typescript import { S2, S2Environment, S2Error } from "@s2-dev/streamstore"; // Initialize the S2 client with environment variables and configuration const s2 = new S2({ ...S2Environment.parse(), // Parses S2_ENDPOINT_ACCOUNT and S2_ENDPOINT_BASIN from env accessToken: process.env.S2_ACCESS_TOKEN ?? "your-access-token", retry: { maxAttempts: 3, minBaseDelayMillis: 100, maxBaseDelayMillis: 500, appendRetryPolicy: "all", // or "noSideEffects" for idempotent-only retries requestTimeoutMillis: 5_000, }, }); // Create a basin-scoped client (basins are namespaces for streams) const basin = s2.basin("my-basin-name"); // Create a stream-scoped client for data operations const stream = basin.stream("my-stream-name"); // Output: S2 client ready with basin and stream clients ``` -------------------------------- ### AppendSession Example Usage Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/interfaces/AppendSession.html This example demonstrates the typical lifecycle of an AppendSession. It shows how to create a session, submit data using AppendInput, acknowledge the submission, and finally close the session. This pattern is crucial for reliable data appending to streams. ```typescript const session = await stream.appendSession(); const ackTicket = await session.submit( AppendInput.create([AppendRecord.string({ body: "event" })]), ); await ackTicket.ack(); await session.close(); ``` -------------------------------- ### Quick Start: S2 Streamstore TypeScript SDK Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Demonstrates a basic workflow using the S2 TypeScript SDK. It covers setting up the S2 client, creating a basin and stream, appending records (string and bytes), and reading them back. Requires S2_ACCESS_TOKEN and S2_BASIN environment variables. ```typescript import { AppendAck, AppendInput, AppendRecord, S2, S2Environment, } from "@s2-dev/streamstore"; const basinName = process.env.S2_BASIN ?? "my-existing-basin"; const streamName = process.env.S2_STREAM ?? "my-new-stream"; const s2 = new S2({ ...S2Environment.parse(), accessToken: process.env.S2_ACCESS_TOKEN ?? "my-access-token", }); // Create a basin (namespace) client for basin-level operations. const basin = s2.basin(basinName); // Make a new stream within the basin, using the default configuration. const streamResponse = await basin.streams.create({ stream: streamName }); console.dir(streamResponse, { depth: null }); // Create a stream client on our new stream. const stream = basin.stream(streamName); // Make a single append call. const append: Promise = stream.append( // `append` expects an input batch of one or many records. AppendInput.create([ // Records can use a string encoding... AppendRecord.string({ body: "Hello from the docs snippet!", headers: [["content-type", "text/plain"]], }), // ...or contain raw binary data. AppendRecord.bytes({ body: new TextEncoder().encode("Bytes payload"), }), ]), ); // When the promise resolves, the data is fully durable and present on the stream. const ack = await append; console.log( `Appended records ${ack.start.seqNum} through ${ack.end.seqNum} (exclusive).`, ); console.dir(ack, { depth: null }); // Read the two records back as binary. const batch = await stream.read( { start: { from: { seqNum: ack.start.seqNum } }, stop: { limits: { count: 2 } }, }, { as: "bytes" }, ); for (const record of batch.records) { console.dir(record, { depth: null }); console.log("decoded body: %s", new TextDecoder().decode(record.body)); } ``` -------------------------------- ### Export S2 Access Token Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/examples/README.md Sets the S2_ACCESS_TOKEN environment variable. This token is required for authenticating with the S2 API. Ensure you replace 'MY_TOKEN' with your actual API key obtained from s2.dev. ```bash export S2_ACCESS_TOKEN="MY_TOKEN" ``` -------------------------------- ### GET /streams listAll Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Streams.html Lists all streams across all basins accessible by the client. ```APIDOC ## GET /streams listAll ### Description Lists all streams across all basins accessible by the client. ### Method GET ### Endpoint /streams ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage: // streams.listAll() ``` ### Response #### Success Response (200) - **Array** - A list of all stream names across all basins. #### Response Example ```json [ "basin1/stream1", "basin2/stream2" ] ``` ``` -------------------------------- ### ReadStart Interface Definition Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/interfaces/ReadStart.html Defines the ReadStart interface for the streamstore, specifying optional properties for controlling read operations. It includes 'clamp' to start from the tail if the position is beyond it, and 'from' to specify the starting point of the read. ```typescript interface ReadStart { [clamp](#clamp)?: boolean; [from](#from)?: [ReadFrom](../types/ReadFrom.html); } ``` -------------------------------- ### Get Basin Client Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2.html Creates a basin-scoped client bound to a specific basin name. ```APIDOC ## S2.basin(name: string) ### Description Create a basin-scoped client bound to a specific basin name. ### Method GET ### Endpoint `/api/v1/basins/{name}` (Conceptual - actual endpoint depends on SDK implementation) ### Parameters #### Path Parameters - **name** (string) - Required - Basin name (8-48 characters, lowercase alphanumeric and hyphens, no leading/trailing hyphens). ### Request Example ```javascript const s2Client = new S2({ accessToken: 'YOUR_ACCESS_TOKEN' }); const specificBasinClient = s2Client.basin('my-basin-name'); ``` ### Response #### Success Response (200) - **S2Basin** (S2Basin) - A client instance scoped to the specified basin. #### Throws - If the basin name is invalid. ### Response Example ```json { "basinClient": "S2Basin Client Instance" } ``` ``` -------------------------------- ### GET /streams list Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Streams.html Lists all streams within the basin. ```APIDOC ## GET /streams list ### Description Lists all streams within the basin. ### Method GET ### Endpoint /streams ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage: // streams.list() ``` ### Response #### Success Response (200) - **Array** - A list of stream names. #### Response Example ```json [ "stream1", "stream2" ] ``` ``` -------------------------------- ### GET /streams getConfig Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Streams.html Retrieves the configuration for a specific stream. Requires the stream name. ```APIDOC ## GET /streams getConfig ### Description Retrieves the configuration for a specific stream. Requires the stream name. ### Method GET ### Endpoint /streams ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **args** (object) - Required - Input for getting stream configuration. - **stream** (string) - Required - Stream name. - **options** (object) - Optional - Request options. ### Request Example ```json { "args": { "stream": "my-stream" }, "options": {} } ``` ### Response #### Success Response (200) - **StreamConfig** (object) - The configuration of the stream. - **field1** (type) - Description #### Response Example ```json { "field1": "value1" } ``` ``` -------------------------------- ### Manage S2 Basins (TypeScript) Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Provides examples of managing S2 basins using the TypeScript SDK. Covers listing basins with pagination and filtering, creating new basins with default stream configurations, retrieving basin configurations, reconfiguring existing basins, and deleting basins. ```typescript import { S2, S2Environment, S2Error } from "@s2-dev/streamstore"; const s2 = new S2({ ...S2Environment.parse(), accessToken: process.env.S2_ACCESS_TOKEN!, }); // List basins (paginated) const basinList = await s2.basins.list({ limit: 10, prefix: "my-" }); console.log("Basins:", basinList.basins.map((b) => b.name)); // Output: Basins: ['my-basin-01', 'my-basin-02'] // List all basins with automatic pagination for await (const basin of s2.basins.listAll({ prefix: "my-" })) { console.log("Basin:", basin.name, "State:", basin.state); } // Output: Basin: my-basin-01 State: active // Create a new basin with default stream configuration const created = await s2.basins.create({ basin: "my-new-basin", config: { defaultStreamConfig: { retentionPolicy: { ageSecs: 86400 * 7 }, // 7 days retention storageClass: "standard", }, }, }); console.log("Created basin:", created.name, "State:", created.state); // Output: Created basin: my-new-basin State: creating // Get basin configuration const config = await s2.basins.getConfig({ basin: "my-new-basin" }); console.log("Basin config:", config); // Output: Basin config: { defaultStreamConfig: { retentionPolicy: { ageSecs: 604800 }, ... } } // Reconfigure basin const updated = await s2.basins.reconfigure({ basin: "my-new-basin", createStreamOnAppend: true, }); // Delete basin (marks for deletion) await s2.basins.delete({ basin: "my-new-basin" }); ``` -------------------------------- ### Create S2 Basin using S2 CLI Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/examples/README.md Creates a new basin in S2 using the S2 Command Line Interface. The `--create-stream-on-append` flag ensures that a new stream is automatically created when data is appended to the basin. This command utilizes the S2_BASIN environment variable set previously. ```bash s2 create-basin "${S2_BASIN}" --create-stream-on-append ``` -------------------------------- ### Manage S2 Streams with TypeScript SDK Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Demonstrates how to create, list, get configuration, reconfigure, and delete streams within an S2 basin using the TypeScript SDK. It includes error handling for stream creation and pagination for listing streams. ```typescript import { S2, S2Environment, S2Error } from "@s2-dev/streamstore"; const s2 = new S2({ ...S2Environment.parse(), accessToken: process.env.S2_ACCESS_TOKEN!, }); const basin = s2.basin("my-basin"); // Create a stream with configuration const created = await basin.streams.create({ stream: "events/user-actions", config: { retentionPolicy: { ageSecs: 86400 * 30 }, // 30 days storageClass: "standard", timestamping: { mode: "client_prefer" }, deleteOnEmpty: { minAgeSecs: 3600 }, // Auto-delete if empty after 1 hour }, }); console.log("Created stream config:", created.config); // Handle "already exists" gracefully try { await basin.streams.create({ stream: "events/user-actions" }); } catch (error) { if (error instanceof S2Error && error.status === 409) { console.log("Stream already exists"); } else { throw error; } } // List streams with pagination const streams = await basin.streams.list({ prefix: "events/", limit: 100 }); console.log("Streams:", streams.streams.map((s) => s.name)); // Output: Streams: ['events/user-actions', 'events/orders'] // List all streams with automatic pagination for await (const stream of basin.streams.listAll({ prefix: "events/" })) { console.log("Stream:", stream.name, "Created:", stream.createdAt); } // Get stream configuration const config = await basin.streams.getConfig({ stream: "events/user-actions" }); console.log("Retention:", config.retentionPolicy); // Reconfigure stream await basin.streams.reconfigure({ stream: "events/user-actions", retentionPolicy: { ageSecs: 86400 * 60 }, // Extend to 60 days }); // Delete stream await basin.streams.delete({ stream: "events/user-actions" }); ``` -------------------------------- ### Retrieve Metrics with S2 SDK (TypeScript) Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Shows how to fetch account, basin, and stream-level metrics using the S2 SDK. This includes examples for retrieving active basins, storage usage over time, append operations, and stream-specific metrics with different aggregation intervals. ```typescript import { S2, S2Environment } from "@s2-dev/streamstore"; const s2 = new S2({ ...S2Environment.parse(), accessToken: process.env.S2_ACCESS_TOKEN!, }); // Account-level metrics const accountMetrics = await s2.metrics.account({ set: "active-basins", start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30 days ago end: new Date(), }); for (const metric of accountMetrics.values) { if ("scalar" in metric) { console.log(`${metric.scalar.name}: ${metric.scalar.value} ${metric.scalar.unit}`); } } // Output: active_basins: 5 count // Basin-level storage metrics with hourly aggregation const basinStorage = await s2.metrics.basin({ basin: "my-basin", set: "storage", start: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24 hours ago end: new Date(), interval: "hour", }); for (const metric of basinStorage.values) { if ("gauge" in metric) { console.log(`${metric.gauge.name} over time:`); for (const [timestamp, value] of metric.gauge.values) { console.log(` ${timestamp.toISOString()}: ${value}`); } } } // Basin-level append operations const appendOps = await s2.metrics.basin({ basin: "my-basin", set: "append-ops", start: new Date(Date.now() - 6 * 60 * 60 * 1000), // 6 hours end: new Date(), interval: "hour", }); // Stream-level metrics const streamMetrics = await s2.metrics.stream({ basin: "my-basin", stream: "my-stream", set: "storage", start: new Date(Date.now() - 60 * 60 * 1000), // 1 hour end: new Date(), interval: "minute", }); console.log("Stream metrics:", streamMetrics.values.length, "metrics returned"); ``` -------------------------------- ### ReadStart Interface Properties Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/interfaces/ReadStart.html Details the optional properties of the ReadStart interface. 'clamp' is a boolean that, when true, allows reading from the end of the stream if the requested position is out of bounds. 'from' specifies the starting point for reading, referencing the ReadFrom type. ```typescript clamp?: boolean; from?: [ReadFrom](../types/ReadFrom.html); ``` -------------------------------- ### Producer Example - TypeScript Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/Producer.html Demonstrates how to use the Producer class to write records to a stream and process their durability acknowledgments. It involves creating an AppendSession, initializing a Producer with a BatchTransform, writing records, and handling acknowledgments. ```typescript const appendSession = await stream.appendSession(); const producer = new Producer(new BatchTransform(), appendSession); const writer = producer.writable.getWriter(); await writer.write(AppendRecord.string({ body: "hello" })); await writer.close(); for await (const ack of producer.readable) { console.log("record durable at seq", ack.seqNum()); } await producer.close(); ``` -------------------------------- ### GET /metrics Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/API.AccountMetricsData.html Retrieves account metrics data. You can specify a start and end timestamp, an interval for timeseries data, and the metric set you are interested in. ```APIDOC ## GET /metrics ### Description Retrieves account metrics data. You can specify a start and end timestamp, an interval for timeseries data, and the metric set you are interested in. ### Method GET ### Endpoint /metrics ### Parameters #### Query Parameters - **set** (AccountMetricSet) - Required - The metric set to retrieve. - **start** (number) - Optional - The start timestamp as Unix epoch seconds. - **end** (number) - Optional - The end timestamp as Unix epoch seconds. - **interval** (TimeseriesInterval) - Optional - The interval to aggregate over for timeseries metric sets. ### Request Example ```json { "query": { "set": "someMetricSet", "start": 1678886400, "end": 1678972800, "interval": "daily" } } ``` ### Response #### Success Response (200) - **metrics** (object) - An object containing the requested account metrics. #### Response Example ```json { "metrics": { "metric1": 100, "metric2": "someValue" } } ``` ``` -------------------------------- ### Read Data with ReadSession (TypeScript) Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/README.md Demonstrates reading data from an S2 stream using a ReadSession, suitable for reading multiple batches or tailing for new data. This example sets a start offset and a wait time for new data, then iterates through received records, logging their sequence number and body. ```typescript const readSession = await stream.readSession({ start: { from: { tailOffset: 10 }, clamp: true }, stop: { waitSecs: 10 }, }); for await (const record of readSession) { console.log(record.seqNum, record.body); } ``` -------------------------------- ### Explicit Trimming of Stream Records with TypeScript Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Demonstrates how to explicitly remove old records from an S2 stream using trim command records. This example shows appending records and then trimming them up to a specified sequence number, effectively managing storage when automatic retention policies are insufficient. It also verifies that reading after trimming starts from the new beginning. ```typescript import { AppendInput, AppendRecord, S2, S2Environment, } from "@s2-dev/streamstore"; const s2 = new S2({ ...S2Environment.parse(), accessToken: process.env.S2_ACCESS_TOKEN!, }); const stream = s2.basin("my-basin").stream("my-stream"); // Append some records for (let i = 0; i < 100; i++) { await stream.append( AppendInput.create([AppendRecord.string({ body: `Record ${i}` })]) ); } // Trim records up to sequence number 50 (exclusive) // Records 0-49 will be deleted await stream.append( AppendInput.create([AppendRecord.trim(50)]) ); console.log("Trimmed records up to seqNum 50"); // Reading from seqNum 0 now starts at 50 const batch = await stream.read({ start: { from: { seqNum: 0 }, clamp: true }, stop: { limits: { count: 10 } }, }); console.log("First available record:", batch.records[0]?.seqNum); // Output: First available record: 50 await stream.close(); ``` -------------------------------- ### S2 Client Initialization Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2.html Initializes a new S2 client with provided options, including access token configuration. ```APIDOC ## new S2(options: S2ClientOptions) ### Description Create a new S2 client. ### Method Constructor ### Parameters #### Request Body - **options** (S2ClientOptions) - Required - Access token configuration. ### Response #### Success Response (200) - **S2** (S2) - The initialized S2 client instance. ### Request Example ```json { "accessToken": "YOUR_ACCESS_TOKEN" } ``` ### Response Example ```json { "client": "S2 Client Instance" } ``` ``` -------------------------------- ### S2Basin Methods Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Basin.html Methods available on the S2Basin instance. ```APIDOC ## stream(name: string, options?: StreamOptions): S2Stream ### Description Create a stream-scoped helper bound to `this` basin. ### Method GET (or similar, depending on implementation) ### Endpoint (Implicitly related to the basin's base URL) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (string) - Required - Stream name * **options** (StreamOptions) - Optional - Additional options for the stream ### Request Example ```json { "name": "my-stream", "options": { "someOption": "value" } } ``` ### Response #### Success Response (200) * **S2Stream** - An instance of the S2Stream helper for the specified stream. #### Response Example ```json { "streamInstance": "S2Stream" } ``` ``` -------------------------------- ### S2 Client Initialization Source: https://context7.com/s2-streamstore/s2-sdk-typescript/llms.txt Demonstrates how to initialize the S2 client with environment variables and configuration, including retry policies. It also shows how to create basin-scoped and stream-scoped clients. ```APIDOC ## S2 Client Initialization ### Description Initialize the S2 client with environment variables and configuration. This includes setting up retry policies and creating basin and stream clients for data operations. ### Method `new S2(config)` ### Endpoint N/A (Client-side initialization) ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the S2 client. - **accessToken** (string) - Required - The access token for authentication. - **environment** (object) - Optional - S2 environment configuration. If not provided, it attempts to parse from environment variables (`S2_ENDPOINT_ACCOUNT`, `S2_ENDPOINT_BASIN`). - **endpointAccount** (string) - Optional - The account endpoint URL. - **endpointBasin** (string) - Optional - The basin endpoint URL. - **retry** (object) - Optional - Configuration for automatic retries. - **maxAttempts** (number) - Optional - Maximum number of retry attempts. - **minBaseDelayMillis** (number) - Optional - Minimum base delay in milliseconds between retries. - **maxBaseDelayMillis** (number) - Optional - Maximum base delay in milliseconds between retries. - **appendRetryPolicy** (string) - Optional - Policy for retrying append operations ('all' or 'noSideEffects'). - **requestTimeoutMillis** (number) - Optional - Timeout for each request in milliseconds. ### Request Example ```typescript import { S2, S2Environment } from "@s2-dev/streamstore"; const s2 = new S2({ ...S2Environment.parse(), // Parses S2_ENDPOINT_ACCOUNT and S2_ENDPOINT_BASIN from env accessToken: process.env.S2_ACCESS_TOKEN ?? "your-access-token", retry: { maxAttempts: 3, minBaseDelayMillis: 100, maxBaseDelayMillis: 500, appendRetryPolicy: "all", requestTimeoutMillis: 5_000, }, }); const basin = s2.basin("my-basin-name"); const stream = basin.stream("my-stream-name"); ``` ### Response #### Success Response (200) N/A (Client-side initialization) #### Response Example N/A ``` -------------------------------- ### S2Environment Class Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Environment.html Documentation for the S2Environment class, including its constructor and static methods. ```APIDOC ## Class S2Environment ### Description Represents the S2 environment configuration. ### Constructors #### constructor() * `new S2Environment()`: Initializes a new instance of the S2Environment class. #### Returns - `S2Environment`: An instance of the S2Environment class. ### Methods #### `static` parse() * `S2Environment.parse()`: Parses the environment configuration. #### Returns - `S2EnvironmentConfig[]`: An array of S2 environment configuration objects. * Defined in `packages/streamstore/src/common.ts:70` ``` -------------------------------- ### Initialize Application Display - JavaScript Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/modules/AppendInput.html Initializes the application's display by hiding the body initially and then showing the main application page after a short delay. This is used to prevent content flashing before the application is ready or themed. ```javascript document.body.style.display="none"; setTimeout(() => window.app ? app.showPage() : document.body.style.removeProperty("display"), 500); ``` -------------------------------- ### S2Basin Constructor Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Basin.html Initializes a new S2Basin client for a specific basin. This client is used to manage streams within that basin. ```APIDOC ## new S2Basin(name: string, options: { accessToken: any; baseUrl: string; includeBasinHeader: boolean; retryConfig?: RetryConfig; }): S2Basin ### Description Create a basin-scoped client that talks to `https://{basin}.b.aws.s2.dev/v1`. Use this to work with streams inside a single basin. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (string) - Required - Basin name * **options** (object) - Required - Configuration for the basin-scoped client * **accessToken** (any) - Required - Access token for authentication * **baseUrl** (string) - Required - Base URL for the basin endpoint * **includeBasinHeader** (boolean) - Required - Whether to include the basin header * **retryConfig** (RetryConfig) - Optional - Configuration for retries ### Request Example ```json { "name": "my-basin", "options": { "accessToken": "your-access-token", "baseUrl": "https://my-basin.b.aws.s2.dev/v1", "includeBasinHeader": true } } ``` ### Response #### Success Response (200) * **S2Basin** - An instance of the S2Basin client #### Response Example ```json { "basinInstance": "S2Basin" } ``` ``` -------------------------------- ### POST /basins (Create Basin) Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Basins.html Creates a new basin with the specified configuration. Basin names must be globally unique. ```APIDOC ## POST /basins ### Description Create a basin. ### Method POST ### Endpoint /basins ### Parameters #### Request Body * **args** (object) - Required - Input for creating a basin. * **basin** (string) - Required - Basin name which must be globally unique. It can be between 8 and 48 characters in length, and comprise lowercase letters, numbers and hyphens. It cannot begin or end with a hyphen. * **config** (object) - Optional - Basin configuration. * *(See [BasinConfig](../interfaces/BasinConfig.html) for details)* * **scope** (string) - Optional - Basin scope. Example: "aws:us-east-1" * **options** ([S2RequestOptions](../types/S2RequestOptions.html)) - Optional - Request options. ### Request Example ```json { "args": { "basin": "my-unique-basin-name", "config": { "retention": "7d" }, "scope": "aws:us-east-1" } } ``` ### Response #### Success Response (200) * **CreateBasinResponse** (object) - The response from creating a basin. * *(See [CreateBasinResponse](../interfaces/CreateBasinResponse.html) for details)* #### Response Example ```json { "basin": "my-unique-basin-name", "config": { "retention": "7d" }, "scope": "aws:us-east-1" } ``` ``` -------------------------------- ### read API Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2Stream.html Reads records from the stream, supporting various starting positions and format options. ```APIDOC ## GET /stream/read ### Description Reads records from the stream. Supports specifying a starting position by sequence number, timestamp, or tail offset, and can clamp reads to the tail. Non-streaming reads are bounded by `count` and `bytes`. Use `readSession` for streaming reads. ### Method GET ### Endpoint /stream/read ### Parameters #### Query Parameters - **input** (ReadInput) - Optional - Specifies the starting position and other read constraints like `seq_num`, `timestamp`, `tail_offset`, `count`, and `bytes`. - **options** (S2RequestOptions & { as?: "string" | "bytes" }) - Optional - Configuration options for the request, including the format (`as`: "string" or "bytes") for the returned data. ### Response #### Success Response (200) - **readBatch** (ReadBatch) - A batch of records read from the stream, where `Format` can be 'string' or 'bytes'. #### Response Example ```json { "records": [ { "seq_num": 12346, "timestamp": "2023-10-27T10:01:00Z", "body": "SGVsbG8gV29ybGQ=", "header": {} } ] } ``` ``` -------------------------------- ### S2ClientOptions Configuration Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/S2ClientOptions.html This section details the configuration options available when initializing the S2 client. It covers authentication, various timeout settings, endpoint configuration, and retry mechanisms for robust API interactions. ```APIDOC ## S2ClientOptions Type ### Description Configuration for constructing the top-level `S2` client. The client authenticates using a Bearer access token on every request. ### Type Alias `S2ClientOptions` ### Properties #### Path Parameters * None #### Query Parameters * None #### Request Body * **accessToken** (string) - Required - Access token used for HTTP Bearer authentication. Typically obtained via your S2 account or created using `s2.accessTokens.issue`. * **connectionTimeoutMillis** (number) - Optional - Maximum time in milliseconds to wait for connection establishment. This is a "fail fast" timeout that aborts slow connections early. Connection time counts toward requestTimeoutMillis. Defaults to 3000ms. * **endpoints** (S2Endpoints | S2EndpointsInit) - Optional - Endpoint configuration for the S2 environment. Defaults to AWS (`aws.s2.dev` and `{basin}.b.aws.s2.dev`) with the API base path inferred as `/v1`. * **requestTimeoutMillis** (number) - Optional - Maximum time in milliseconds to wait for an append ack before considering the attempt timed out and applying retry logic. Used by retrying append sessions. When unset, defaults to 5000ms. * **retry** (RetryConfig) - Optional - Retry configuration for handling transient failures. Applies to management operations (basins, streams, tokens) and stream operations (read, append). Defaults to `{ maxAttempts: 3, minBaseDelayMillis: 100, maxBaseDelayMillis: 1000, appendRetryPolicy: "all" }`. ### Request Example ```json { "accessToken": "YOUR_ACCESS_TOKEN", "connectionTimeoutMillis": 5000, "endpoints": { "api": "https://api.s2.dev", "basin": "{basin}.b.aws.s2.dev" }, "requestTimeoutMillis": 10000, "retry": { "maxAttempts": 5, "minBaseDelayMillis": 200, "maxBaseDelayMillis": 2000, "appendRetryPolicy": "all" } } ``` ### Response #### Success Response (200) * **None** - This type defines client options and does not directly return a response body upon successful initialization. #### Response Example * N/A ``` -------------------------------- ### GET /metrics/{basin}/{stream} Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/API.StreamMetricsData.html Retrieves metrics data for a specific stream within a basin. Supports filtering by time range and interval. ```APIDOC ## GET /metrics/{basin}/{stream} ### Description Retrieves metrics data for a specific stream within a basin. Supports filtering by time range and interval. ### Method GET ### Endpoint /metrics/{basin}/{stream} ### Parameters #### Path Parameters - **basin** (string) - Required - The name of the basin. - **stream** (string) - Required - The name of the stream. #### Query Parameters - **start** (number) - Optional - Start timestamp as Unix epoch seconds, if applicable for the metric set. - **end** (number) - Optional - End timestamp as Unix epoch seconds, if applicable for metric set. - **interval** (TimeseriesInterval) - Optional - Interval to aggregate over for timeseries metric sets. - **set** (StreamMetricSet) - Required - Metric set to return. ### Request Example ```json { "example": "Not applicable for GET request body" } ``` ### Response #### Success Response (200) - **metricsData** (object) - The retrieved metrics data. #### Response Example ```json { "example": "{\"metric1\": 123, \"metric2\": 456}" } ``` ``` -------------------------------- ### List All Access Tokens Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/S2AccessTokens.html Lists all access tokens with automatic pagination. This method returns a lazy async iterable that fetches pages as needed. ```APIDOC ## GET /accessTokens ### Description Lists all access tokens with automatic pagination. Returns a lazy async iterable that fetches pages as needed. ### Method GET ### Endpoint /accessTokens ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filters tokens by ID prefix. - **limit** (number) - Optional - Maximum number of results per page. #### Request Body None ### Request Example ```typescript for await (const token of s2.accessTokens.listAll({ prefix: "service-" })) { console.log(token.id); } ``` ### Response #### Success Response (200) - **tokens** (Array) - An array of access token information objects. #### Response Example ```json { "tokens": [ { "id": "token-123", "createdAt": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Get Stream Configuration Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/API.GetStreamConfigResponses.html Retrieves the configuration for a stream. This endpoint returns a StreamConfig object upon successful execution. ```APIDOC ## GET /api/stream/config ### Description Retrieves the configuration for a stream. This endpoint returns a StreamConfig object upon successful execution. ### Method GET ### Endpoint /api/stream/config ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **200** (object) - An object containing the StreamConfig. - **streamConfig** (object) - The configuration details for the stream. #### Response Example ```json { "200": { "streamId": "string", "streamName": "string", "createdAt": "string", "updatedAt": "string" } } ``` ``` -------------------------------- ### Theme Initialization and App Display Logic Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/API.BasinMetricsResponse.html This snippet initializes the document theme based on local storage and controls the initial display of the application body. It uses a timeout to ensure the application is ready before showing the page. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.removeProperty("display"),500) ``` -------------------------------- ### ReadFrom Type Alias Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/ReadFrom.html Defines the possible starting positions for reading data from a stream. This includes options based on sequence number, timestamp, or an offset. ```APIDOC ## ReadFrom Type Alias ### Description Defines the possible starting positions for reading data from a stream. This includes options based on sequence number, timestamp, or an offset. ### Type Alias `ReadFrom` ### Definition ```typescript { seqNum: number; } | { timestamp: number | Date; } | { tailOffset: number; } ``` ### Usage This type is used to specify where to begin reading from a stream in the s2-streamstore. You can choose to start at a specific sequence number, a particular point in time, or from a certain offset relative to the end of the stream. ``` -------------------------------- ### Get Stream Configuration Data Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/types/API.GetStreamConfigData.html Retrieves the configuration data for a specified stream. This endpoint requires the stream name as a path parameter. ```APIDOC ## GET /streams/{stream} ### Description Retrieves the configuration data for a specified stream. This endpoint requires the stream name as a path parameter. ### Method GET ### Endpoint /streams/{stream} ### Parameters #### Path Parameters - **stream** (string) - Required - The name of the stream for which to retrieve configuration data. #### Query Parameters This endpoint does not accept query parameters. #### Request Body This endpoint does not accept a request body. ### Request Example ```json { "example": "No request body needed for GET request" } ``` ### Response #### Success Response (200) - **stream** (string) - The name of the stream. - **config** (object) - An object containing the stream's configuration details. (Note: Specific fields within config are not detailed in the provided text but would typically include settings like retention policies, shard counts, etc.) #### Response Example ```json { "stream": "my-stream-name", "config": { "retention": "7d", "shards": 3 } } ``` ``` -------------------------------- ### Error.prepareStackTrace Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/classes/RangeNotSatisfiableError.html Allows for customization of how stack traces are formatted. This method is called by the V8 engine when a stack trace is generated. ```APIDOC ## POST /error/prepareStackTrace ### Description Customizes the formatting of error stack traces. This endpoint is intended for advanced usage where specific stack trace formatting is required. ### Method POST ### Endpoint /error/prepareStackTrace ### Parameters #### Request Body - **err** (Error) - The error object for which the stack trace is being prepared. - **stackTraces** (Array) - An array of CallSite objects representing the stack frames. ### Request Example ```json { "err": { "name": "CustomError", "message": "Something went wrong" }, "stackTraces": [ { "getFileName": () => "file.js", "getLineNumber": () => 10, "getMethodName": () => "myFunction" } ] } ``` ### Response #### Success Response (200) - **formattedStackTrace** (any) - The custom formatted stack trace string or object. #### Response Example ```json { "formattedStackTrace": "CustomError: Something went wrong\n at myFunction (file.js:10)" } ``` ``` -------------------------------- ### Initialize Theme from Local Storage with TypeScript Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/functions/AppendRecord.string.html This snippet initializes the application's theme based on the value stored in local storage. If no theme is found, it defaults to 'os'. It also includes a mechanism to progressively display the body content after a short delay. ```typescript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### ReadInput Interface Properties - TypeScript Source: https://github.com/s2-streamstore/s2-sdk-typescript/blob/main/docs/interfaces/ReadInput.html Details the optional properties of the ReadInput interface. 'ignoreCommandRecords' is a boolean, 'start' and 'stop' can be of types ReadStart and ReadStop respectively. ```typescript ignoreCommandRecords?: boolean; start?: [ReadStart](ReadStart.html); stop?: [ReadStop](ReadStop.html); ```