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.
package/dist/index.d.mts CHANGED
@@ -1,320 +1,6 @@
1
- import { n as IStream } from "./stream-CPQKQv-x.mjs";
2
- import { Readable, Writable } from "node:stream";
1
+ import { A as MessageType, B as RegisterTriggerTypeMessage, C as ChannelReader, D as EnqueueResult, E as AuthResult, F as OnTriggerRegistrationResult, H as TriggerAction$1, I as OnTriggerTypeRegistrationInput, L as OnTriggerTypeRegistrationResult, M as OnFunctionRegistrationInput, N as OnFunctionRegistrationResult, O as HttpAuthConfig, P as OnTriggerRegistrationInput, R as RegisterFunctionMessage, T as AuthInput, U as TriggerRequest, V as StreamChannelRef, _ as Trigger, a as ApiResponse, b as TriggerHandler, c as HttpRequest, d as InternalHttpRequest, f as RegisterFunctionInput, g as RemoteFunctionHandler, h as RegisterTriggerTypeInput, i as ApiRequest, j as MiddlewareFunctionInput, k as HttpInvocationConfig, l as HttpResponse, m as RegisterTriggerInput, n as http, o as Channel, p as RegisterFunctionOptions, s as FunctionRef, u as ISdk, v as TriggerTypeRef, w as ChannelWriter, y as TriggerConfig, z as RegisterTriggerMessage } from "./utils-tcJ0Rzg-.mjs";
3
2
  import { Logger, OtelConfig } from "@iii-dev/observability";
4
3
 
