import { Readable, Writable } from "node:stream"; //#region src/iii-types.d.ts declare enum MessageType { RegisterFunction = "registerfunction", UnregisterFunction = "unregisterfunction", InvokeFunction = "invokefunction", InvocationResult = "invocationresult", RegisterTriggerType = "registertriggertype", RegisterTrigger = "registertrigger", UnregisterTrigger = "unregistertrigger", UnregisterTriggerType = "unregistertriggertype", TriggerRegistrationResult = "triggerregistrationresult", WorkerRegistered = "workerregistered" } type RegisterTriggerTypeMessage = { message_type: MessageType.RegisterTriggerType; id: string; description: string; }; type RegisterTriggerMessage = { message_type: MessageType.RegisterTrigger; id: string; type: string; function_id: string; config: unknown; metadata?: Record; }; /** * Authentication configuration for HTTP-invoked functions. * * - `hmac` -- HMAC signature verification using a shared secret. * - `bearer` -- Bearer token authentication. * - `api_key` -- API key sent via a custom header. */ type HttpAuthConfig = { type: 'hmac'; secret_key: string; } | { type: 'bearer'; token_key: string; } | { type: 'api_key'; header: string; value_key: string; }; /** * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare * Workers, etc.) instead of a local handler. */ type HttpInvocationConfig = { /** URL to invoke. */url: string; /** HTTP method. Defaults to `POST`. */ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Timeout in milliseconds. */ timeout_ms?: number; /** Custom headers to send with the request. */ headers?: Record; /** Authentication configuration. */ auth?: HttpAuthConfig; }; type RegisterFunctionFormat = { /** * The name of the parameter */ name?: string; /** * The description of the parameter */ description?: string; /** * The type of the parameter */ type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'; /** * The body of the parameter (for objects) */ properties?: Record; /** * The items of the parameter (for arrays) */ items?: unknown; /** * Whether the parameter is required */ required?: string[]; [key: string]: unknown; }; type RegisterFunctionMessage = { message_type: MessageType.RegisterFunction; /** * The path of the function (use :: for namespacing, e.g. external::my_lambda) */ id: string; /** * The description of the function */ description?: string; /** * The request format of the function */ request_format?: RegisterFunctionFormat; /** * The response format of the function */ response_format?: RegisterFunctionFormat; metadata?: Record; /** * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.) */ invocation?: HttpInvocationConfig; }; /** * Routing action for {@link TriggerRequest}. Determines how the engine * handles the invocation. * * - `enqueue` -- Routes through a named queue for async processing. * - `void` -- Fire-and-forget, no response. */ type TriggerAction = { type: 'enqueue'; queue: string; } | { type: 'void'; }; /** * Input passed to the RBAC auth function during WebSocket upgrade. * Contains the HTTP headers, query parameters, and client IP from the * connecting worker's upgrade request. */ type AuthInput = { /** HTTP headers from the WebSocket upgrade request. */headers: Record; /** Query parameters from the upgrade URL. Each key maps to an array of values to support repeated keys. */ query_params: Record; /** IP address of the connecting client. */ ip_address: string; }; /** * Return value from the RBAC auth function. Controls which functions the * authenticated worker can invoke and what context is forwarded to the * middleware. */ type AuthResult = { /** Additional function IDs to allow beyond the `expose_functions` config. */allowed_functions: string[]; /** Function IDs to deny even if they match `expose_functions`. Takes precedence over allowed. */ forbidden_functions: string[]; /** Trigger type IDs the worker may register triggers for. When omitted, all types are allowed. */ allowed_trigger_types?: string[]; /** Whether the worker may register new trigger types. */ allow_trigger_type_registration: boolean; /** Whether the worker may register new functions. Defaults to `true` if omitted. */ allow_function_registration?: boolean; /** Arbitrary context forwarded to the middleware function on every invocation. */ context: Record; /** Optional prefix applied to all function IDs registered by this worker. */ function_registration_prefix?: string; }; /** * Input passed to the RBAC middleware function on every function invocation * through the RBAC port. The middleware can inspect, modify, or reject the * call before it reaches the target function. */ type MiddlewareFunctionInput = { /** ID of the function being invoked. */function_id: string; /** Payload sent by the caller. */ payload: Record; /** Routing action, if any. */ action?: TriggerAction; /** Auth context returned by the auth function for this session. */ context: Record; }; /** * Input passed to the `on_trigger_type_registration_function_id` hook * when a worker attempts to register a new trigger type through the RBAC port. * Return an {@link OnTriggerTypeRegistrationResult} with the (possibly mapped) * fields, or throw to deny the registration. */ type OnTriggerTypeRegistrationInput = { /** ID of the trigger type being registered. */trigger_type_id: string; /** Human-readable description of the trigger type. */ description: string; /** Auth context from `AuthResult.context` for this session. */ context: Record; }; /** * Result returned from the `on_trigger_type_registration_function_id` hook. * All fields are optional -- omitted fields keep the original value from the * registration request. */ type OnTriggerTypeRegistrationResult = { /** Mapped trigger type ID. */trigger_type_id?: string; /** Mapped description. */ description?: string; }; /** * Input passed to the `on_trigger_registration_function_id` hook * when a worker attempts to register a trigger through the RBAC port. * Return an {@link OnTriggerRegistrationResult} with the (possibly mapped) * fields, or throw to deny the registration. */ type OnTriggerRegistrationInput = { /** ID of the trigger being registered. */trigger_id: string; /** Trigger type identifier. */ trigger_type: string; /** ID of the function this trigger is bound to. */ function_id: string; /** Trigger-specific configuration. */ config: unknown; /** Arbitrary metadata attached to the trigger. */ metadata?: Record; /** Auth context from `AuthResult.context` for this session. */ context: Record; }; /** * Result returned from the `on_trigger_registration_function_id` hook. * All fields are optional -- omitted fields keep the original value from the * registration request. */ type OnTriggerRegistrationResult = { /** Mapped trigger ID. */trigger_id?: string; /** Mapped trigger type. */ trigger_type?: string; /** Mapped function ID. */ function_id?: string; /** Mapped trigger configuration. */ config?: unknown; }; /** * Input passed to the `on_function_registration_function_id` hook * when a worker attempts to register a function through the RBAC port. * Return an {@link OnFunctionRegistrationResult} with the (possibly mapped) * fields, or throw to deny the registration. */ type OnFunctionRegistrationInput = { /** ID of the function being registered. */function_id: string; /** Human-readable description of the function. */ description?: string; /** Arbitrary metadata attached to the function. */ metadata?: Record; /** Auth context from `AuthResult.context` for this session. */ context: Record; }; /** * Result returned from the `on_function_registration_function_id` hook. * All fields are optional -- omitted fields keep the original value from the * registration request. */ type OnFunctionRegistrationResult = { /** Mapped function ID. */function_id?: string; /** Mapped description. */ description?: string; /** Mapped metadata. */ metadata?: Record; }; /** * Result returned when a function is invoked with `TriggerAction.Enqueue`. */ type EnqueueResult = { /** Unique receipt ID for the enqueued message. */messageReceiptId: string; }; /** * Request object passed to {@link ISdk.trigger}. * * @typeParam TInput - Type of the payload. */ type TriggerRequest = { /** ID of the function to invoke. */function_id: string; /** Payload to pass to the function. */ payload: TInput; /** Routing action. Omit for synchronous request/response. */ action?: TriggerAction; /** Override the default invocation timeout in milliseconds. */ timeoutMs?: number; }; /** * Serializable reference to one end of a streaming channel. Can be included * in invocation payloads to pass channel endpoints between workers. */ type StreamChannelRef = { /** Unique channel identifier. */channel_id: string; /** Access key for authentication. */ access_key: string; /** Whether this ref is for reading or writing. */ direction: 'read' | 'write'; }; //#endregion //#region src/channels.d.ts /** * Direction of a streaming channel endpoint. Mirrors the Rust SDK's * `ChannelDirection` enum and matches the literal values used by * {@link StreamChannelRef.direction}. */ declare const ChannelDirection: { readonly Read: "read"; readonly Write: "write"; }; type ChannelDirection = (typeof ChannelDirection)[keyof typeof ChannelDirection]; /** * Discriminated runtime tag for an item observed on a streaming channel. * Mirrors the Rust SDK's `ChannelItem` enum (`Text` / `Binary`). Carrier for * factory + type-guard helpers so callers can construct and discriminate * channel items without depending on Rust-specific shape. */ type ChannelItem = { type: 'text'; value: string; } | { type: 'binary'; value: Uint8Array; }; declare const ChannelItem: { /** Construct a text channel item. */readonly Text: (value: string) => ChannelItem; /** Construct a binary channel item. */ readonly Binary: (value: Uint8Array) => ChannelItem; }; /** * Write end of a streaming channel. Provides both a Node.js `Writable` stream * and a `sendMessage` method for sending structured text messages. * * @example * ```typescript * import { createChannel } from 'iii-sdk/helpers' * const channel = await createChannel(iii) * * // Stream binary data * channel.writer.stream.write(Buffer.from('hello')) * channel.writer.stream.end() * * // Or send text messages * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' })) * channel.writer.close() * ``` */ declare class ChannelWriter { private static readonly FRAME_SIZE; private ws; private wsReady; private readonly pendingMessages; /** Node.js Writable stream for binary data. */ readonly stream: Writable; private readonly url; constructor(engineWsBase: string, ref: StreamChannelRef); private ensureConnected; /** Send a text message through the channel. */ sendMessage(msg: string): void; /** Close the channel writer. */ close(): void; private sendChunked; private sendRaw; } /** * Read end of a streaming channel. Provides both a Node.js `Readable` stream * for binary data and an `onMessage` callback for structured text messages. * * @example * ```typescript * import { createChannel } from 'iii-sdk/helpers' * const channel = await createChannel(iii) * * // Stream binary data * channel.reader.stream.on('data', (chunk) => console.log(chunk)) * * // Or receive text messages * channel.reader.onMessage((msg) => console.log('Got:', msg)) * ``` */ declare class ChannelReader { private ws; private connected; private readonly messageCallbacks; /** Node.js Readable stream for binary data. */ readonly stream: Readable; private readonly url; constructor(engineWsBase: string, ref: StreamChannelRef); private ensureConnected; /** Register a callback to receive text messages from the channel. */ onMessage(callback: (msg: string) => void): void; readAll(): Promise; close(): void; } //#endregion //#region src/triggers.d.ts /** * Configuration passed to a trigger handler when a trigger instance is * registered or unregistered. * * @typeParam TConfig - Type of the trigger-specific configuration. */ type TriggerConfig = { /** Trigger instance ID. */id: string; /** Function to invoke when the trigger fires. */ function_id: string; /** Trigger-specific configuration. */ config: TConfig; /** Arbitrary metadata attached to the trigger. */ metadata?: Record; }; /** * Handler interface for custom trigger types. Passed to * `ISdk.registerTriggerType`. * * @typeParam TConfig - Type of the trigger-specific configuration. * * @example * ```typescript * const handler: TriggerHandler<{ interval: number }> = { * async registerTrigger({ id, function_id, config }) { * // Set up periodic invocation * }, * async unregisterTrigger({ id, function_id, config }) { * // Clean up * }, * } * ``` */ type TriggerHandler = { /** Called when a trigger instance is registered. */registerTrigger(config: TriggerConfig): Promise; /** Called when a trigger instance is unregistered. */ unregisterTrigger(config: TriggerConfig): Promise; }; //#endregion //#region src/types.d.ts /** * Async function handler for a registered function. Receives the invocation * payload and returns the result. * * @typeParam TInput - Type of the invocation payload. * @typeParam TOutput - Type of the return value. * * @example * ```typescript * const handler: RemoteFunctionHandler<{ name: string }, { message: string }> = * async (data) => ({ message: `Hello, ${data.name}!` }) * ``` */ type RemoteFunctionHandler = (data: TInput) => Promise; type RegisterTriggerInput = Omit; type RegisterFunctionInput = Omit; type RegisterFunctionOptions = Omit; type RegisterTriggerTypeInput = Omit; interface ISdk { /** * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs. * @param trigger - The trigger to register * @returns A trigger object that can be used to unregister the trigger * * @example * ```typescript * const trigger = iii.registerTrigger({ * type: 'cron', * function_id: 'my-service::process-batch', * config: { expression: '0 *\/5 * * * * *' }, * }) * * // Later, remove the trigger * trigger.unregister() * ``` */ registerTrigger(trigger: RegisterTriggerInput): Trigger; /** * Registers a new function with a local handler or an HTTP invocation config. * @param functionId - Unique function identifier * @param handler - Async handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.) * @param options - Optional function registration options (description, request/response formats, metadata) * @returns A handle that can be used to unregister the function * * @example * ```typescript * // Local handler * const ref = iii.registerFunction( * 'greet', * async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }), * { description: 'Returns a greeting' }, * ) * * // HTTP invocation * const lambdaRef = iii.registerFunction( * 'external::my-lambda', * { * url: 'https://abc123.lambda-url.us-east-1.on.aws', * method: 'POST', * timeout_ms: 30_000, * auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' }, * }, * { description: 'Proxied Lambda function' }, * ) * * // Later, remove the function * ref.unregister() * ``` */ registerFunction(functionId: string, handler: RemoteFunctionHandler | HttpInvocationConfig, options?: RegisterFunctionOptions): FunctionRef; /** * Invokes a function using a request object. * * @param request - The trigger request containing function_id, payload, and optional action/timeout * @returns The result of the function * * @example * ```typescript * // Synchronous invocation * const result = await iii.trigger<{ name: string }, { message: string }>({ * function_id: 'greet', * payload: { name: 'World' }, * timeoutMs: 5000, * }) * console.log(result.message) // "Hello, World!" * * // Fire-and-forget * await iii.trigger({ * function_id: 'send-email', * payload: { to: 'user@example.com' }, * action: TriggerAction.Void(), * }) * * // Enqueue for async processing * const receipt = await iii.trigger({ * function_id: 'process-order', * payload: { orderId: '123' }, * action: TriggerAction.Enqueue({ queue: 'orders' }), * }) * ``` */ trigger(request: TriggerRequest): Promise; /** * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs. * @param triggerType - The trigger type to register * @param handler - The handler for the trigger type * @returns A trigger type object that can be used to unregister the trigger type * * @example * ```typescript * type CronConfig = { expression: string } * * iii.registerTriggerType( * { id: 'cron', description: 'Fires on a cron schedule' }, * { * async registerTrigger({ id, function_id, config }) { * startCronJob(id, config.expression, () => * iii.trigger({ function_id, payload: {} }), * ) * }, * async unregisterTrigger({ id }) { * stopCronJob(id) * }, * }, * ) * ``` */ registerTriggerType(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler): TriggerTypeRef; /** * Unregisters a trigger type. * @param triggerType - The trigger type to unregister * * @example * ```typescript * iii.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' }) * ``` */ unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void; /** * Gracefully shutdown the iii, cleaning up all resources. * * @example * ```typescript * process.on('SIGTERM', async () => { * await iii.shutdown() * process.exit(0) * }) * ``` */ shutdown(): Promise; } /** * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to * remove the trigger from the engine. */ type Trigger = { /** Removes this trigger from the engine. */unregister(): void; }; /** * Handle returned by {@link ISdk.registerFunction}. Contains the function's * `id` and an `unregister()` method. */ type FunctionRef = { /** The unique function identifier. */id: string; /** Removes this function from the engine. */ unregister: () => void; }; /** * Typed handle returned by {@link ISdk.registerTriggerType}. * * Provides convenience methods to register triggers and functions scoped * to this trigger type, so callers don't need to repeat the `type` field. * * @typeParam TConfig - Trigger-specific configuration type. * * @example * ```typescript * type CronConfig = { expression: string } * * const cron = iii.registerTriggerType( * { id: 'cron', description: 'Fires on a cron schedule' }, * cronHandler, * ) * * // Register a trigger — type is inferred as CronConfig * cron.registerTrigger('my::fn', { expression: '0 *\/5 * * * * *' }) * * // Register a function and bind a trigger in one call * cron.registerFunction( * 'my::fn', * async (data) => { return { ok: true } }, * { expression: '0 *\/5 * * * * *' }, * ) * ``` */ type TriggerTypeRef = { /** The trigger type identifier. */id: string; /** * Register a trigger bound to this trigger type. * * @param functionId - The function to invoke when the trigger fires. * @param config - Trigger-specific configuration. * @param metadata - Optional arbitrary metadata attached to the trigger. * @returns A {@link Trigger} handle with an `unregister()` method. */ registerTrigger(functionId: string, config: TConfig, metadata?: Record): Trigger; /** * Register a function and immediately bind it to this trigger type. * * @param functionId - Unique function identifier. * @param handler - Local function handler. * @param config - Trigger-specific configuration. * @param metadata - Optional arbitrary metadata attached to the trigger. * @returns A {@link FunctionRef} handle. */ registerFunction(functionId: string, handler: RemoteFunctionHandler, config: TConfig, metadata?: Record): FunctionRef; /** * Unregister this trigger type from the engine. */ unregister(): void; }; /** * A streaming channel pair for worker-to-worker data transfer. Created via * the `createChannel` helper from `iii-sdk/helpers`. */ type Channel = { /** Writer end of the channel. */writer: ChannelWriter; /** Reader end of the channel. */ reader: ChannelReader; /** Serializable reference to the writer (can be sent to other workers). */ writerRef: StreamChannelRef; /** Serializable reference to the reader (can be sent to other workers). */ readerRef: StreamChannelRef; }; type InternalHttpRequest = { path_params: Record; query_params: Record; body: TBody; headers: Record; method: string; response: ChannelWriter; request_body: ChannelReader; }; /** * Response object passed to HTTP function handlers. Use `status()` and * `headers()` to set response metadata, write to `stream` for streaming * responses, and call `close()` when done. */ type HttpResponse = { /** Set the HTTP status code. */status: (statusCode: number) => void; /** Set response headers. */ headers: (headers: Record) => void; /** Writable stream for the response body. */ stream: NodeJS.WritableStream; /** Close the response. */ close: () => void; }; /** * Incoming HTTP request received by a function registered with an HTTP trigger. * * @typeParam TBody - Type of the parsed request body. */ type HttpRequest = Omit, 'response'>; /** * Alias for {@link HttpRequest}. Represents an incoming API request. * * @typeParam TBody - Type of the parsed request body. */ type ApiRequest = HttpRequest; /** * Structured API response returned from HTTP function handlers. * * @typeParam TStatus - HTTP status code literal type. * @typeParam TBody - Type of the response body. * * @example * ```typescript * const response: ApiResponse = { * status_code: 200, * headers: { 'content-type': 'application/json' }, * body: { message: 'ok' }, * } * ``` */ type ApiResponse> = { /** HTTP status code. */status_code: TStatus; /** Response headers. */ headers?: Record; /** Response body. */ body?: TBody; }; //#endregion //#region src/utils.d.ts /** * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments) * into the function handler format expected by the SDK. * * @param callback - Async handler receiving an {@link HttpRequest} and {@link HttpResponse}. * @returns A function handler compatible with {@link ISdk.registerFunction}. * * @example * ```typescript * import { http } from 'iii-sdk' * * iii.registerFunction( * 'my-api', * http(async (req, res) => { * res.status(200) * res.headers({ 'content-type': 'application/json' }) * res.stream.end(JSON.stringify({ hello: 'world' })) * res.close() * }), * ) * ``` */ declare const http: (callback: (req: HttpRequest, res: HttpResponse) => Promise) => (req: InternalHttpRequest) => Promise; /** * Type guard that checks if a value is a {@link StreamChannelRef}. * * @param value - Value to check. * @returns `true` if the value is a valid `StreamChannelRef`. */ declare const isChannelRef: (value: unknown) => value is StreamChannelRef; /** * Recursively extract all {@link StreamChannelRef} values from a JSON-like * input, returning each match paired with its dotted/bracketed path. Mirrors * the Rust SDK's `extract_channel_refs`. * * @param data - Arbitrary JSON-like value. * @returns Array of `[path, ref]` tuples. Empty when no refs are found. */ declare const extractChannelRefs: (data: unknown) => Array<[string, StreamChannelRef]>; //#endregion export { MessageType as A, RegisterTriggerTypeMessage as B, ChannelReader as C, EnqueueResult as D, AuthResult as E, OnTriggerRegistrationResult as F, TriggerAction as H, OnTriggerTypeRegistrationInput as I, OnTriggerTypeRegistrationResult as L, OnFunctionRegistrationInput as M, OnFunctionRegistrationResult as N, HttpAuthConfig as O, OnTriggerRegistrationInput as P, RegisterFunctionMessage as R, ChannelItem as S, AuthInput as T, TriggerRequest as U, StreamChannelRef as V, Trigger as _, ApiResponse as a, TriggerHandler as b, HttpRequest as c, InternalHttpRequest as d, RegisterFunctionInput as f, RemoteFunctionHandler as g, RegisterTriggerTypeInput as h, ApiRequest as i, MiddlewareFunctionInput as j, HttpInvocationConfig as k, HttpResponse as l, RegisterTriggerInput as m, http as n, Channel as o, RegisterFunctionOptions as p, isChannelRef as r, FunctionRef as s, extractChannelRefs as t, ISdk as u, TriggerTypeRef as v, ChannelWriter as w, ChannelDirection as x, TriggerConfig as y, RegisterTriggerMessage as z }; //# sourceMappingURL=utils-DcbZmefT.d.cts.map