iii-sdk 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,707 @@
1
+ import { Readable, Writable } from "node:stream";
2
+
3
+ //#region src/iii-types.d.ts
4
+ declare enum MessageType {
5
+ RegisterFunction = "registerfunction",
6
+ UnregisterFunction = "unregisterfunction",
7
+ InvokeFunction = "invokefunction",
8
+ InvocationResult = "invocationresult",
9
+ RegisterTriggerType = "registertriggertype",
10
+ RegisterTrigger = "registertrigger",
11
+ UnregisterTrigger = "unregistertrigger",
12
+ UnregisterTriggerType = "unregistertriggertype",
13
+ TriggerRegistrationResult = "triggerregistrationresult",
14
+ WorkerRegistered = "workerregistered"
15
+ }
16
+ type RegisterTriggerTypeMessage = {
17
+ message_type: MessageType.RegisterTriggerType;
18
+ id: string;
19
+ description: string;
20
+ };
21
+ type RegisterTriggerMessage = {
22
+ message_type: MessageType.RegisterTrigger;
23
+ id: string;
24
+ type: string;
25
+ function_id: string;
26
+ config: unknown;
27
+ metadata?: Record<string, unknown>;
28
+ };
29
+ /**
30
+ * Authentication configuration for HTTP-invoked functions.
31
+ *
32
+ * - `hmac` -- HMAC signature verification using a shared secret.
33
+ * - `bearer` -- Bearer token authentication.
34
+ * - `api_key` -- API key sent via a custom header.
35
+ */
36
+ type HttpAuthConfig = {
37
+ type: 'hmac';
38
+ secret_key: string;
39
+ } | {
40
+ type: 'bearer';
41
+ token_key: string;
42
+ } | {
43
+ type: 'api_key';
44
+ header: string;
45
+ value_key: string;
46
+ };
47
+ /**
48
+ * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare
49
+ * Workers, etc.) instead of a local handler.
50
+ */
51
+ type HttpInvocationConfig = {
52
+ /** URL to invoke. */url: string; /** HTTP method. Defaults to `POST`. */
53
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Timeout in milliseconds. */
54
+ timeout_ms?: number; /** Custom headers to send with the request. */
55
+ headers?: Record<string, string>; /** Authentication configuration. */
56
+ auth?: HttpAuthConfig;
57
+ };
58
+ type RegisterFunctionFormat = {
59
+ /**
60
+ * The name of the parameter
61
+ */
62
+ name?: string;
63
+ /**
64
+ * The description of the parameter
65
+ */
66
+ description?: string;
67
+ /**
68
+ * The type of the parameter
69
+ */
70
+ type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer';
71
+ /**
72
+ * The body of the parameter (for objects)
73
+ */
74
+ properties?: Record<string, unknown>;
75
+ /**
76
+ * The items of the parameter (for arrays)
77
+ */
78
+ items?: unknown;
79
+ /**
80
+ * Whether the parameter is required
81
+ */
82
+ required?: string[];
83
+ [key: string]: unknown;
84
+ };
85
+ type RegisterFunctionMessage = {
86
+ message_type: MessageType.RegisterFunction;
87
+ /**
88
+ * The path of the function (use :: for namespacing, e.g. external::my_lambda)
89
+ */
90
+ id: string;
91
+ /**
92
+ * The description of the function
93
+ */
94
+ description?: string;
95
+ /**
96
+ * The request format of the function
97
+ */
98
+ request_format?: RegisterFunctionFormat;
99
+ /**
100
+ * The response format of the function
101
+ */
102
+ response_format?: RegisterFunctionFormat;
103
+ metadata?: Record<string, unknown>;
104
+ /**
105
+ * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)
106
+ */
107
+ invocation?: HttpInvocationConfig;
108
+ };
109
+ /**
110
+ * Routing action for {@link TriggerRequest}. Determines how the engine
111
+ * handles the invocation.
112
+ *
113
+ * - `enqueue` -- Routes through a named queue for async processing.
114
+ * - `void` -- Fire-and-forget, no response.
115
+ */
116
+ type TriggerAction = {
117
+ type: 'enqueue';
118
+ queue: string;
119
+ } | {
120
+ type: 'void';
121
+ };
122
+ /**
123
+ * Input passed to the RBAC auth function during WebSocket upgrade.
124
+ * Contains the HTTP headers, query parameters, and client IP from the
125
+ * connecting worker's upgrade request.
126
+ */
127
+ type AuthInput = {
128
+ /** HTTP headers from the WebSocket upgrade request. */headers: Record<string, string>; /** Query parameters from the upgrade URL. Each key maps to an array of values to support repeated keys. */
129
+ query_params: Record<string, string[]>; /** IP address of the connecting client. */
130
+ ip_address: string;
131
+ };
132
+ /**
133
+ * Return value from the RBAC auth function. Controls which functions the
134
+ * authenticated worker can invoke and what context is forwarded to the
135
+ * middleware.
136
+ */
137
+ type AuthResult = {
138
+ /** 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. */
139
+ forbidden_functions: string[]; /** Trigger type IDs the worker may register triggers for. When omitted, all types are allowed. */
140
+ allowed_trigger_types?: string[]; /** Whether the worker may register new trigger types. */
141
+ allow_trigger_type_registration: boolean; /** Whether the worker may register new functions. Defaults to `true` if omitted. */
142
+ allow_function_registration?: boolean; /** Arbitrary context forwarded to the middleware function on every invocation. */
143
+ context: Record<string, unknown>; /** Optional prefix applied to all function IDs registered by this worker. */
144
+ function_registration_prefix?: string;
145
+ };
146
+ /**
147
+ * Input passed to the RBAC middleware function on every function invocation
148
+ * through the RBAC port. The middleware can inspect, modify, or reject the
149
+ * call before it reaches the target function.
150
+ */
151
+ type MiddlewareFunctionInput = {
152
+ /** ID of the function being invoked. */function_id: string; /** Payload sent by the caller. */
153
+ payload: Record<string, unknown>; /** Routing action, if any. */
154
+ action?: TriggerAction; /** Auth context returned by the auth function for this session. */
155
+ context: Record<string, unknown>;
156
+ };
157
+ /**
158
+ * Input passed to the `on_trigger_type_registration_function_id` hook
159
+ * when a worker attempts to register a new trigger type through the RBAC port.
160
+ * Return an {@link OnTriggerTypeRegistrationResult} with the (possibly mapped)
161
+ * fields, or throw to deny the registration.
162
+ */
163
+ type OnTriggerTypeRegistrationInput = {
164
+ /** ID of the trigger type being registered. */trigger_type_id: string; /** Human-readable description of the trigger type. */
165
+ description: string; /** Auth context from `AuthResult.context` for this session. */
166
+ context: Record<string, unknown>;
167
+ };
168
+ /**
169
+ * Result returned from the `on_trigger_type_registration_function_id` hook.
170
+ * All fields are optional -- omitted fields keep the original value from the
171
+ * registration request.
172
+ */
173
+ type OnTriggerTypeRegistrationResult = {
174
+ /** Mapped trigger type ID. */trigger_type_id?: string; /** Mapped description. */
175
+ description?: string;
176
+ };
177
+ /**
178
+ * Input passed to the `on_trigger_registration_function_id` hook
179
+ * when a worker attempts to register a trigger through the RBAC port.
180
+ * Return an {@link OnTriggerRegistrationResult} with the (possibly mapped)
181
+ * fields, or throw to deny the registration.
182
+ */
183
+ type OnTriggerRegistrationInput = {
184
+ /** ID of the trigger being registered. */trigger_id: string; /** Trigger type identifier. */
185
+ trigger_type: string; /** ID of the function this trigger is bound to. */
186
+ function_id: string; /** Trigger-specific configuration. */
187
+ config: unknown; /** Arbitrary metadata attached to the trigger. */
188
+ metadata?: Record<string, unknown>; /** Auth context from `AuthResult.context` for this session. */
189
+ context: Record<string, unknown>;
190
+ };
191
+ /**
192
+ * Result returned from the `on_trigger_registration_function_id` hook.
193
+ * All fields are optional -- omitted fields keep the original value from the
194
+ * registration request.
195
+ */
196
+ type OnTriggerRegistrationResult = {
197
+ /** Mapped trigger ID. */trigger_id?: string; /** Mapped trigger type. */
198
+ trigger_type?: string; /** Mapped function ID. */
199
+ function_id?: string; /** Mapped trigger configuration. */
200
+ config?: unknown;
201
+ };
202
+ /**
203
+ * Input passed to the `on_function_registration_function_id` hook
204
+ * when a worker attempts to register a function through the RBAC port.
205
+ * Return an {@link OnFunctionRegistrationResult} with the (possibly mapped)
206
+ * fields, or throw to deny the registration.
207
+ */
208
+ type OnFunctionRegistrationInput = {
209
+ /** ID of the function being registered. */function_id: string; /** Human-readable description of the function. */
210
+ description?: string; /** Arbitrary metadata attached to the function. */
211
+ metadata?: Record<string, unknown>; /** Auth context from `AuthResult.context` for this session. */
212
+ context: Record<string, unknown>;
213
+ };
214
+ /**
215
+ * Result returned from the `on_function_registration_function_id` hook.
216
+ * All fields are optional -- omitted fields keep the original value from the
217
+ * registration request.
218
+ */
219
+ type OnFunctionRegistrationResult = {
220
+ /** Mapped function ID. */function_id?: string; /** Mapped description. */
221
+ description?: string; /** Mapped metadata. */
222
+ metadata?: Record<string, unknown>;
223
+ };
224
+ /**
225
+ * Result returned when a function is invoked with `TriggerAction.Enqueue`.
226
+ */
227
+ type EnqueueResult = {
228
+ /** Unique receipt ID for the enqueued message. */messageReceiptId: string;
229
+ };
230
+ /**
231
+ * Request object passed to {@link ISdk.trigger}.
232
+ *
233
+ * @typeParam TInput - Type of the payload.
234
+ */
235
+ type TriggerRequest<TInput = unknown> = {
236
+ /** ID of the function to invoke. */function_id: string; /** Payload to pass to the function. */
237
+ payload: TInput; /** Routing action. Omit for synchronous request/response. */
238
+ action?: TriggerAction; /** Override the default invocation timeout in milliseconds. */
239
+ timeoutMs?: number;
240
+ };
241
+ /**
242
+ * Serializable reference to one end of a streaming channel. Can be included
243
+ * in invocation payloads to pass channel endpoints between workers.
244
+ */
245
+ type StreamChannelRef = {
246
+ /** Unique channel identifier. */channel_id: string; /** Access key for authentication. */
247
+ access_key: string; /** Whether this ref is for reading or writing. */
248
+ direction: 'read' | 'write';
249
+ };
250
+ //#endregion
251
+ //#region src/channels.d.ts
252
+ /**
253
+ * Direction of a streaming channel endpoint. Mirrors the Rust SDK's
254
+ * `ChannelDirection` enum and matches the literal values used by
255
+ * {@link StreamChannelRef.direction}.
256
+ */
257
+ declare const ChannelDirection: {
258
+ readonly Read: "read";
259
+ readonly Write: "write";
260
+ };
261
+ type ChannelDirection = (typeof ChannelDirection)[keyof typeof ChannelDirection];
262
+ /**
263
+ * Discriminated runtime tag for an item observed on a streaming channel.
264
+ * Mirrors the Rust SDK's `ChannelItem` enum (`Text` / `Binary`). Carrier for
265
+ * factory + type-guard helpers so callers can construct and discriminate
266
+ * channel items without depending on Rust-specific shape.
267
+ */
268
+ type ChannelItem = {
269
+ type: 'text';
270
+ value: string;
271
+ } | {
272
+ type: 'binary';
273
+ value: Uint8Array;
274
+ };
275
+ declare const ChannelItem: {
276
+ /** Construct a text channel item. */readonly Text: (value: string) => ChannelItem; /** Construct a binary channel item. */
277
+ readonly Binary: (value: Uint8Array) => ChannelItem;
278
+ };
279
+ /**
280
+ * Write end of a streaming channel. Provides both a Node.js `Writable` stream
281
+ * and a `sendMessage` method for sending structured text messages.
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * import { createChannel } from 'iii-sdk/helpers'
286
+ * const channel = await createChannel(iii)
287
+ *
288
+ * // Stream binary data
289
+ * channel.writer.stream.write(Buffer.from('hello'))
290
+ * channel.writer.stream.end()
291
+ *
292
+ * // Or send text messages
293
+ * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))
294
+ * channel.writer.close()
295
+ * ```
296
+ */
297
+ declare class ChannelWriter {
298
+ private static readonly FRAME_SIZE;
299
+ private ws;
300
+ private wsReady;
301
+ private readonly pendingMessages;
302
+ /** Node.js Writable stream for binary data. */
303
+ readonly stream: Writable;
304
+ private readonly url;
305
+ constructor(engineWsBase: string, ref: StreamChannelRef);
306
+ private ensureConnected;
307
+ /** Send a text message through the channel. */
308
+ sendMessage(msg: string): void;
309
+ /** Close the channel writer. */
310
+ close(): void;
311
+ private sendChunked;
312
+ private sendRaw;
313
+ }
314
+ /**
315
+ * Read end of a streaming channel. Provides both a Node.js `Readable` stream
316
+ * for binary data and an `onMessage` callback for structured text messages.
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * import { createChannel } from 'iii-sdk/helpers'
321
+ * const channel = await createChannel(iii)
322
+ *
323
+ * // Stream binary data
324
+ * channel.reader.stream.on('data', (chunk) => console.log(chunk))
325
+ *
326
+ * // Or receive text messages
327
+ * channel.reader.onMessage((msg) => console.log('Got:', msg))
328
+ * ```
329
+ */
330
+ declare class ChannelReader {
331
+ private ws;
332
+ private connected;
333
+ private readonly messageCallbacks;
334
+ /** Node.js Readable stream for binary data. */
335
+ readonly stream: Readable;
336
+ private readonly url;
337
+ constructor(engineWsBase: string, ref: StreamChannelRef);
338
+ private ensureConnected;
339
+ /** Register a callback to receive text messages from the channel. */
340
+ onMessage(callback: (msg: string) => void): void;
341
+ readAll(): Promise<Buffer>;
342
+ close(): void;
343
+ }
344
+ //#endregion
345
+ //#region src/triggers.d.ts
346
+ /**
347
+ * Configuration passed to a trigger handler when a trigger instance is
348
+ * registered or unregistered.
349
+ *
350
+ * @typeParam TConfig - Type of the trigger-specific configuration.
351
+ */
352
+ type TriggerConfig<TConfig> = {
353
+ /** Trigger instance ID. */id: string; /** Function to invoke when the trigger fires. */
354
+ function_id: string; /** Trigger-specific configuration. */
355
+ config: TConfig; /** Arbitrary metadata attached to the trigger. */
356
+ metadata?: Record<string, unknown>;
357
+ };
358
+ /**
359
+ * Handler interface for custom trigger types. Passed to
360
+ * `ISdk.registerTriggerType`.
361
+ *
362
+ * @typeParam TConfig - Type of the trigger-specific configuration.
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * const handler: TriggerHandler<{ interval: number }> = {
367
+ * async registerTrigger({ id, function_id, config }) {
368
+ * // Set up periodic invocation
369
+ * },
370
+ * async unregisterTrigger({ id, function_id, config }) {
371
+ * // Clean up
372
+ * },
373
+ * }
374
+ * ```
375
+ */
376
+ type TriggerHandler<TConfig> = {
377
+ /** Called when a trigger instance is registered. */registerTrigger(config: TriggerConfig<TConfig>): Promise<void>; /** Called when a trigger instance is unregistered. */
378
+ unregisterTrigger(config: TriggerConfig<TConfig>): Promise<void>;
379
+ };
380
+ //#endregion
381
+ //#region src/types.d.ts
382
+ /**
383
+ * Async function handler for a registered function. Receives the invocation
384
+ * payload and returns the result.
385
+ *
386
+ * @typeParam TInput - Type of the invocation payload.
387
+ * @typeParam TOutput - Type of the return value.
388
+ *
389
+ * @example
390
+ * ```typescript
391
+ * const handler: RemoteFunctionHandler<{ name: string }, { message: string }> =
392
+ * async (data) => ({ message: `Hello, ${data.name}!` })
393
+ * ```
394
+ */
395
+ type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput) => Promise<TOutput>;
396
+ type RegisterTriggerInput = Omit<RegisterTriggerMessage, 'message_type' | 'id'>;
397
+ type RegisterFunctionInput = Omit<RegisterFunctionMessage, 'message_type'>;
398
+ type RegisterFunctionOptions = Omit<RegisterFunctionMessage, 'message_type' | 'id'>;
399
+ type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, 'message_type'>;
400
+ interface ISdk {
401
+ /**
402
+ * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.
403
+ * @param trigger - The trigger to register
404
+ * @returns A trigger object that can be used to unregister the trigger
405
+ *
406
+ * @example
407
+ * ```typescript
408
+ * const trigger = iii.registerTrigger({
409
+ * type: 'cron',
410
+ * function_id: 'my-service::process-batch',
411
+ * config: { expression: '0 *\/5 * * * * *' },
412
+ * })
413
+ *
414
+ * // Later, remove the trigger
415
+ * trigger.unregister()
416
+ * ```
417
+ */
418
+ registerTrigger(trigger: RegisterTriggerInput): Trigger;
419
+ /**
420
+ * Registers a new function with a local handler or an HTTP invocation config.
421
+ * @param functionId - Unique function identifier
422
+ * @param handler - Async handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.)
423
+ * @param options - Optional function registration options (description, request/response formats, metadata)
424
+ * @returns A handle that can be used to unregister the function
425
+ *
426
+ * @example
427
+ * ```typescript
428
+ * // Local handler
429
+ * const ref = iii.registerFunction(
430
+ * 'greet',
431
+ * async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
432
+ * { description: 'Returns a greeting' },
433
+ * )
434
+ *
435
+ * // HTTP invocation
436
+ * const lambdaRef = iii.registerFunction(
437
+ * 'external::my-lambda',
438
+ * {
439
+ * url: 'https://abc123.lambda-url.us-east-1.on.aws',
440
+ * method: 'POST',
441
+ * timeout_ms: 30_000,
442
+ * auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' },
443
+ * },
444
+ * { description: 'Proxied Lambda function' },
445
+ * )
446
+ *
447
+ * // Later, remove the function
448
+ * ref.unregister()
449
+ * ```
450
+ */
451
+ registerFunction(functionId: string, handler: RemoteFunctionHandler | HttpInvocationConfig, options?: RegisterFunctionOptions): FunctionRef;
452
+ /**
453
+ * Invokes a function using a request object.
454
+ *
455
+ * @param request - The trigger request containing function_id, payload, and optional action/timeout
456
+ * @returns The result of the function
457
+ *
458
+ * @example
459
+ * ```typescript
460
+ * // Synchronous invocation
461
+ * const result = await iii.trigger<{ name: string }, { message: string }>({
462
+ * function_id: 'greet',
463
+ * payload: { name: 'World' },
464
+ * timeoutMs: 5000,
465
+ * })
466
+ * console.log(result.message) // "Hello, World!"
467
+ *
468
+ * // Fire-and-forget
469
+ * await iii.trigger({
470
+ * function_id: 'send-email',
471
+ * payload: { to: 'user@example.com' },
472
+ * action: TriggerAction.Void(),
473
+ * })
474
+ *
475
+ * // Enqueue for async processing
476
+ * const receipt = await iii.trigger({
477
+ * function_id: 'process-order',
478
+ * payload: { orderId: '123' },
479
+ * action: TriggerAction.Enqueue({ queue: 'orders' }),
480
+ * })
481
+ * ```
482
+ */
483
+ trigger<TInput, TOutput>(request: TriggerRequest<TInput>): Promise<TOutput>;
484
+ /**
485
+ * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.
486
+ * @param triggerType - The trigger type to register
487
+ * @param handler - The handler for the trigger type
488
+ * @returns A trigger type object that can be used to unregister the trigger type
489
+ *
490
+ * @example
491
+ * ```typescript
492
+ * type CronConfig = { expression: string }
493
+ *
494
+ * iii.registerTriggerType<CronConfig>(
495
+ * { id: 'cron', description: 'Fires on a cron schedule' },
496
+ * {
497
+ * async registerTrigger({ id, function_id, config }) {
498
+ * startCronJob(id, config.expression, () =>
499
+ * iii.trigger({ function_id, payload: {} }),
500
+ * )
501
+ * },
502
+ * async unregisterTrigger({ id }) {
503
+ * stopCronJob(id)
504
+ * },
505
+ * },
506
+ * )
507
+ * ```
508
+ */
509
+ registerTriggerType<TConfig>(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>): TriggerTypeRef<TConfig>;
510
+ /**
511
+ * Unregisters a trigger type.
512
+ * @param triggerType - The trigger type to unregister
513
+ *
514
+ * @example
515
+ * ```typescript
516
+ * iii.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
517
+ * ```
518
+ */
519
+ unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void;
520
+ /**
521
+ * Gracefully shutdown the iii, cleaning up all resources.
522
+ *
523
+ * @example
524
+ * ```typescript
525
+ * process.on('SIGTERM', async () => {
526
+ * await iii.shutdown()
527
+ * process.exit(0)
528
+ * })
529
+ * ```
530
+ */
531
+ shutdown(): Promise<void>;
532
+ }
533
+ /**
534
+ * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to
535
+ * remove the trigger from the engine.
536
+ */
537
+ type Trigger = {
538
+ /** Removes this trigger from the engine. */unregister(): void;
539
+ };
540
+ /**
541
+ * Handle returned by {@link ISdk.registerFunction}. Contains the function's
542
+ * `id` and an `unregister()` method.
543
+ */
544
+ type FunctionRef = {
545
+ /** The unique function identifier. */id: string; /** Removes this function from the engine. */
546
+ unregister: () => void;
547
+ };
548
+ /**
549
+ * Typed handle returned by {@link ISdk.registerTriggerType}.
550
+ *
551
+ * Provides convenience methods to register triggers and functions scoped
552
+ * to this trigger type, so callers don't need to repeat the `type` field.
553
+ *
554
+ * @typeParam TConfig - Trigger-specific configuration type.
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * type CronConfig = { expression: string }
559
+ *
560
+ * const cron = iii.registerTriggerType<CronConfig>(
561
+ * { id: 'cron', description: 'Fires on a cron schedule' },
562
+ * cronHandler,
563
+ * )
564
+ *
565
+ * // Register a trigger — type is inferred as CronConfig
566
+ * cron.registerTrigger('my::fn', { expression: '0 *\/5 * * * * *' })
567
+ *
568
+ * // Register a function and bind a trigger in one call
569
+ * cron.registerFunction(
570
+ * 'my::fn',
571
+ * async (data) => { return { ok: true } },
572
+ * { expression: '0 *\/5 * * * * *' },
573
+ * )
574
+ * ```
575
+ */
576
+ type TriggerTypeRef<TConfig = unknown> = {
577
+ /** The trigger type identifier. */id: string;
578
+ /**
579
+ * Register a trigger bound to this trigger type.
580
+ *
581
+ * @param functionId - The function to invoke when the trigger fires.
582
+ * @param config - Trigger-specific configuration.
583
+ * @param metadata - Optional arbitrary metadata attached to the trigger.
584
+ * @returns A {@link Trigger} handle with an `unregister()` method.
585
+ */
586
+ registerTrigger(functionId: string, config: TConfig, metadata?: Record<string, unknown>): Trigger;
587
+ /**
588
+ * Register a function and immediately bind it to this trigger type.
589
+ *
590
+ * @param functionId - Unique function identifier.
591
+ * @param handler - Local function handler.
592
+ * @param config - Trigger-specific configuration.
593
+ * @param metadata - Optional arbitrary metadata attached to the trigger.
594
+ * @returns A {@link FunctionRef} handle.
595
+ */
596
+ registerFunction(functionId: string, handler: RemoteFunctionHandler, config: TConfig, metadata?: Record<string, unknown>): FunctionRef;
597
+ /**
598
+ * Unregister this trigger type from the engine.
599
+ */
600
+ unregister(): void;
601
+ };
602
+ /**
603
+ * A streaming channel pair for worker-to-worker data transfer. Created via
604
+ * the `createChannel` helper from `iii-sdk/helpers`.
605
+ */
606
+ type Channel = {
607
+ /** Writer end of the channel. */writer: ChannelWriter; /** Reader end of the channel. */
608
+ reader: ChannelReader; /** Serializable reference to the writer (can be sent to other workers). */
609
+ writerRef: StreamChannelRef; /** Serializable reference to the reader (can be sent to other workers). */
610
+ readerRef: StreamChannelRef;
611
+ };
612
+ type InternalHttpRequest<TBody = unknown> = {
613
+ path_params: Record<string, string>;
614
+ query_params: Record<string, string | string[]>;
615
+ body: TBody;
616
+ headers: Record<string, string | string[]>;
617
+ method: string;
618
+ response: ChannelWriter;
619
+ request_body: ChannelReader;
620
+ };
621
+ /**
622
+ * Response object passed to HTTP function handlers. Use `status()` and
623
+ * `headers()` to set response metadata, write to `stream` for streaming
624
+ * responses, and call `close()` when done.
625
+ */
626
+ type HttpResponse = {
627
+ /** Set the HTTP status code. */status: (statusCode: number) => void; /** Set response headers. */
628
+ headers: (headers: Record<string, string>) => void; /** Writable stream for the response body. */
629
+ stream: NodeJS.WritableStream; /** Close the response. */
630
+ close: () => void;
631
+ };
632
+ /**
633
+ * Incoming HTTP request received by a function registered with an HTTP trigger.
634
+ *
635
+ * @typeParam TBody - Type of the parsed request body.
636
+ */
637
+ type HttpRequest<TBody = unknown> = Omit<InternalHttpRequest<TBody>, 'response'>;
638
+ /**
639
+ * Alias for {@link HttpRequest}. Represents an incoming API request.
640
+ *
641
+ * @typeParam TBody - Type of the parsed request body.
642
+ */
643
+ type ApiRequest<TBody = unknown> = HttpRequest<TBody>;
644
+ /**
645
+ * Structured API response returned from HTTP function handlers.
646
+ *
647
+ * @typeParam TStatus - HTTP status code literal type.
648
+ * @typeParam TBody - Type of the response body.
649
+ *
650
+ * @example
651
+ * ```typescript
652
+ * const response: ApiResponse = {
653
+ * status_code: 200,
654
+ * headers: { 'content-type': 'application/json' },
655
+ * body: { message: 'ok' },
656
+ * }
657
+ * ```
658
+ */
659
+ type ApiResponse<TStatus extends number = number, TBody = string | Buffer | Record<string, unknown>> = {
660
+ /** HTTP status code. */status_code: TStatus; /** Response headers. */
661
+ headers?: Record<string, string>; /** Response body. */
662
+ body?: TBody;
663
+ };
664
+ //#endregion
665
+ //#region src/utils.d.ts
666
+ /**
667
+ * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)
668
+ * into the function handler format expected by the SDK.
669
+ *
670
+ * @param callback - Async handler receiving an {@link HttpRequest} and {@link HttpResponse}.
671
+ * @returns A function handler compatible with {@link ISdk.registerFunction}.
672
+ *
673
+ * @example
674
+ * ```typescript
675
+ * import { http } from 'iii-sdk'
676
+ *
677
+ * iii.registerFunction(
678
+ * 'my-api',
679
+ * http(async (req, res) => {
680
+ * res.status(200)
681
+ * res.headers({ 'content-type': 'application/json' })
682
+ * res.stream.end(JSON.stringify({ hello: 'world' }))
683
+ * res.close()
684
+ * }),
685
+ * )
686
+ * ```
687
+ */
688
+ declare const http: (callback: (req: HttpRequest, res: HttpResponse) => Promise<void | ApiResponse>) => (req: InternalHttpRequest) => Promise<void | ApiResponse>;
689
+ /**
690
+ * Type guard that checks if a value is a {@link StreamChannelRef}.
691
+ *
692
+ * @param value - Value to check.
693
+ * @returns `true` if the value is a valid `StreamChannelRef`.
694
+ */
695
+ declare const isChannelRef: (value: unknown) => value is StreamChannelRef;
696
+ /**
697
+ * Recursively extract all {@link StreamChannelRef} values from a JSON-like
698
+ * input, returning each match paired with its dotted/bracketed path. Mirrors
699
+ * the Rust SDK's `extract_channel_refs`.
700
+ *
701
+ * @param data - Arbitrary JSON-like value.
702
+ * @returns Array of `[path, ref]` tuples. Empty when no refs are found.
703
+ */
704
+ declare const extractChannelRefs: (data: unknown) => Array<[string, StreamChannelRef]>;
705
+ //#endregion
706
+ 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 };
707
+ //# sourceMappingURL=utils-tcJ0Rzg-.d.mts.map