5
- //#region src/iii-types.d.ts
6
- declare enum MessageType {
7
- RegisterFunction = "registerfunction",
8
- UnregisterFunction = "unregisterfunction",
9
- InvokeFunction = "invokefunction",
10
- InvocationResult = "invocationresult",
11
- RegisterTriggerType = "registertriggertype",
12
- RegisterTrigger = "registertrigger",
13
- UnregisterTrigger = "unregistertrigger",
14
- UnregisterTriggerType = "unregistertriggertype",
15
- TriggerRegistrationResult = "triggerregistrationresult",
16
- WorkerRegistered = "workerregistered"
17
- }
18
- type RegisterTriggerTypeMessage = {
19
- message_type: MessageType.RegisterTriggerType;
20
- id: string;
21
- description: string;
22
- };
23
- type RegisterTriggerMessage = {
24
- message_type: MessageType.RegisterTrigger;
25
- id: string;
26
- type: string;
27
- function_id: string;
28
- config: unknown;
29
- metadata?: Record<string, unknown>;
30
- };
31
- /**
32
- * Authentication configuration for HTTP-invoked functions.
33
- *
34
- * - `hmac` -- HMAC signature verification using a shared secret.
35
- * - `bearer` -- Bearer token authentication.
36
- * - `api_key` -- API key sent via a custom header.
37
- */
38
- type HttpAuthConfig = {
39
- type: 'hmac';
40
- secret_key: string;
41
- } | {
42
- type: 'bearer';
43
- token_key: string;
44
- } | {
45
- type: 'api_key';
46
- header: string;
47
- value_key: string;
48
- };
49
- /**
50
- * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare
51
- * Workers, etc.) instead of a local handler.
52
- */
53
- type HttpInvocationConfig = {
54
- /** URL to invoke. */url: string; /** HTTP method. Defaults to `POST`. */
55
- method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Timeout in milliseconds. */
56
- timeout_ms?: number; /** Custom headers to send with the request. */
57
- headers?: Record<string, string>; /** Authentication configuration. */
58
- auth?: HttpAuthConfig;
59
- };
60
- type RegisterFunctionFormat = {
61
- /**
62
- * The name of the parameter
63
- */
64
- name?: string;
65
- /**
66
- * The description of the parameter
67
- */
68
- description?: string;
69
- /**
70
- * The type of the parameter
71
- */
72
- type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer';
73
- /**
74
- * The body of the parameter (for objects)
75
- */
76
- properties?: Record<string, unknown>;
77
- /**
78
- * The items of the parameter (for arrays)
79
- */
80
- items?: unknown;
81
- /**
82
- * Whether the parameter is required
83
- */
84
- required?: string[];
85
- [key: string]: unknown;
86
- };
87
- type RegisterFunctionMessage = {
88
- message_type: MessageType.RegisterFunction;
89
- /**
90
- * The path of the function (use :: for namespacing, e.g. external::my_lambda)
91
- */
92
- id: string;
93
- /**
94
- * The description of the function
95
- */
96
- description?: string;
97
- /**
98
- * The request format of the function
99
- */
100
- request_format?: RegisterFunctionFormat;
101
- /**
102
- * The response format of the function
103
- */
104
- response_format?: RegisterFunctionFormat;
105
- metadata?: Record<string, unknown>;
106
- /**
107
- * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)
108
- */
109
- invocation?: HttpInvocationConfig;
110
- };
111
- /**
112
- * Routing action for {@link TriggerRequest}. Determines how the engine
113
- * handles the invocation.
114
- *
115
- * - `enqueue` -- Routes through a named queue for async processing.
116
- * - `void` -- Fire-and-forget, no response.
117
- */
118
- type TriggerAction$1 = {
119
- type: 'enqueue';
120
- queue: string;
121
- } | {
122
- type: 'void';
123
- };
124
- /**
125
- * Input passed to the RBAC auth function during WebSocket upgrade.
126
- * Contains the HTTP headers, query parameters, and client IP from the
127
- * connecting worker's upgrade request.
128
- */
129
- type AuthInput = {
130
- /** 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. */
131
- query_params: Record<string, string[]>; /** IP address of the connecting client. */
132
- ip_address: string;
133
- };
134
- /**
135
- * Return value from the RBAC auth function. Controls which functions the
136
- * authenticated worker can invoke and what context is forwarded to the
137
- * middleware.
138
- */
139
- type AuthResult = {
140
- /** 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. */
141
- forbidden_functions: string[]; /** Trigger type IDs the worker may register triggers for. When omitted, all types are allowed. */
142
- allowed_trigger_types?: string[]; /** Whether the worker may register new trigger types. */
143
- allow_trigger_type_registration: boolean; /** Whether the worker may register new functions. Defaults to `true` if omitted. */
144
- allow_function_registration?: boolean; /** Arbitrary context forwarded to the middleware function on every invocation. */
145
- context: Record<string, unknown>; /** Optional prefix applied to all function IDs registered by this worker. */
146
- function_registration_prefix?: string;
147
- };
148
- /**
149
- * Input passed to the RBAC middleware function on every function invocation
150
- * through the RBAC port. The middleware can inspect, modify, or reject the
151
- * call before it reaches the target function.
152
- */
153
- type MiddlewareFunctionInput = {
154
- /** ID of the function being invoked. */function_id: string; /** Payload sent by the caller. */
155
- payload: Record<string, unknown>; /** Routing action, if any. */
156
- action?: TriggerAction$1; /** Auth context returned by the auth function for this session. */
157
- context: Record<string, unknown>;
158
- };
159
- /**
160
- * Input passed to the `on_trigger_type_registration_function_id` hook
161
- * when a worker attempts to register a new trigger type through the RBAC port.
162
- * Return an {@link OnTriggerTypeRegistrationResult} with the (possibly mapped)
163
- * fields, or throw to deny the registration.
164
- */
165
- type OnTriggerTypeRegistrationInput = {
166
- /** ID of the trigger type being registered. */trigger_type_id: string; /** Human-readable description of the trigger type. */
167
- description: string; /** Auth context from `AuthResult.context` for this session. */
168
- context: Record<string, unknown>;
169
- };
170
- /**
171
- * Result returned from the `on_trigger_type_registration_function_id` hook.
172
- * All fields are optional -- omitted fields keep the original value from the
173
- * registration request.
174
- */
175
- type OnTriggerTypeRegistrationResult = {
176
- /** Mapped trigger type ID. */trigger_type_id?: string; /** Mapped description. */
177
- description?: string;
178
- };
179
- /**
180
- * Input passed to the `on_trigger_registration_function_id` hook
181
- * when a worker attempts to register a trigger through the RBAC port.
182
- * Return an {@link OnTriggerRegistrationResult} with the (possibly mapped)
183
- * fields, or throw to deny the registration.
184
- */
185
- type OnTriggerRegistrationInput = {
186
- /** ID of the trigger being registered. */trigger_id: string; /** Trigger type identifier. */
187
- trigger_type: string; /** ID of the function this trigger is bound to. */
188
- function_id: string; /** Trigger-specific configuration. */
189
- config: unknown; /** Arbitrary metadata attached to the trigger. */
190
- metadata?: Record<string, unknown>; /** Auth context from `AuthResult.context` for this session. */
191
- context: Record<string, unknown>;
192
- };
193
- /**
194
- * Result returned from the `on_trigger_registration_function_id` hook.
195
- * All fields are optional -- omitted fields keep the original value from the
196
- * registration request.
197
- */
198
- type OnTriggerRegistrationResult = {
199
- /** Mapped trigger ID. */trigger_id?: string; /** Mapped trigger type. */
200
- trigger_type?: string; /** Mapped function ID. */
201
- function_id?: string; /** Mapped trigger configuration. */
202
- config?: unknown;
203
- };
204
- /**
205
- * Input passed to the `on_function_registration_function_id` hook
206
- * when a worker attempts to register a function through the RBAC port.
207
- * Return an {@link OnFunctionRegistrationResult} with the (possibly mapped)
208
- * fields, or throw to deny the registration.
209
- */
210
- type OnFunctionRegistrationInput = {
211
- /** ID of the function being registered. */function_id: string; /** Human-readable description of the function. */
212
- description?: string; /** Arbitrary metadata attached to the function. */
213
- metadata?: Record<string, unknown>; /** Auth context from `AuthResult.context` for this session. */
214
- context: Record<string, unknown>;
215
- };
216
- /**
217
- * Result returned from the `on_function_registration_function_id` hook.
218
- * All fields are optional -- omitted fields keep the original value from the
219
- * registration request.
220
- */
221
- type OnFunctionRegistrationResult = {
222
- /** Mapped function ID. */function_id?: string; /** Mapped description. */
223
- description?: string; /** Mapped metadata. */
224
- metadata?: Record<string, unknown>;
225
- };
226
- /**
227
- * Result returned when a function is invoked with `TriggerAction.Enqueue`.
228
- */
229
- type EnqueueResult = {
230
- /** Unique receipt ID for the enqueued message. */messageReceiptId: string;
231
- };
232
- /**
233
- * Request object passed to {@link ISdk.trigger}.
234
- *
235
- * @typeParam TInput - Type of the payload.
236
- */
237
- type TriggerRequest<TInput = unknown> = {
238
- /** ID of the function to invoke. */function_id: string; /** Payload to pass to the function. */
239
- payload: TInput; /** Routing action. Omit for synchronous request/response. */
240
- action?: TriggerAction$1; /** Override the default invocation timeout in milliseconds. */
241
- timeoutMs?: number;
242
- };
243
- /**
244
- * Serializable reference to one end of a streaming channel. Can be included
245
- * in invocation payloads to pass channel endpoints between workers.
246
- */
247
- type StreamChannelRef = {
248
- /** Unique channel identifier. */channel_id: string; /** Access key for authentication. */
249
- access_key: string; /** Whether this ref is for reading or writing. */
250
- direction: 'read' | 'write';
251
- };
252
- //#endregion
253
- //#region src/channels.d.ts
254
- /**
255
- * Write end of a streaming channel. Provides both a Node.js `Writable` stream
256
- * and a `sendMessage` method for sending structured text messages.
257
- *
258
- * @example
259
- * ```typescript
260
- * const channel = await iii.createChannel()
261
- *
262
- * // Stream binary data
263
- * channel.writer.stream.write(Buffer.from('hello'))
264
- * channel.writer.stream.end()
265
- *
266
- * // Or send text messages
267
- * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))
268
- * channel.writer.close()
269
- * ```
270
- */
271
- declare class ChannelWriter {
272
- private static readonly FRAME_SIZE;
273
- private ws;
274
- private wsReady;
275
- private readonly pendingMessages;
276
- /** Node.js Writable stream for binary data. */
277
- readonly stream: Writable;
278
- private readonly url;
279
- constructor(engineWsBase: string, ref: StreamChannelRef);
280
- private ensureConnected;
281
- /** Send a text message through the channel. */
282
- sendMessage(msg: string): void;
283
- /** Close the channel writer. */
284
- close(): void;
285
- private sendChunked;
286
- private sendRaw;
287
- }
288
- /**
289
- * Read end of a streaming channel. Provides both a Node.js `Readable` stream
290
- * for binary data and an `onMessage` callback for structured text messages.
291
- *
292
- * @example
293
- * ```typescript
294
- * const channel = await iii.createChannel()
295
- *
296
- * // Stream binary data
297
- * channel.reader.stream.on('data', (chunk) => console.log(chunk))
298
- *
299
- * // Or receive text messages
300
- * channel.reader.onMessage((msg) => console.log('Got:', msg))
301
- * ```
302
- */
303
- declare class ChannelReader {
304
- private ws;
305
- private connected;
306
- private readonly messageCallbacks;
307
- /** Node.js Readable stream for binary data. */
308
- readonly stream: Readable;
309
- private readonly url;
310
- constructor(engineWsBase: string, ref: StreamChannelRef);
311
- private ensureConnected;
312
- /** Register a callback to receive text messages from the channel. */
313
- onMessage(callback: (msg: string) => void): void;
314
- readAll(): Promise<Buffer>;
315
- close(): void;
316
- }
317
- //#endregion
318
4
  //#region src/errors.d.ts
