import { JsonValue } from '@bufbuild/protobuf'; import { ValueJson } from '@bufbuild/protobuf/wkt'; import { Client, Code, ConnectError } from '@connectrpc/connect'; import { SignalData } from '../genproto/mochabugapis/adapt/graph/v1/signal_data_pb.js'; import { SignalFormatJson } from '../genproto/mochabugapis/adapt/graph/v1/signal_format_pb.js'; import { VertexMetadataJson } from '../genproto/mochabugapis/adapt/graph/v1/vertex_metadata_pb.js'; import { ConfiguratorService, ListIncomingSignalsResponseJson } from '../genproto/mochabugapis/adapt/runtime/v1/configurator_service_pb.js'; import { ExchangeOperation, ExecutorService } from '../genproto/mochabugapis/adapt/runtime/v1/executor_service_pb.js'; import { FileForgeService, HtmlRenderOptionsJson, ImageAdjustJson, ImageBlurJson, ImageCropJson, ImageDpiJson, ImageFlipJson, ImageFocalJson, ImageHueJson, ImageTextJson, ImageMaxFramesJson, ImageOutputJson, ImagePadJson, ImagePageJson, ImageProportionJson, ImageResizeJson, ImageRgbJson, ImageRotateJson, ImageRoundCornerJson, ImageSharpenJson, ImageTrimJson, ImageWatermarkJson, OfficeRenderOptionsJson, PdfAFormat, PdfOutputOptionsJson } from '../genproto/mochabugapis/adapt/runtime/v1/fileforge_service_pb.js'; import { PluginService, Token } from '../genproto/mochabugapis/adapt/runtime/v1/plugin_service_pb.js'; import { GetValue, NamespaceJson, SelectOpJson, WriteOperation } from '../genproto/mochabugapis/adapt/runtime/v1/store_pb.js'; import type { ConfiguratorEnvironment, Environment, ExecutorEnvironment } from '@mochabug/adapt-builder/runtime'; export { Code, ConnectError }; export type { ValueJson }; /** * Represents the content of an asset file. */ export type AssetFile = { /** * Content of the asset file as a readable stream. */ content: ReadableStream; /** * MIME type of the asset file. */ mime: string; }; /** * Base class for API interactions. Extended by specific API implementations. * Not intended for direct use. */ export declare class ApiBase { protected env: Environment; protected pluginService: Client; protected readonly pluginToken: string; protected fileforge: Client; protected authorization?: { token: string; promise: Promise; verified: boolean; }; /** * Initializes the ApiBase instance with environment settings and a plugin token. * * @param env - Environment configuration for API communication. * @param pluginToken - Token for plugin authentication. */ constructor(env: Environment, pluginToken: string); /** * Retrieves a single plugin-scoped variable by its name. * Supports dot notation for nested variable names (e.g., 'api.credentials.key'). * * @param name - The name of the variable (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*(?:\.[_$a-zA-Z][_$a-zA-Z0-9]*)*$). * @returns A promise that resolves with the variable value (undefined if not found). * * @example * ```typescript * const apiUrl = await api.getSystemVariable('api.url'); * const nested = await api.getSystemVariable('config.database.host'); * ``` */ getSystemVariable(name: string): Promise; /** * Retrieves multiple plugin-scoped variables by their names with full type safety. * Supports dot notation for nested variable names. * * @template T - Record type mapping variable names to their expected types. * @param keys - Names of the variables to retrieve (1-100 unique names, each 1-100 chars). * @returns A promise that resolves with an object mapping variable names to their typed values. * @throws {ConnectError} Code.InvalidArgument if keys array is empty or exceeds 100 items. * * @example * ```typescript * const vars = await api.getSystemVariables<{ * 'api.url': string; * 'api.timeout': number; * 'api.enabled': boolean; * }>('api.url', 'api.timeout', 'api.enabled'); * * // Fully typed! * vars['api.url']; // string * vars['api.timeout']; // number * vars['api.enabled']; // boolean * ``` */ getSystemVariables>(...keys: Array): Promise; /** * Retrieves a single user-scoped variable by its name. * Supports dot notation for nested variable names (e.g., 'user.preferences.theme'). * * @param name - The name of the variable (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*(?:\.[_$a-zA-Z][_$a-zA-Z0-9]*)*$). * @returns A promise that resolves with the user variable value (undefined if not found). * * @example * ```typescript * const theme = await api.getUserVariable('user.preferences.theme'); * const email = await api.getUserVariable('user.email'); * ``` */ getUserVariable(name: string): Promise; /** * Retrieves multiple user-scoped variables by their names with full type safety. * Supports dot notation for nested variable names. * * @template T - Record type mapping variable names to their expected types. * @param keys - Names of the user variables to retrieve (1-100 unique names, each 1-100 chars). * @returns A promise that resolves with an object mapping variable names to their typed values. * @throws {ConnectError} Code.InvalidArgument if keys array is empty or exceeds 100 items. * * @example * ```typescript * const vars = await api.getUserVariables<{ * 'user.email': string; * 'user.age': number; * 'user.verified': boolean; * }>('user.email', 'user.age', 'user.verified'); * * // Fully typed! * vars['user.email']; // string * vars['user.age']; // number * vars['user.verified']; // boolean * ``` */ getUserVariables>(...keys: Array): Promise; /** * Retrieves a single user OAuth2 bearer token by its name. * Returns a Token object containing the access token, type (typically 'Bearer'), and expiration timestamp. * * @param name - The name of the user token (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*(?:\.[_$a-zA-Z][_$a-zA-Z0-9]*)*$). * @returns A promise that resolves with the Token object (undefined if not found). * Token contains: { name, token, type, expires } * * @example * ```typescript * const githubToken = await api.getUserToken('github'); * if (githubToken) { * console.log(githubToken.token, githubToken.type, githubToken.expires); * } * ``` */ getUserToken(name: string): Promise; /** * Retrieves multiple user OAuth2 bearer tokens by their names. * Each Token contains the access token, type (typically 'Bearer'), and expiration timestamp. * * @param names - Names of the user tokens to retrieve (1-100 unique names, each 1-100 chars). * @returns A promise that resolves with an object mapping token names to their Token objects. * Each Token contains: { name, token, type, expires } * @throws {ConnectError} Code.InvalidArgument if names array is empty or exceeds 100 items. * * @example * ```typescript * const tokens = await api.getUserTokens('github', 'google'); * * tokens['github']; // Token | undefined * tokens['google']; // Token | undefined * ``` */ getUserTokens(...names: string[]): Promise>; /** * Retrieves a single plugin OAuth2 bearer token from a service account by its name. * Returns a Token object containing the access token, type (typically 'Bearer'), and expiration timestamp. * * @param name - The name of the plugin token (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*(?:\.[_$a-zA-Z][_$a-zA-Z0-9]*)*$). * @returns A promise that resolves with the Token object (undefined if not found). * Token contains: { name, token, type, expires } * * @example * ```typescript * const serviceToken = await api.getSystemToken('service_account'); * if (serviceToken) { * console.log(serviceToken.token, serviceToken.expires); * } * ``` */ getSystemToken(name: string): Promise; /** * Retrieves multiple plugin OAuth2 bearer tokens from service accounts by their names. * Each Token contains the access token, type (typically 'Bearer'), and expiration timestamp. * * @param names - Names of the plugin tokens to retrieve (1-100 unique names, each 1-100 chars). * @returns A promise that resolves with an object mapping token names to their Token objects. * Each Token contains: { name, token, type, expires } * @throws {ConnectError} Code.InvalidArgument if names array is empty or exceeds 100 items. * * @example * ```typescript * const tokens = await api.getSystemTokens('service_account', 'backup_service'); * * tokens['service_account']; // Token | undefined * tokens['backup_service']; // Token | undefined * ``` */ getSystemTokens(...names: string[]): Promise>; /** * Creates a fetch function for user-level HTTP proxy requests. * * User services are vertex-level configurations where each user can provide * their own certificates, API keys, and credentials. * * @param name - The service name defined in vertex user_services * @returns A fetch function configured with HTTP proxy headers * * @example * ```typescript * const fetch = api.userHttpProxy("stripe_api"); * const res = await fetch("https://api.stripe.com/v1/charges"); * ``` */ userHttpProxy(name: string): typeof fetch; /** * Creates a fetch function for system-level HTTP proxy requests. * * System services are plugin-wide configurations shared across all vertices. * Configured once by plugin administrators. * * @param name - The service name defined in manifest system_services * @returns A fetch function configured with HTTP proxy headers * * @example * ```typescript * const fetch = api.systemHttpProxy("internal_api"); * const res = await fetch("https://internal.example.com/data"); * ``` */ systemHttpProxy(name: string): typeof fetch; /** * Validates an access token to ensure it's authorized for the current plugin and execution context. * The trusted plugin token identifies the route; the candidate retains its own permissions. * Each explicit call revalidates the token with the backend. * * @param token - The access token to validate (max 10000 chars). * @returns A promise that resolves when the token is successfully validated. * @throws {ConnectError} Code.Unauthenticated if the token is invalid or Code.PermissionDenied if unauthorized. * * @example * ```typescript * try { * await api.authorize(userProvidedToken); * // Token is valid, proceed with operations * } catch (error) { * // Token is invalid or lacks permissions * } * ``` */ authorize(token: string): Promise; /** * Get information about configured system services. * System services are plugin-wide configurations shared across all vertices. * * @returns A promise that resolves with a map of configured services where keys are service paths * (using dot notation for nested services) and values indicate if the service is configured. * * @example * ```typescript * const services = await api.getSystemServices(); * // Returns { "http_service": true, "oneof_service.option_a": true, "grouped.nested": true } * ``` */ getSystemServices(): Promise<{ [key: string]: boolean; }>; /** * Reads a file from the plugin's assets directory. * * @param path - The file path relative to the assets directory. * @returns A promise that resolves with the file content and MIME type. * @throws {ConnectError} If the file is not found. */ readFile(path: string): Promise; /** * Helper to create SignalData from BinaryFile. * Sets mime-type to application/octet-stream as the API relies on filename for format detection. */ private createSignalData; /** * Helper to extract BinaryFile from SignalData response. */ private extractBinaryFile; /** * Convert HTML content to PDF using Chromium. * * @param options - HTML to PDF conversion options * @param options.indexHtml - Main HTML content (required, max 10MB) * @param options.headerHtml - Header HTML template (max 1MB) * @param options.footerHtml - Footer HTML template (max 1MB) * @param options.assets - Asset files (images, CSS, etc.) - max 100 files * @param options.render - Rendering options (margins, scale, orientation, etc.) * @param options.output - PDF output options (PDF/A, encryption, etc.) * @returns The rendered PDF file * * @example * ```typescript * const pdf = await api.htmlToPdf({ * indexHtml: '

Hello World

', * render: { landscape: true, printBackground: true } * }); * ``` */ htmlToPdf(options: { indexHtml: string; headerHtml?: string; footerHtml?: string; assets?: BinaryFile[]; render?: HtmlRenderOptionsJson; output?: PdfOutputOptionsJson; }): Promise; /** * Convert Markdown files to PDF using Chromium. * Markdown is rendered using gomarkdown library with support for tables, footnotes, * task lists, MathJax, and more. * * @param options - Markdown to PDF conversion options * @param options.wrapperHtml - HTML wrapper with styling (required). Body must be empty. * @param options.markdownFiles - Markdown files to convert (1-50 files, rendered in order) * @param options.headerHtml - Header HTML template (max 1MB) * @param options.footerHtml - Footer HTML template (max 1MB) * @param options.assets - Asset files (images, etc.) - max 100 files * @param options.render - Rendering options * @param options.output - PDF output options * @returns The rendered PDF file * * @example * ```typescript * const pdf = await api.markdownToPdf({ * wrapperHtml: '', * markdownFiles: [ * { filename: 'chapter1.md', data: new TextEncoder().encode('# Chapter 1\n\nHello!') } * ] * }); * ``` */ markdownToPdf(options: { wrapperHtml: string; markdownFiles: BinaryFile[]; headerHtml?: string; footerHtml?: string; assets?: BinaryFile[]; render?: HtmlRenderOptionsJson; output?: PdfOutputOptionsJson; }): Promise; /** * Convert Office documents to PDF. * Supports a wide range of formats including DOC, DOCX, XLS, XLSX, PPT, PPTX, ODT, and many more. * * @param options - Office to PDF conversion options * @param options.document - The document file to convert (must have supported extension) * @param options.render - Rendering options (landscape, page ranges, etc.) * @param options.output - PDF output options * @returns The rendered PDF file * * @example * ```typescript * const pdf = await api.officeToPdf({ * document: { filename: 'report.docx', data: docxBytes }, * render: { landscape: true } * }); * ``` */ officeToPdf(options: { document: BinaryFile; render?: OfficeRenderOptionsJson; output?: PdfOutputOptionsJson; }): Promise; /** * Transform an image with various operations. * Operations are applied in the order they appear in the operations array. * * @param options - Image transformation options * @param options.input - The input image file * @param options.operations - Ordered list of operations to apply (max 50) * @param options.output - Output format and quality options * @returns The transformed image file * * @example * ```typescript * const resized = await api.transformImage({ * input: { filename: 'photo.jpg', data: imageBytes }, * operations: [ * { resize: { width: 800, height: 600, type: 'RESIZE_TYPE_FIT' } }, * { rotate: { angle: 90 } } * ], * output: { format: 'IMAGE_FORMAT_WEBP', quality: 85 } * }); * ``` */ transformImage(options: { input: BinaryFile; operations?: ImageOperationInput[]; output?: ImageOutputJson; }): Promise; /** * Merge multiple PDF files into a single PDF. * Files are sorted alphanumerically by filename before merging. * * @param options - PDF merge options * @param options.files - PDF files to merge (2-100 files) * @param options.pdfa - PDF/A archival format * @param options.pdfua - PDF/UA accessibility compliance * @param options.flatten - Flatten interactive elements * @param options.userPassword - Password required to open the PDF * @param options.ownerPassword - Password for full access/editing * @returns The merged PDF file * * @example * ```typescript * const merged = await api.mergePdfs({ * files: [ * { filename: '01-intro.pdf', data: pdf1Bytes }, * { filename: '02-content.pdf', data: pdf2Bytes } * ] * }); * ``` */ mergePdfs(options: { files: BinaryFile[]; pdfa?: PdfAFormat; pdfua?: boolean; flatten?: boolean; userPassword?: string; ownerPassword?: string; }): Promise; /** * Split a PDF into multiple parts. * * @param options - PDF split options * @param options.file - The PDF file to split * @param options.mode - Split mode: 'intervals' or 'pages' * @param options.span - For intervals: positive integer (e.g., "1", "2"). For pages: page ranges (e.g., "1-3,5,7-10") * @param options.unify - Merge split parts into a single file * @param options.pdfa - PDF/A archival format * @param options.pdfua - PDF/UA accessibility compliance * @param options.flatten - Flatten interactive elements * @param options.userPassword - Password required to open the PDFs * @param options.ownerPassword - Password for full access/editing * @returns Array of split PDF files * * @example * ```typescript * // Split every 2 pages * const parts = await api.splitPdf({ * file: { filename: 'document.pdf', data: pdfBytes }, * mode: 'intervals', * span: '2' * }); * * // Extract specific pages * const extracted = await api.splitPdf({ * file: { filename: 'document.pdf', data: pdfBytes }, * mode: 'pages', * span: '1-3,5,10-12' * }); * ``` */ splitPdf(options: { file: BinaryFile; mode: 'intervals' | 'pages'; span: string; unify?: boolean; pdfa?: PdfAFormat; pdfua?: boolean; flatten?: boolean; userPassword?: string; ownerPassword?: string; }): Promise; /** * Encrypt a PDF with password protection. * * @param options - PDF encryption options * @param options.file - The PDF file to encrypt * @param options.userPassword - Password required to open the PDF (required) * @param options.ownerPassword - Password for full access/editing permissions * @returns The encrypted PDF file * * @example * ```typescript * const encrypted = await api.encryptPdf({ * file: { filename: 'sensitive.pdf', data: pdfBytes }, * userPassword: 'viewerpass', * ownerPassword: 'adminpass' * }); * ``` */ encryptPdf(options: { file: BinaryFile; userPassword: string; ownerPassword?: string; }): Promise; /** * Convert a PDF to PDF/A archival format or PDF/UA accessible format. * * @param options - PDF conversion options * @param options.file - The PDF file to convert * @param options.pdfa - PDF/A archival format (1B, 2B, or 3B) * @param options.pdfua - PDF/UA accessibility compliance * @returns The converted PDF file * * @example * ```typescript * const archival = await api.convertPdf({ * file: { filename: 'document.pdf', data: pdfBytes }, * pdfa: PdfAFormat._2B * }); * ``` */ convertPdf(options: { file: BinaryFile; pdfa?: PdfAFormat; pdfua?: boolean; }): Promise; /** * Flatten a PDF, converting interactive elements (forms, annotations) to static content. * * @param options - PDF flatten options * @param options.file - The PDF file to flatten * @returns The flattened PDF file * * @example * ```typescript * const flattened = await api.flattenPdf({ * file: { filename: 'form.pdf', data: pdfBytes } * }); * ``` */ flattenPdf(options: { file: BinaryFile; }): Promise; } /** * Represents the result of a batch read operation from the store. * Keys that were not found in the store are not present in the result. */ export declare class BatchReadResult { readonly result: Record; /** * Constructs a BatchReadResult from the store's batch read response. * @param result - Map of keys to their retrieved values (keys not found are excluded). * @internal */ constructor(result: Record); /** * Retrieves the result of a specific read operation by its key as JSON. * * @param key - The key to retrieve from the batch result. * @returns The value and metadata, or undefined if the key was not found in the store. * - value: The parsed JSON value * - ttl: Remaining TTL in seconds (0 = no expiration) * - lastModified: When the value was last modified * - etag: Entity tag for concurrency control * * @example * ```typescript * const result = await store.readBatch(['user:1', 'user:2', 'user:3']); * const user1 = result.get('user:1'); * if (user1) { * console.log(user1.value.name, 'TTL:', user1.ttl); * } * ``` */ get(key: string): { value: T; ttl: number; lastModified: Date; etag: string; } | undefined; /** * Retrieves the result of a specific read operation by its key as raw binary. * * @param key - The key to retrieve from the batch result. * @returns The raw binary value and metadata, or undefined if the key was not found in the store. * - value: The raw binary data as Uint8Array * - ttl: Remaining TTL in seconds (0 = no expiration) * - lastModified: When the value was last modified * - etag: Entity tag for concurrency control * * @example * ```typescript * const result = await store.readBatch(['asset:1', 'asset:2']); * const asset1 = result.getBinary('asset:1'); * if (asset1) { * console.log('Size:', asset1.value.length, 'bytes'); * } * ``` */ getBinary(key: string): { ttl: number; value: Uint8Array; lastModified: Date; etag: string; } | undefined; } /** * Utility class for constructing batch write operations for the KV store. * Provides a fluent interface for building write batches. * * Note: Batch operations do not support preconditions. Use Store.insert() and Store.delete() * methods directly for conditional writes. */ export declare class WriteBatchBuilder { private ops; /** * Adds an insert operation to the batch for JSON data or raw binary data. * * @param key - The key to insert (max 4096 characters). * @param value - The value to store (will be JSON-serialized unless it's Uint8Array). * @param ttl - Optional time-to-live in seconds (0 = no expiration). * @returns The current instance of the builder for chaining. * * @example * ```typescript * const batch = new WriteBatchBuilder() * .insert('user:1', { name: 'Alice' }, 3600) * .insert('user:2', { name: 'Bob' }) * .build(); * ``` */ insert(key: string, value: T, ttl?: number): this; /** * Adds a delete operation to the batch. * * @param key - The key to delete (max 4096 characters). * @returns The current instance of the builder for chaining. * * @example * ```typescript * const batch = new WriteBatchBuilder() * .delete('temp:cache:1') * .delete('temp:cache:2') * .build(); * ``` */ delete(key: string): this; /** * Adds a range delete operation to the batch (lexicographic comparison). * * Range delete works like SelectOp for defining the range. Not setting any start or end will * delete the entire store when this batch is executed. * * @param start - The start key of the range. If omitted, deletes from the empty key. * @param end - The end key of the range. If omitted, deletes to the end. * @param startInclusive - Include start (>= vs >). Defaults to `false`. * @param endInclusive - Include end (<= vs <). Defaults to `false`. * @returns The current instance for method chaining. * * @example * ```typescript * // Delete all keys with prefix "user/" * builder.rangeDelete('user/', 'user/~'); * * // Delete logs for a specific month * builder.rangeDelete('logs/2024-01/', 'logs/2024-02/'); * ``` */ rangeDelete(start?: string, end?: string, startInclusive?: boolean, endInclusive?: boolean): this; /** * Finalizes the batch and returns the array of write operations. * * @returns The array of WriteOperation objects ready to be executed. */ build(): WriteOperation[]; } /** * Options for lock operations. */ export interface LockOptions { /** * Maximum number of retries if the lock is not acquired immediately. Defaults to 5. */ maxRetries?: number; /** * Initial delay before retrying in milliseconds. Defaults to 50ms. */ initialDelay?: number; /** * Maximum delay between retries in milliseconds. Defaults to 2000ms. */ maxDelay?: number; } /** * Preconditions for conditional insert operations. * Used for implementing locks and optimistic concurrency control. * * IMPORTANT CONSTRAINTS (from proto validation): * - failIfExists CANNOT be combined with etagEquals, timestampEquals, or timestampRange * - When failIfExists is true, all other fields must be undefined * - etagEquals and timestamp conditions can be used together */ export interface InsertCondition { /** * Fail the insert if the key already exists. * When true, this cannot be combined with any other conditions. * Useful for acquiring locks atomically. */ failIfExists?: boolean; /** * Only insert if the current etag matches this value. * Cannot be used with failIfExists. */ etagEquals?: string; /** * Only insert if last_modified exactly matches this timestamp. * Cannot be used with failIfExists or timestampRange. */ timestampEquals?: Date; /** * Only insert if last_modified falls within this time range. * Cannot be used with failIfExists or timestampEquals. */ timestampRange?: { /** * Start * * @generated from field: google.protobuf.Timestamp start = 1; */ start?: Date; /** * End * * @generated from field: google.protobuf.Timestamp end = 2; */ end?: Date; /** * Include start (>= vs >) * * @generated from field: bool start_inclusive = 3; */ startInclusive: boolean; /** * Include end (<= vs <) * * @generated from field: bool end_inclusive = 4; */ endInclusive: boolean; }; } /** * Preconditions for conditional delete operations. * Used for safe deletion with verification. * * IMPORTANT CONSTRAINTS (from proto validation): * - mustExists CANNOT be combined with etagEquals, timestampEquals, or timestampRange * - When mustExists is true, all other fields must be undefined * - etagEquals and timestamp conditions can be used together */ export interface DeleteCondition { /** * Fail the delete if the key doesn't exist. * When true, this cannot be combined with any other conditions. */ mustExists?: boolean; /** * Only delete if the current etag matches this value. * Cannot be used with mustExists. */ etagEquals?: string; /** * Only delete if last_modified exactly matches this timestamp. * Cannot be used with mustExists or timestampRange. */ timestampEquals?: Date; /** * Only delete if last_modified falls within this time range. * Cannot be used with mustExists or timestampEquals. */ timestampRange?: { /** * Start * * @generated from field: google.protobuf.Timestamp start = 1; */ start?: Date; /** * End * * @generated from field: google.protobuf.Timestamp end = 2; */ end?: Date; /** * Include start (>= vs >) * * @generated from field: bool start_inclusive = 3; */ startInclusive: boolean; /** * Include end (<= vs <) * * @generated from field: bool end_inclusive = 4; */ endInclusive: boolean; }; } /** * Metadata returned from store write operations. */ export interface StoreMetadata { /** * Remaining time-to-live in seconds. * 0 means no expiration (the value will not expire). */ ttl: number; /** * Timestamp when the value was last modified. * All operations in a write batch share the same timestamp. */ lastModified: Date; /** * Entity tag for optimistic concurrency control. * Changes with each modification of the value. */ etag: string; } /** * Internal type for store service clients * @internal */ type StoreServiceClient = Client | Client; /** * Represents a store in a specific namespace, providing key-value storage operations. * Stores can be scoped to different namespaces with different lifetimes: * - NAMESPACE_VERTEX: Lives as long as the plugin in the project (vertex scope) * - NAMESPACE_PLUGIN: Lives as long as the plugin in the project (plugin-wide scope) * - NAMESPACE_VERTEX_INSTANCE: Lives as long as the instance (vertex scope, session storage) * - NAMESPACE_PLUGIN_INSTANCE: Lives as long as the instance (plugin-wide scope, session storage) */ export declare class Store { private service; private namespace; /** * Constructs a Store instance for a specific namespace. * @param service - The gRPC service client (ExecutorService or ConfiguratorService). * @param namespace - The namespace determining the store's scope and lifetime. * @internal */ constructor(service: StoreServiceClient, namespace: NamespaceJson); /** * Inserts or updates a key-value pair in the store with JSON data. * Supports conditional writes for implementing locks and optimistic concurrency control. * * @param key - The key to insert (max 4096 characters). * @param value - The JSON value to store (will be JSON-serialized). * @param ttl - Optional time-to-live in seconds (0 = no expiration). * @param condition - Optional preconditions for the write: * - failIfExists: Fail if key already exists (cannot be combined with other conditions) * - etagEquals: Only write if current etag matches * - timestampEquals: Only write if last_modified exactly matches * - timestampRange: Only write if last_modified falls within range * @returns A promise that resolves with metadata (ttl, lastModified, etag) when the operation completes. * @throws {ConnectError} Code.FailedPrecondition if precondition fails, Code.InvalidArgument for invalid inputs. * * @example * ```typescript * // Simple insert * await store.insert('user:123', { name: 'Alice' }, 3600); * * // Conditional insert - fail if exists (for locks) * await store.insert('lock:resource', { owner: 'process-1' }, 30, { failIfExists: true }); * * // Optimistic concurrency with etag * const data = await store.get('counter'); * await store.insert('counter', data.data + 1, undefined, { etagEquals: data.etag }); * ``` */ insert(key: string, value: T, ttl?: number, condition?: InsertCondition): Promise; /** * Deletes a key-value pair from the store. * Supports conditional deletes for safe removal operations. * * @param key - The key to delete (max 4096 characters). * @param condition - Optional preconditions for the delete: * - mustExists: Fail if key doesn't exist (cannot be combined with other conditions) * - etagEquals: Only delete if current etag matches * - timestampEquals: Only delete if last_modified exactly matches * - timestampRange: Only delete if last_modified falls within range * @returns A promise that resolves when the operation completes. * @throws {ConnectError} Code.FailedPrecondition if precondition fails. * * @example * ```typescript * // Simple delete * await store.delete('temp:data'); * * // Conditional delete - only if exists * await store.delete('lock:resource', { mustExists: true }); * * // Delete with etag verification * const data = await store.get('config'); * await store.delete('config', { etagEquals: data.etag }); * ``` */ delete(key: string, condition?: DeleteCondition): Promise; /** * Deletes all items within a specified key range from the store (lexicographic comparison). * * Range delete works like SelectOp for defining the range. Not setting any start or end will * delete the entire store. * * Note: Range delete operations do not support preconditions. For conditional deletes, * use the {@link delete} method. * * @param start - The start key of the range. If omitted, deletes from the empty key. * @param end - The end key of the range. If omitted, deletes to the end. * @param startInclusive - Include start (>= vs >). Defaults to `false`. * @param endInclusive - Include end (<= vs <). Defaults to `false`. * @returns A promise that resolves when the range delete operation completes. * * @example * ```typescript * // Delete all keys with prefix "user/" * await store.rangeDelete('user/', 'user/~'); * * // Delete logs for a specific month * await store.rangeDelete('logs/2024-01/', 'logs/2024-02/'); * * // Delete all items in the store * await store.rangeDelete(); * ``` */ rangeDelete(start?: string, end?: string, startInclusive?: boolean, endInclusive?: boolean): Promise; /** * Retrieves a value by its key from the store as JSON. * * @param key - The key to retrieve (max 4096 characters). * @returns A promise that resolves with the retrieved JSON value and metadata, or undefined if key not found. * - data: The parsed JSON value * - ttl: Remaining TTL in seconds (0 = no expiration) * - etag: The ETag for optimistic concurrency control * - lastModified: Timestamp of last modification * * @example * ```typescript * const user = await store.get('user:123'); * if (user) { * console.log(user.data.name, 'expires in', user.ttl, 'seconds'); * } * ``` */ get(key: string): Promise<{ data: T; ttl: number; etag: string; lastModified: Date; } | undefined>; /** * Retrieves a value by its key from the store as raw binary. * * @param key - The key to retrieve (max 4096 characters). * @returns A promise that resolves with the retrieved binary value and metadata, or undefined if key not found. * - data: The raw binary value as Uint8Array * - ttl: Remaining TTL in seconds (0 = no expiration) * - etag: The ETag for optimistic concurrency control * - lastModified: Timestamp of last modification * * @example * ```typescript * const asset = await store.getBinary('asset:image.png'); * if (asset) { * console.log('Image size:', asset.data.length, 'bytes'); * } * ``` */ getBinary(key: string): Promise<{ data: Uint8Array; ttl: number; etag: string; lastModified: Date; } | undefined>; /** * Performs a range query on keys using lexicographic comparison, returning parsed JSON data. * * Range queries allow scanning keys within a specific range. For example: * - "user/" to "user/~" - all keys starting with "user/" * - "logs/2024-01/" to "logs/2024-02/" - all logs from January 2024 * * Not setting start or end will scan the entire store. * Results are always returned in ascending order by key. * * @param select - The select operation specifying: * - start: Optional start key (max 4096 chars). Omit to start from empty key * - end: Optional end key (max 4096 chars) * - startInclusive: Whether to include start key (>= vs >) * - endInclusive: Whether to include end key (<= vs <) * - limit: Max results (1-1000) * - pageToken: Optional token to continue from previous query * @returns A promise that resolves to an object containing: * - items: Array of values with metadata (value as JSON type T, TTL, etag, lastModified) * - nextToken: Optional pagination token to continue the query * * @example * ```typescript * // Get all user keys * const result = await store.selectRange({ * start: 'user/', * end: 'user/~', * startInclusive: true, * endInclusive: false, * limit: 100 * }); * * // Continue pagination * if (result.nextToken) { * const next = await store.selectRange({ * start: 'user/', * end: 'user/~', * startInclusive: true, * endInclusive: false, * limit: 100, * pageToken: result.nextToken * }); * } * ``` */ selectRange(select: SelectOpJson): Promise<{ nextToken?: string; items: { key: string; value: T; ttl: number; etag: string; lastModified: Date; }[]; }>; /** * Performs a range query on keys using lexicographic comparison, returning raw binary data. * * Range queries allow scanning keys within a specific range. For example: * - "user/" to "user/~" - all keys starting with "user/" * - "logs/2024-01/" to "logs/2024-02/" - all logs from January 2024 * * Not setting start or end will scan the entire store. * Results are always returned in ascending order by key. * * @param select - The select operation specifying: * - start: Optional start key (max 4096 chars). Omit to start from empty key * - end: Optional end key (max 4096 chars) * - startInclusive: Whether to include start key (>= vs >) * - endInclusive: Whether to include end key (<= vs <) * - limit: Max results (1-1000) * - pageToken: Optional token to continue from previous query * @returns A promise that resolves to an object containing: * - items: Array of values with metadata (value as Uint8Array, TTL, etag, lastModified) * - nextToken: Optional pagination token to continue the query * * @example * ```typescript * // Get all binary assets * const result = await store.selectRangeBinary({ * start: 'assets/', * end: 'assets/~', * startInclusive: true, * endInclusive: false, * limit: 50 * }); * * // Continue pagination * if (result.nextToken) { * const next = await store.selectRangeBinary({ * start: 'assets/', * end: 'assets/~', * startInclusive: true, * endInclusive: false, * limit: 50, * pageToken: result.nextToken * }); * } * ``` */ selectRangeBinary(select: SelectOpJson): Promise<{ nextToken?: string; items: { value: Uint8Array; ttl: number; etag: string; lastModified: Date; }[]; }>; /** * Executes a batch of write operations on the store. * All operations are atomic - either all succeed or all fail. * All operations in a batch share the same timestamp. * Interfering operations on the same key have undefined order. * * Note: Batch operations do not support preconditions. Use the single insert/delete * methods for conditional writes. * * @param ops - The write operations to execute (1-500 operations). Use WriteBatchBuilder to construct. * @returns A promise that resolves with metadata for each inserted key (deletes don't return metadata). * @throws {ConnectError} Code.InvalidArgument if invalid operations or limits exceeded. * * @example * ```typescript * const ops = new WriteBatchBuilder() * .insert('user:1', { name: 'Alice' }, 3600) * .insert('user:2', { name: 'Bob' }, 3600) * .delete('temp:old') * .build(); * * const metadata = await store.writeBatch(ops); * console.log('Insert metadata:', metadata); * ``` */ writeBatch(ops: WriteOperation[]): Promise<{ [key: string]: StoreMetadata; }>; /** * Executes a batch of read operations on the store. * Keys not found are ignored (not present in the result). * * @param keys - The keys to read (1-10000 keys, each max 4096 characters). * @returns A promise that resolves with a BatchReadResult containing found items. * * @example * ```typescript * const result = await store.readBatch(['user:1', 'user:2', 'user:3']); * const user1 = result.get('user:1'); * if (user1) { * console.log(user1.value.name); * } * ``` */ readBatch(keys: string[]): Promise; /** * Attempts to acquire a lock for a specified duration. * Uses an atomic insert operation with failIfExists precondition that fails if the key already exists. * * @param locker - The unique identifier for the lock (max 4096 chars). * @param ttl - Time-to-live in seconds (defaults to 5 seconds if not specified). * @returns A promise that resolves with true if the lock was acquired, false if already held. * * @example * ```typescript * // Try to acquire lock with default 5 second TTL * const acquired = await store.acquire('resource_lock'); * if (acquired) { * // Lock acquired, perform work * } * * // Acquire lock with custom TTL * const acquired2 = await store.acquire('long_operation', 30); * ``` */ acquire(locker: string, ttl?: number): Promise; /** * Releases a previously acquired lock by deleting the lock key. * * @param locker - The unique identifier for the lock (max 4096 chars). * @returns A promise that resolves when the lock is released. * * @example * ```typescript * await store.release('resource_lock'); * ``` */ release(locker: string): Promise; /** * Acquires a lock and executes a critical section of code with exponential backoff retry logic. * Automatically releases the lock after the section completes or fails. * * The retry mechanism uses exponential backoff: * - Delay = min(initialDelay * 2^attempt, maxDelay) * - Default: 50ms, 100ms, 200ms, 400ms, 800ms (capped at maxDelay) * * @template T - The return type of the critical section function. * @param key - The unique identifier for the lock (max 4096 chars). * @param section - The critical section to execute once the lock is acquired. * @param options - Optional lock options: * - maxRetries: Maximum retry attempts (default: 5) * - initialDelay: Initial delay in ms before first retry (default: 50ms) * - maxDelay: Maximum delay in ms between retries (default: 2000ms) * @returns A promise that resolves with the result of the critical section. * @throws {Error} If the lock cannot be acquired after maxRetries attempts. * * @example * ```typescript * const result = await store.lock('counter_lock', async () => { * const counter = await store.get('counter'); * await store.insert('counter', (counter?.data ?? 0) + 1); * return counter?.data ?? 0; * }); * * // With custom options * const result2 = await store.lock('resource', async () => { * // critical work * }, { maxRetries: 10, initialDelay: 100, maxDelay: 5000 }); * ``` */ lock(key: string, section: () => Promise, options?: LockOptions): Promise; } /** * Binary file with filename and data. * Used for both input and output in FileForge operations. */ export interface BinaryFile { /** The filename. Used for format detection on input. */ filename: string; /** The binary file data. */ data: Uint8Array; } /** * Discriminative union type for image transformation operations. * Each operation variant has exactly one operation field set. */ export type ImageOperationInput = { resize: ImageResizeJson; } | { crop: ImageCropJson; } | { rotate: ImageRotateJson; } | { flip: ImageFlipJson; } | { pad: ImagePadJson; } | { trim: ImageTrimJson; } | { proportion: ImageProportionJson; } | { focal: ImageFocalJson; } | { adjust: ImageAdjustJson; } | { hue: ImageHueJson; } | { rgb: ImageRgbJson; } | { blur: ImageBlurJson; } | { sharpen: ImageSharpenJson; } | { roundCorner: ImageRoundCornerJson; } | { watermark: ImageWatermarkJson; } | { text: ImageTextJson; } | { maxFrames: ImageMaxFramesJson; } | { page: ImagePageJson; } | { dpi: ImageDpiJson; }; /** * Provides access to the least privileged Executor API, without session capabilities. * This API allows plugins to interact with vertex configuration and local storage. */ export declare class ExecutorApi extends ApiBase { protected readonly executor: Client; /** * Initializes an instance of ExecutorApi. * * @param env - The executor environment configuration. * @param pluginToken - The plugin token for authorization. */ constructor(env: ExecutorEnvironment, pluginToken: string); /** * Get vertex configuration with JSON-parsed config field. * Optionally specify which fields to include in the response. * * @template T - Type of the config object (defaults to any) * @param fields - Optional field names to include. If not specified, returns all fields. * @returns Object containing the requested fields with config as parsed JSON (type T). * * @example * ```typescript * // Get all fields (all fields are guaranteed to be present) * const {config, metadata, services} = await api.getConfig(); * * // Get only config with type - result type is { config: Settings } * const {config} = await api.getConfig('config'); * * // Get config and metadata - result type is { config: Settings; metadata: VertexMetadataJson } * const {config, metadata} = await api.getConfig('config', 'metadata'); * ``` */ getConfig(): Promise<{ config: T; metadata: VertexMetadataJson; configuredServices: { [key: string]: boolean; }; }>; getConfig(...fields: K[]): Promise>; /** * Get vertex configuration with binary config field (Uint8Array). * Optionally specify which fields to include in the response. * * @param fields - Optional field names to include. If not specified, returns all fields. * @returns Object containing the requested fields with config as raw Uint8Array. * * @example * ```typescript * // Get all fields with binary config (all guaranteed present) * const {config, metadata, services} = await api.getConfigBinary(); * * // Get only binary config - result type is { config: Uint8Array } * const {config} = await api.getConfigBinary('config'); * ``` */ getConfigBinary(): Promise<{ config: Uint8Array; metadata: VertexMetadataJson; configuredServices: { [key: string]: boolean; }; }>; getConfigBinary(...fields: K[]): Promise>; /** * Provides access to a local store instance, scoped by namespace. * * Namespace lifetimes: * - 'vertex' (NAMESPACE_VERTEX): Shared across sessions of this graph vertex, bounded by the automation lifetime * - 'plugin' (NAMESPACE_PLUGIN): Shared across vertices and sessions of this plugin, bounded by the automation lifetime * * Access scopes: * - NAMESPACE_VERTEX: runtimeapi/executor.store.vertex * - NAMESPACE_PLUGIN: runtimeapi/executor.store.plugin * * @param namespace - The namespace for the store, either 'vertex' or 'plugin'. * @returns An instance of Store configured for the specified namespace. */ getLocalStore(namespace: 'vertex' | 'plugin'): Store; /** * Retrieves a session-scoped API with the provided authorization header. * Session APIs have additional capabilities like sending signals and managing exchanges. * Their first session operation verifies the caller unless this API already verified it. * Configuration and persistent stores continue to use the plugin token. * * @param authHeader - The authorization header to use for the session API (e.g., 'Bearer '). * @returns An instance of SessionExecutorApi configured with the provided auth header. */ getSessionApi(authHeader: string): SessionExecutorApi; } /** * Provides an API with session storage capabilities, specifically for use when a session is stopping. * This API allows access to session-scoped stores that persist for the lifetime of the instance. */ export declare class StopExecutorApi extends ExecutorApi { /** * The session authorization header for session-based operations. */ protected readonly sessionAuthHeader: string; protected readonly sessionExecutor: Client; /** * Initializes an instance of StopExecutorApi. * * @param env - The executor environment configuration. * @param pluginToken - The plugin token for authorization. * @param sessionAuthHeader - The authorization header for session-based operations. */ constructor(env: ExecutorEnvironment, pluginToken: string, sessionAuthHeader: string); /** * Retrieves the session authorization header used for this API instance. * This header contains the session access token and can be used to create * additional session-scoped API instances or for custom authorization needs. * * @returns The session authorization header (format: 'Bearer '). * * @example * ```typescript * const authHeader = api.getAuthHeader(); * // Use for creating another session API or custom requests * ``` */ getAuthHeader(): string; /** * Retrieves a session-specific store instance based on the provided namespace. * Session stores persist for the lifetime of the instance (the running session). * * Namespace lifetimes: * - 'vertex' (NAMESPACE_VERTEX_INSTANCE): Vertex-scoped, lives as long as the instance * - 'plugin' (NAMESPACE_PLUGIN_INSTANCE): Plugin-wide scope, lives as long as the instance * * Access scopes: * - NAMESPACE_VERTEX_INSTANCE: runtimeapi/executor.store.vertex.instance, runtimeapi/executor.store.vertex.instance:read * - NAMESPACE_PLUGIN_INSTANCE: runtimeapi/executor.store.plugin.instance, runtimeapi/executor.store.plugin.instance:read * * @param namespace - The namespace for the store, either 'vertex' or 'plugin'. * @returns An instance of Store configured for the session's namespace. */ getSessionStore(namespace: 'vertex' | 'plugin'): Store; } /** * Options for listing bound receiver signals. */ export interface ListSignalsOptions { /** * Number of signals per page (max 500, defaults to 50 if not specified). */ pageSize?: number; /** * Whether to order signals in descending order. */ orderDescending?: boolean; /** * Cursor for pagination (max 500 chars). * Used internally by continueListSignals - typically you don't set this directly. * @internal */ cursor?: string; } /** * Provides access to the Privileged Executor API, allowing session-based operations. * This API enables sending signals, managing exchanges, and accessing receiver signals. */ export declare class SessionExecutorApi extends StopExecutorApi { /** * Initializes an instance of SessionExecutorApi. * * @param env - The executor environment configuration. * @param pluginToken - The plugin token for authorization. * @param sessionAuthHeader - The authorization header for session access. */ constructor(env: ExecutorEnvironment, pluginToken: string, sessionAuthHeader: string); /** * Lists signals bound to the receiver that activated this vertex, returning parsed JSON data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * IMPORTANT: The response payload is limited to a maximum of 16MB. * If the total size of all signals would exceed this limit, the response * will be truncated and a cursor will be provided to continue fetching * the remaining signals in subsequent requests. * * @param options - Optional listing options: * - pageSize: Number of signals per page (max 500, defaults to 50) * - orderDescending: Whether to order signals in descending order * @returns A promise that resolves to the list of signals, receiver name, and a cursor for pagination. * * @example * ```typescript * const result = await api.listSignals({ pageSize: 10 }); * result.signals // Record * ``` */ listSignals(options?: ListSignalsOptions): Promise<{ signals: Record; receiver: string; cursor?: string; }>; /** * Lists signals bound to the receiver that activated this vertex, returning raw binary data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * IMPORTANT: The response payload is limited to a maximum of 16MB. * If the total size of all signals would exceed this limit, the response * will be truncated and a cursor will be provided to continue fetching * the remaining signals in subsequent requests. * * @param options - Optional listing options: * - pageSize: Number of signals per page (max 500, defaults to 50) * - orderDescending: Whether to order signals in descending order * @returns A promise that resolves to the list of binary signals, receiver name, and a cursor for pagination. * * @example * ```typescript * const result = await api.listSignalsBinary({ pageSize: 10 }); * result.signals // Record * ``` */ listSignalsBinary(options?: ListSignalsOptions): Promise<{ signals: Record; receiver: string; cursor?: string; }>; /** * Continues listing signals bound to the receiver that activated this vertex from a given cursor, returning parsed JSON data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @param cursor - The cursor to continue from. * @returns A promise that resolves to the next set of signals, receiver name, and a new cursor for further pagination. * * @example * ```typescript * const result = await api.continueListSignals(cursor); * result.signals // Record * ``` */ continueListSignals(cursor: string): Promise<{ signals: Record; receiver: string; cursor?: string; }>; /** * Continues listing signals bound to the receiver that activated this vertex from a given cursor, returning raw binary data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @param cursor - The cursor to continue from. * @returns A promise that resolves to the next set of binary signals, receiver name, and a new cursor for further pagination. * * @example * ```typescript * const result = await api.continueListSignalsBinary(cursor); * result.signals // Record> * ``` */ continueListSignalsBinary(cursor: string): Promise<{ signals: Record; receiver: string; cursor?: string; }>; /** * Retrieves a signal bound to the receiver that activated this vertex, returning parsed JSON data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @param name - The name of the signal (1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @returns A promise that resolves to the signal data, or undefined if not set. * * @example * ```typescript * const user = await api.getSignal<{name: string}>('user'); // {name: string} | undefined * ``` */ getSignal(name: string): Promise; /** * Retrieves a signal bound to the receiver that activated this vertex, returning raw binary data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @param name - The name of the signal (1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @returns A promise that resolves to the signal data as Uint8Array, or undefined if not set. * * @example * ```typescript * const binary = await api.getSignalBinary('avatar'); // SignalData | undefined * ``` */ getSignalBinary(name: string): Promise; /** * Retrieves multiple signals bound to the receiver that activated this vertex in a single batch operation with full type safety. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @template T - Record type mapping signal names to their expected types. * @param names - Names of the signals to retrieve (1-500 unique names, each 1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @returns A promise that resolves with an object mapping signal names to their typed values. * @throws {ConnectError} Code.InvalidArgument if names array is empty or exceeds 500 items. * * @example * ```typescript * const signals = await api.getSignals<{ * 'user': { name: string; email: string }; * 'settings': { theme: string; notifications: boolean }; * 'count': number; * }>('user', 'settings', 'count'); * * // Fully typed! * signals['user']; // { name: string; email: string } * signals['settings']; // { theme: string; notifications: boolean } * signals['count']; // number * ``` */ getSignals>(...names: Array): Promise; /** * Retrieves multiple signals bound to the receiver that activated this vertex in a single batch operation, returning raw binary data. * * Signal retrieval is always scoped to the specific receiver that triggered * the vertex execution, providing access to the contextual data that initiated * this workflow. * * @param names - The names of the signals to retrieve (1-500 unique names, each 1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @returns A promise that resolves to a record mapping signal names to their binary data. * @throws {ConnectError} Code.InvalidArgument if names array is empty or exceeds 500 items. * * @example * ```typescript * const binaries = await api.getSignalsBinary('avatar', 'thumbnail', 'document'); * binaries['avatar']; // SignalData * binaries['thumbnail']; // SignalData * ``` */ getSignalsBinary(...names: string[]): Promise>; /** * Sends data on the specified transmitter with the given signals. * For stream transmitters, this sends data but does not advance the cursor position in the graph. * * Signal values can be either JSON data or raw binary data (Uint8Array). The method * automatically detects the type and encodes accordingly. * * @param transmitter - The identifier of the transmitter (max 100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$, optional). * @param signals - Signals to transmit (0-50 signals, each signal name 1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * Values can be JSON or Uint8Array. * @returns A promise that resolves when the send operation is completed. * @throws {ConnectError} Code.InvalidArgument if transmitter or signal constraints are violated. * * @example * ```typescript * // Send JSON signals * await api.send('output', { * user: { name: 'John', age: 30 }, * status: 'success' * }); * * // Send binary signals * await api.send('output', { * avatar: new Uint8Array([...]), * document: new Uint8Array([...]) * }); * * // Mix JSON and binary * await api.send('output', { * user: { name: 'John' }, * avatar: new Uint8Array([...]) * }); * ``` */ send(transmitter?: string, signals?: { [name: string]: any | { data: Uint8Array; mimeType: string; filename?: string; }; }): Promise; /** * Dispatches an exchange operation with a specific receiver and set of signals. * Exchanges are asynchronous operations that can return results through transmitters. * * Signal values can be either JSON data or raw binary data (Uint8Array). The method * automatically detects the type and encodes accordingly. * * @param name - The name of the exchange to dispatch (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @param receiver - The receiver to dispatch the exchange to (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * @param signals - Signals to send with the exchange (0-50 signals, each signal name 1-512 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * Values can be JSON or Uint8Array. * @returns A promise that resolves to the exchange operation details. * @throws {ConnectError} Code.InvalidArgument if name, receiver, or signal constraints are violated. * * @example * ```typescript * // Dispatch exchange with JSON signals * const op = await api.dispatchExchange('process_user', 'user_handler', { * user: { name: 'John', age: 30 }, * action: 'create' * }); * * // Dispatch exchange with binary signals * const op = await api.dispatchExchange('process_image', 'image_handler', { * image: new Uint8Array([...]), * metadata: { width: 800, height: 600 } * }); * ``` */ dispatchExchange(name: string, receiver: string, signals?: { [name: string]: any | { data: Uint8Array; mimeType: string; filename?: string; }; }): Promise; /** * Retrieves an exchange operation by its ID to check its status and results. * * @param id - The id returned by the dispatch. * @returns A promise that resolves to the exchange operation details. * @throws {ConnectError} Code.NotFound if the exchange operation doesn't exist. * */ getExchange(id: string): Promise; /** * Cancels an ongoing exchange operation by its ID. * If the exchange is already completed or cancelled, this operation is idempotent. * * @param id - The id returned by the dispatch. * @returns A promise that resolves when the exchange is successfully canceled. * */ cancelExchange(id: string): Promise; } /** * Options for posting vertex configuration. * * Config semantics: * - Set config to a value (object or Uint8Array) to update it * - Set config to empty Uint8Array (new Uint8Array()) to clear it * - Omit config (undefined) to keep existing config unchanged * * Metadata semantics: * - Set metadata to update it * - Omit metadata (undefined) to keep existing metadata unchanged * - Metadata cannot be cleared * * At least one of config or metadata MUST be provided. */ export interface PostConfigOptions { /** * Set this to true if you would like to override any bindings that already exist. * This should be used if the plugin is handling signal bindings itself. * When true, the plugin takes full control of receiver/transmitter bindings. */ overrideBindings?: boolean; /** * The configuration to set. Can be either a typed object (which will be JSON-serialized) * or raw Uint8Array. * - Set to value: Updates the config * - Set to empty Uint8Array: Clears the config * - Omit (undefined): Keeps existing config unchanged */ config?: Config | Uint8Array; /** * Metadata to update with the configuration. * - Set to value: Updates the metadata * - Omit (undefined): Keeps existing metadata unchanged * - Cannot be cleared (must always have a value if present) */ metadata?: VertexMetadataJson; } /** * API for interacting with the Configurator service. * This API allows plugins to manage vertex configuration and access persistent storage. */ export declare class ConfiguratorApi extends ApiBase { private readonly configurator; /** * Initializes an instance of ConfiguratorApi. * * @param env - The environment configuration for the Configurator. * @param pluginToken - The trusted runtime route token for plugin services and caller verification. * @param callerAuthHeader - Canonical bearer header for configuration and stores. Without it, * only plugin services, caller verification, and assets are available. */ constructor(env: ConfiguratorEnvironment, pluginToken: string, callerAuthHeader?: string); /** * Get vertex configuration with JSON-parsed config field. * Optionally specify which fields to include in the response. * * @template T - Type of the config object (defaults to any) * @param fields - Optional field names to include. If not specified, returns all fields. * @returns Object containing the requested fields with config as parsed JSON (type T). */ getConfig(): Promise<{ config: T; metadata: VertexMetadataJson; configuredServices: { [key: string]: boolean; }; }>; getConfig(...fields: K[]): Promise>; /** * Get vertex configuration with binary config field (Uint8Array). * Optionally specify which fields to include in the response. * * @param fields - Optional field names to include. If not specified, returns all fields. * @returns Object containing the requested fields with config as raw Uint8Array. */ getConfigBinary(): Promise<{ config: Uint8Array; metadata: VertexMetadataJson; configuredServices: { [key: string]: boolean; }; }>; getConfigBinary(...fields: K[]): Promise>; /** * Updates the vertex configuration and/or metadata. * At least one of config or metadata must be provided. * * Config handling: * - Set to a value (object or Uint8Array) to update the config * - Set to empty bytes to clear the config * - Omit (undefined) to keep existing config unchanged * * Metadata handling: * - Set to update the metadata * - Omit (undefined) to keep existing metadata unchanged * - Cannot be cleared * * @param opts - Configuration options: * - config: The configuration to set (will be JSON-serialized unless Uint8Array) * - metadata: Optional metadata to update * - overrideBindings: Set to true to override existing signal bindings (use when plugin handles bindings) * @returns A promise that resolves to the updated vertex metadata (useful for checking error codes after setting bindings). * @throws {ConnectError} Code.InvalidArgument if neither config nor metadata is provided. * * @example * ```typescript * // Update config only * await api.postConfig({ config: { apiKey: 'new-key' } }); * * // Update metadata only * await api.postConfig({ metadata: { label: 'New Label' } }); * * // Update both with binding override * await api.postConfig({ * config: { enabled: true }, * metadata: { description: 'Updated' }, * overrideBindings: true * }); * ``` */ postConfig(opts: PostConfigOptions): Promise; /** * Lists all available incoming signals on a specific receiver. * This endpoint enables the configurator to get information about incoming signals * from vertices that transmit to this vertex's receivers. * * If you have multiple receivers, call this endpoint multiple times (once per receiver). * * @param receiver - The receiver to check for signals (1-100 chars, pattern: ^[_$a-zA-Z][_$a-zA-Z0-9]*$). * If not set, the first connected receiver is used. * @param formats - Optional signal formats to filter by. Only returns signals that match at least one schema in the array. * This allows filtering incoming signals to only those that conform to specific JTD schemas. * @param fieldMask - Optional field mask to apply to the returned schema. * Example: Set to "vertices" to omit vertex logos and reduce response size. * @returns A promise that resolves to information about incoming vertices, their transmitters, and available signals. * - vertices: Array of incoming vertices with their transmitters and signal definitions * - vertexLogos: Map of vertex logo IDs to logo data (base64 or data URI) * - receiver: The receiver name the signals are fetched on * * @example * ```typescript * // Get all incoming signals on default receiver * const signals = await api.listIncomingSignals(); * * // Get signals from specific receiver, filtered by format * const filtered = await api.listIncomingSignals('data_receiver', [mySignalFormat]); * * // Get signals without logos (smaller response) * const minimal = await api.listIncomingSignals('input', undefined, 'vertices'); * ``` */ listIncomingSignals(receiver?: string, formats?: SignalFormatJson[], fieldMask?: string): Promise; /** * Provides access to a local store scoped by the specified namespace. * Local stores persist for the lifetime of the plugin in the project. * * @param namespace - The namespace for the store, either 'vertex' or 'plugin'. * @returns An instance of Store configured for the specified namespace. */ getLocalStore(namespace: 'vertex' | 'plugin'): Store; } /** * Maps HTTP status codes to ConnectError instances. * * @param status - The HTTP status code. * @returns A ConnectError instance with the appropriate code and message. */ export declare function mapHttpError(status: number): ConnectError; /** * Maps a ConnectError to the corresponding HTTP status code. * * @param error - The ConnectError instance. * @returns The corresponding HTTP status code. */ export declare function mapConnectErrorToHttpStatus(error: ConnectError): number; //# sourceMappingURL=index.d.ts.map