319
5
  /**
320
6
  * Typed error surfaced when an invocation dispatched over the SDK fails — RBAC
@@ -385,384 +71,6 @@ interface IIIReconnectionConfig {
385
71
  maxRetries: number;
386
72
  }
387
73
  //#endregion
388
- //#region src/triggers.d.ts
389
- /**
390
- * Configuration passed to a trigger handler when a trigger instance is
391
- * registered or unregistered.
392
- *
393
- * @typeParam TConfig - Type of the trigger-specific configuration.
394
- */
395
- type TriggerConfig<TConfig> = {
396
- /** Trigger instance ID. */id: string; /** Function to invoke when the trigger fires. */
397
- function_id: string; /** Trigger-specific configuration. */
398
- config: TConfig; /** Arbitrary metadata attached to the trigger. */
399
- metadata?: Record<string, unknown>;
400
- };
401
- /**
402
- * Handler interface for custom trigger types. Passed to
403
- * `ISdk.registerTriggerType`.
404
- *
405
- * @typeParam TConfig - Type of the trigger-specific configuration.
406
- *
407
- * @example
408
- * ```typescript
409
- * const handler: TriggerHandler<{ interval: number }> = {
410
- * async registerTrigger({ id, function_id, config }) {
411
- * // Set up periodic invocation
412
- * },
413
- * async unregisterTrigger({ id, function_id, config }) {
414
- * // Clean up
415
- * },
416
- * }
417
- * ```
418
- */
419
- type TriggerHandler<TConfig> = {
420
- /** Called when a trigger instance is registered. */registerTrigger(config: TriggerConfig<TConfig>): Promise<void>; /** Called when a trigger instance is unregistered. */
421
- unregisterTrigger(config: TriggerConfig<TConfig>): Promise<void>;
422
- };
423
- //#endregion
424
- //#region src/types.d.ts
425
- /**
426
- * Async function handler for a registered function. Receives the invocation
427
- * payload and returns the result.
428
- *
429
- * @typeParam TInput - Type of the invocation payload.
430
- * @typeParam TOutput - Type of the return value.
431
- *
432
- * @example
433
- * ```typescript
434
- * const handler: RemoteFunctionHandler<{ name: string }, { message: string }> =
435
- * async (data) => ({ message: `Hello, ${data.name}!` })
436
- * ```
437
- */
438
- type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput) => Promise<TOutput>;
439
- type RegisterTriggerInput = Omit<RegisterTriggerMessage, 'message_type' | 'id'>;
440
- type RegisterFunctionInput = Omit<RegisterFunctionMessage, 'message_type'>;
441
- type RegisterFunctionOptions = Omit<RegisterFunctionMessage, 'message_type' | 'id'>;
442
- type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, 'message_type'>;
443
- interface ISdk {
444
- /**
445
- * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.
446
- * @param trigger - The trigger to register
447
- * @returns A trigger object that can be used to unregister the trigger
448
- *
449
- * @example
450
- * ```typescript
451
- * const trigger = iii.registerTrigger({
452
- * type: 'cron',
453
- * function_id: 'my-service::process-batch',
454
- * config: { expression: '0 *\/5 * * * * *' },
455
- * })
456
- *
457
- * // Later, remove the trigger
458
- * trigger.unregister()
459
- * ```
460
- */
461
- registerTrigger(trigger: RegisterTriggerInput): Trigger;
462
- /**
463
- * Registers a new function with a local handler or an HTTP invocation config.
464
- * @param functionId - Unique function identifier
465
- * @param handler - Async handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.)
466
- * @param options - Optional function registration options (description, request/response formats, metadata)
467
- * @returns A handle that can be used to unregister the function
468
- *
469
- * @example
470
- * ```typescript
471
- * // Local handler
472
- * const ref = iii.registerFunction(
473
- * 'greet',
474
- * async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
475
- * { description: 'Returns a greeting' },
476
- * )
477
- *
478
- * // HTTP invocation
479
- * const lambdaRef = iii.registerFunction(
480
- * 'external::my-lambda',
481
- * {
482
- * url: 'https://abc123.lambda-url.us-east-1.on.aws',
483
- * method: 'POST',
484
- * timeout_ms: 30_000,
485
- * auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' },
486
- * },
487
- * { description: 'Proxied Lambda function' },
488
- * )
489
- *
490
- * // Later, remove the function
491
- * ref.unregister()
492
- * ```
493
- */
494
- registerFunction(functionId: string, handler: RemoteFunctionHandler | HttpInvocationConfig, options?: RegisterFunctionOptions): FunctionRef;
495
- /**
496
- * Invokes a function using a request object.
497
- *
498
- * @param request - The trigger request containing function_id, payload, and optional action/timeout
499
- * @returns The result of the function
500
- *
501
- * @example
502
- * ```typescript
503
- * // Synchronous invocation
504
- * const result = await iii.trigger<{ name: string }, { message: string }>({
505
- * function_id: 'greet',
506
- * payload: { name: 'World' },
507
- * timeoutMs: 5000,
508
- * })
509
- * console.log(result.message) // "Hello, World!"
510
- *
511
- * // Fire-and-forget
512
- * await iii.trigger({
513
- * function_id: 'send-email',
514
- * payload: { to: 'user@example.com' },
515
- * action: TriggerAction.Void(),
516
- * })
517
- *
518
- * // Enqueue for async processing
519
- * const receipt = await iii.trigger({
520
- * function_id: 'process-order',
521
- * payload: { orderId: '123' },
522
- * action: TriggerAction.Enqueue({ queue: 'orders' }),
523
- * })
524
- * ```
525
- */
526
- trigger<TInput, TOutput>(request: TriggerRequest<TInput>): Promise<TOutput>;
527
- /**
528
- * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.
529
- * @param triggerType - The trigger type to register
530
- * @param handler - The handler for the trigger type
531
- * @returns A trigger type object that can be used to unregister the trigger type
532
- *
533
- * @example
534
- * ```typescript
535
- * type CronConfig = { expression: string }
536
- *
537
- * iii.registerTriggerType<CronConfig>(
538
- * { id: 'cron', description: 'Fires on a cron schedule' },
539
- * {
540
- * async registerTrigger({ id, function_id, config }) {
541
- * startCronJob(id, config.expression, () =>
542
- * iii.trigger({ function_id, payload: {} }),
543
- * )
544
- * },
545
- * async unregisterTrigger({ id }) {
546
- * stopCronJob(id)
547
- * },
548
- * },
549
- * )
550
- * ```
551
- */
552
- registerTriggerType<TConfig>(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>): TriggerTypeRef<TConfig>;
553
- /**
554
- * Unregisters a trigger type.
555
- * @param triggerType - The trigger type to unregister
556
- *
557
- * @example
558
- * ```typescript
559
- * iii.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
560
- * ```
561
- */
562
- unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void;
563
- /**
564
- * Creates a streaming channel pair for worker-to-worker data transfer.
565
- * Returns a Channel with a local writer/reader and serializable refs that
566
- * can be passed as fields in the invocation data to other functions.
567
- *
568
- * @param bufferSize - Optional buffer size for the channel (default: 64)
569
- * @returns A Channel with writer, reader, and their serializable refs
570
- *
571
- * @example
572
- * ```typescript
573
- * const channel = await iii.createChannel()
574
- *
575
- * // Pass the writer ref to another function
576
- * await iii.trigger({
577
- * function_id: 'stream-producer',
578
- * payload: { outputChannel: channel.writerRef },
579
- * })
580
- *
581
- * // Read data locally
582
- * channel.reader.onMessage((msg) => {
583
- * console.log('Received:', msg)
584
- * })
585
- * ```
586
- */
587
- createChannel(bufferSize?: number): Promise<Channel>;
588
- /**
589
- * Creates a new stream implementation.
590
- *
591
- * This overrides the default stream implementation.
592
- *
593
- * @param streamName - The name of the stream
594
- * @param stream - The stream implementation
595
- *
596
- * @example
597
- * ```typescript
598
- * const redisStream: IStream<UserSession> = {
599
- * async get({ group_id, item_id }) {
600
- * return JSON.parse(await redis.get(`${group_id}:${item_id}`) ?? 'null')
601
- * },
602
- * async set({ group_id, item_id, data }) {
603
- * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
604
- * await redis.set(`${group_id}:${item_id}`, JSON.stringify(data))
605
- * return { old_value: old ?? undefined, new_value: data }
606
- * },
607
- * async delete({ group_id, item_id }) {
608
- * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
609
- * await redis.del(`${group_id}:${item_id}`)
610
- * return { old_value: old ?? undefined }
611
- * },
612
- * async list({ group_id }) { return [] },
613
- * async listGroups() { return [] },
614
- * async update({ group_id, item_id, ops }) { return { new_value: {} } },
615
- * }
616
- *
617
- * iii.createStream('sessions', redisStream)
618
- * ```
619
- */
620
- createStream<TData>(streamName: string, stream: IStream<TData>): void;
621
- /**
622
- * Gracefully shutdown the iii, cleaning up all resources.
623
- *
624
- * @example
625
- * ```typescript
626
- * process.on('SIGTERM', async () => {
627
- * await iii.shutdown()
628
- * process.exit(0)
629
- * })
630
- * ```
631
- */
632
- shutdown(): Promise<void>;
633
- }
634
- /**
635
- * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to
636
- * remove the trigger from the engine.
637
- */
638
- type Trigger = {
639
- /** Removes this trigger from the engine. */unregister(): void;
640
- };
641
- /**
642
- * Handle returned by {@link ISdk.registerFunction}. Contains the function's
643
- * `id` and an `unregister()` method.
644
- */
645
- type FunctionRef = {
646
- /** The unique function identifier. */id: string; /** Removes this function from the engine. */
647
- unregister: () => void;
648
- };
649
- /**
650
- * Typed handle returned by {@link ISdk.registerTriggerType}.
651
- *
652
- * Provides convenience methods to register triggers and functions scoped
653
- * to this trigger type, so callers don't need to repeat the `type` field.
654
- *
655
- * @typeParam TConfig - Trigger-specific configuration type.
656
- *
657
- * @example
658
- * ```typescript
659
- * type CronConfig = { expression: string }
660
- *
661
- * const cron = iii.registerTriggerType<CronConfig>(
662
- * { id: 'cron', description: 'Fires on a cron schedule' },
663
- * cronHandler,
664
- * )
665
- *
666
- * // Register a trigger — type is inferred as CronConfig
667
- * cron.registerTrigger('my::fn', { expression: '0 *\/5 * * * * *' })
668
- *
669
- * // Register a function and bind a trigger in one call
670
- * cron.registerFunction(
671
- * 'my::fn',
672
- * async (data) => { return { ok: true } },
673
- * { expression: '0 *\/5 * * * * *' },
674
- * )
675
- * ```
676
- */
677
- type TriggerTypeRef<TConfig = unknown> = {
678
- /** The trigger type identifier. */id: string;
679
- /**
680
- * Register a trigger bound to this trigger type.
681
- *
682
- * @param functionId - The function to invoke when the trigger fires.
683
- * @param config - Trigger-specific configuration.
684
- * @param metadata - Optional arbitrary metadata attached to the trigger.
685
- * @returns A {@link Trigger} handle with an `unregister()` method.
686
- */
687
- registerTrigger(functionId: string, config: TConfig, metadata?: Record<string, unknown>): Trigger;
688
- /**
689
- * Register a function and immediately bind it to this trigger type.
690
- *
691
- * @param functionId - Unique function identifier.
692
- * @param handler - Local function handler.
693
- * @param config - Trigger-specific configuration.
694
- * @param metadata - Optional arbitrary metadata attached to the trigger.
695
- * @returns A {@link FunctionRef} handle.
696
- */
697
- registerFunction(functionId: string, handler: RemoteFunctionHandler, config: TConfig, metadata?: Record<string, unknown>): FunctionRef;
698
- /**
699
- * Unregister this trigger type from the engine.
700
- */
701
- unregister(): void;
702
- };
703
- /**
704
- * A streaming channel pair for worker-to-worker data transfer. Created via
705
- * {@link ISdk.createChannel}.
706
- */
707
- type Channel = {
708
- /** Writer end of the channel. */writer: ChannelWriter; /** Reader end of the channel. */
709
- reader: ChannelReader; /** Serializable reference to the writer (can be sent to other workers). */
710
- writerRef: StreamChannelRef; /** Serializable reference to the reader (can be sent to other workers). */
711
- readerRef: StreamChannelRef;
712
- };
713
- type InternalHttpRequest<TBody = unknown> = {
714
- path_params: Record<string, string>;
715
- query_params: Record<string, string | string[]>;
716
- body: TBody;
717
- headers: Record<string, string | string[]>;
718
- method: string;
719
- response: ChannelWriter;
720
- request_body: ChannelReader;
721
- };
722
- /**
723
- * Response object passed to HTTP function handlers. Use `status()` and
724
- * `headers()` to set response metadata, write to `stream` for streaming
725
- * responses, and call `close()` when done.
726
- */
727
- type HttpResponse = {
728
- /** Set the HTTP status code. */status: (statusCode: number) => void; /** Set response headers. */
729
- headers: (headers: Record<string, string>) => void; /** Writable stream for the response body. */
730
- stream: NodeJS.WritableStream; /** Close the response. */
731
- close: () => void;
732
- };
733
- /**
734
- * Incoming HTTP request received by a function registered with an HTTP trigger.
735
- *
736
- * @typeParam TBody - Type of the parsed request body.
737
- */
738
- type HttpRequest<TBody = unknown> = Omit<InternalHttpRequest<TBody>, 'response'>;
739
- /**
740
- * Alias for {@link HttpRequest}. Represents an incoming API request.
741
- *
742
- * @typeParam TBody - Type of the parsed request body.
743
- */
744
- type ApiRequest<TBody = unknown> = HttpRequest<TBody>;
745
- /**
746
- * Structured API response returned from HTTP function handlers.
747
- *
748
- * @typeParam TStatus - HTTP status code literal type.
749
- * @typeParam TBody - Type of the response body.
750
- *
751
- * @example
752
- * ```typescript
753
- * const response: ApiResponse = {
754
- * status_code: 200,
755
- * headers: { 'content-type': 'application/json' },
756
- * body: { message: 'ok' },
757
- * }
758
- * ```
759
- */
760
- type ApiResponse<TStatus extends number = number, TBody = string | Buffer | Record<string, unknown>> = {
761
- /** HTTP status code. */status_code: TStatus; /** Response headers. */
762
- headers?: Record<string, string>; /** Response body. */
763
- body?: TBody;
764
- };
765
- //#endregion
766
74
  //#region src/iii.d.ts
767
75
  /** @internal */
768
76
  type TelemetryOptions = {
@@ -861,30 +169,5 @@ declare const TriggerAction: {
861
169
  */
862
170
  declare const registerWorker: (address: string, options?: InitOptions) => ISdk;
863
171
  //#endregion
864
- //#region src/utils.d.ts
865
- /**
866
- * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)
867
- * into the function handler format expected by the SDK.
868
- *
869
- * @param callback - Async handler receiving an {@link HttpRequest} and {@link HttpResponse}.
870
- * @returns A function handler compatible with {@link ISdk.registerFunction}.
871
- *
872
- * @example
873
- * ```typescript
874
- * import { http } from 'iii-sdk'
875
- *
876
- * iii.registerFunction(
877
- * 'my-api',
878
- * http(async (req, res) => {
879
- * res.status(200)
880
- * res.headers({ 'content-type': 'application/json' })
881
- * res.stream.end(JSON.stringify({ hello: 'world' }))
882
- * res.close()
883
- * }),
884
- * )
885
- * ```
886
- */
887
- declare const http: (callback: (req: HttpRequest, res: HttpResponse) => Promise<void | ApiResponse>) => (req: InternalHttpRequest) => Promise<void | ApiResponse>;
888
- //#endregion
889
172
  export { type ApiRequest, type ApiResponse, type AuthInput, type AuthResult, type Channel, ChannelReader, ChannelWriter, EngineFunctions, EngineTriggers, type EnqueueResult, type FunctionRef, type HttpAuthConfig, type HttpInvocationConfig, type HttpRequest, type HttpResponse, IIIInvocationError, type IIIInvocationErrorInit, type ISdk, type InitOptions, type InternalHttpRequest, Logger, type MessageType, type MiddlewareFunctionInput, type OnFunctionRegistrationInput, type OnFunctionRegistrationResult, type OnTriggerRegistrationInput, type OnTriggerRegistrationResult, type OnTriggerTypeRegistrationInput, type OnTriggerTypeRegistrationResult, type RegisterFunctionInput, type RegisterFunctionMessage, type RegisterFunctionOptions, type RegisterTriggerInput, type RegisterTriggerMessage, type RegisterTriggerTypeInput, type RegisterTriggerTypeMessage, type RemoteFunctionHandler, type StreamChannelRef, type Trigger, TriggerAction, type TriggerAction$1 as TriggerActionType, type TriggerConfig, type TriggerHandler, type TriggerRequest, type TriggerTypeRef, http, registerWorker };
890
173
  //# sourceMappingURL=index.d.mts.map