iii-browser-sdk 0.25.0 → 0.26.0-rc.2

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.
@@ -1,14 +1,313 @@
1
+ //#region src/observe-types.d.ts
2
+ /** What an observer ships to its target. Default `['input', 'output', 'caller']`. */
3
+ type Capture = 'input' | 'output' | 'error' | 'caller' | 'metadata';
4
+ /**
5
+ * An observer's lifecycle: `pending` (no host yet, waiting for the host's
6
+ * ack, or no target yet) → `active` or `error`; `suspended` while its worker
7
+ * or target is away; `disposed` at the end.
8
+ */
9
+ type ObserverState = 'pending' | 'active' | 'suspended' | 'error' | 'disposed';
10
+ /**
11
+ * A declarative filter over `input`, `output`, `error`, `caller` and
12
+ * `metadata`, with explicit operators only:
13
+ * `{ 'input.amount': { $gte: 500 } }`. See the filter language reference.
14
+ */
15
+ type Filter = Record<string, unknown>;
16
+ /** The right side of `iii.observe`: a registered function. */
17
+ type Target = string | {
18
+ function_id: string;
19
+ namespace?: string;
20
+ };
21
+ /** A state reason or an error: a machine-readable code and a message. */
22
+ type ObserveReason = {
23
+ code: string;
24
+ message: string;
25
+ };
26
+ /**
27
+ * Who started an invocation: the worker (`worker_id` / `worker_name`, stamped
28
+ * by the engine), and the function and invocation the call was made from.
29
+ */
30
+ interface Caller {
31
+ /** Absent on activations, whose caller is the engine (`worker_name: 'iii-engine'`). */
32
+ worker_id?: string;
33
+ worker_name?: string;
34
+ /** The handler the call was made from; absent for top-level calls. */
35
+ function_id?: string;
36
+ invocation_id?: string;
37
+ /** The caller of that handler, one level only. */
38
+ parent?: Omit<Caller, 'parent'>;
39
+ }
40
+ /**
41
+ * A caller as the SDK knows it: every field may be missing (a top-level call
42
+ * has no function; a call made before `WorkerRegistered` has no worker id).
43
+ */
44
+ type CallerInfo = Partial<Omit<Caller, 'parent'>> & {
45
+ parent?: Partial<Omit<Caller, 'parent'>>;
46
+ };
47
+ /**
48
+ * What an observer's target receives when iii delivers with
49
+ * `deliver: 'envelope'` (the default). Fields not in the observer's
50
+ * `capture` are absent.
51
+ */
52
+ interface Observed<I = unknown, O = unknown> {
53
+ observer_id: string;
54
+ activation_id: string;
55
+ function_id: string;
56
+ namespace: string;
57
+ invocation_id: string;
58
+ status: 'success' | 'error';
59
+ input?: I;
60
+ output?: O;
61
+ error?: {
62
+ code: string;
63
+ message: string;
64
+ };
65
+ caller?: Caller;
66
+ metadata?: Record<string, unknown>;
67
+ started_at_ms: number;
68
+ duration_ms: number;
69
+ }
70
+ /** The left side of `iii.observe`: what is observed. */
71
+ interface ObserveSource {
72
+ /** The observed function. */
73
+ function_id: string;
74
+ /** Defaults to this worker's namespace (`engine::*` resolves to `default`). */
75
+ namespace?: string;
76
+ /**
77
+ * For the worker that hosts the function: what to set up and which calls
78
+ * to deliver (a table, a cron expression, a route). The engine validates
79
+ * them against the function's `args_format`.
80
+ */
81
+ args?: Record<string, unknown>;
82
+ /** Which calls reach the target, by `input`, `output`, `error`, `caller` and `metadata`; `{}` (or absent) = every call. */
83
+ filters?: Filter;
84
+ /** Which outcomes reach the target; default `'success'`. */
85
+ on?: 'success' | 'error' | 'complete';
86
+ /** What the envelope carries; default `['input', 'output', 'caller']`. */
87
+ capture?: Capture[];
88
+ /**
89
+ * What the target receives when iii delivers: the {@link Observed} envelope
90
+ * (default), the call's `input`, or its `output`.
91
+ */
92
+ deliver?: 'envelope' | 'input' | 'output';
93
+ }
94
+ /** The observer itself: its id, policy and metadata. */
95
+ interface ObserverOptions {
96
+ /**
97
+ * Default: a random UUID, stable across replays. The handle holds it until
98
+ * it is disposed: an `observe` of an id a handle of this client holds
99
+ * throws an {@link ObserveRejection} with code `OBSERVER_ID_CONFLICT` and
100
+ * sends nothing.
101
+ */
102
+ id?: string;
103
+ /** The observer is disposed after this many activations (`MAX_FIRES`). Default: unlimited. */
104
+ max_fires?: number;
105
+ /** The observer is disposed this many milliseconds after it is created (`EXPIRED`). Default: never. */
106
+ expires_in_ms?: number;
107
+ /**
108
+ * Activations running at once; further ones queue, then drop as `OVERFLOW`.
109
+ * Default: the engine's `observers.default_max_in_flight` (64).
110
+ */
111
+ max_in_flight?: number;
112
+ /** Delivered as the metadata sidecar of every activation. */
113
+ metadata?: Record<string, unknown>;
114
+ }
115
+ /** What `iii.observe` returns, synchronously. */
116
+ interface ObserverHandle {
117
+ readonly id: string;
118
+ readonly state: ObserverState;
119
+ /** Why the observer is in its state (`error`, `suspended`, `disposed`). */
120
+ readonly reason?: ObserveReason;
121
+ /**
122
+ * Resolves when the observer is `active`; rejects with an
123
+ * {@link ObserveRejection} carrying the code when it turns `error` or
124
+ * `disposed` first.
125
+ */
126
+ ready(): Promise<void>;
127
+ /**
128
+ * Calls `listener` on every state change, in order; returns the
129
+ * unsubscribe function. Listeners are called asynchronously (never on the
130
+ * connection's read path), so they may call the client.
131
+ */
132
+ onStateChange(listener: (state: ObserverState, reason?: ObserveReason) => void): () => void;
133
+ /**
134
+ * Removes the observer (`unobserve`). It is not replayed on reconnect.
135
+ * After the engine refused the `observe`, it sends nothing. It resolves at
136
+ * once in every case and awaits no answer from the engine, also when it is
137
+ * called before the answer to the `observe` arrives.
138
+ */
139
+ dispose(): Promise<void>;
140
+ }
141
+ /**
142
+ * One call of a function, as its host delivers it: what the handler was
143
+ * called with and what it returned (or threw). Observers observe `output`,
144
+ * the handler's return value.
145
+ */
146
+ interface Call<I = unknown, O = unknown> {
147
+ function_id: string;
148
+ invocation_id: string;
149
+ status: 'success' | 'error';
150
+ input: I;
151
+ /** The handler's return value: what observers observe. */
152
+ output?: O;
153
+ /** What the handler threw. */
154
+ error?: {
155
+ code: string;
156
+ message: string;
157
+ stacktrace?: string;
158
+ };
159
+ /** Who made the call; absent for a call made outside any handler. */
160
+ caller?: Caller;
161
+ metadata?: Record<string, unknown>;
162
+ }
163
+ /**
164
+ * An observer as the worker that hosts its function sees it (the hooks,
165
+ * `FunctionRef.observers()`): its args, filters, target, capture and `on`.
166
+ * Who observes, the observer's metadata and its policy stay with the engine.
167
+ */
168
+ interface Observer {
169
+ readonly id: string;
170
+ /** The observed function (one this worker hosts). */
171
+ readonly function_id: string;
172
+ /** The observer's args, validated against the function's `args_format` by the engine. */
173
+ readonly args: Record<string, unknown>;
174
+ /** The observer's filters, normalized. */
175
+ readonly filters: Filter;
176
+ /** The target function id. */
177
+ readonly target: string;
178
+ readonly on: 'success' | 'error' | 'complete';
179
+ readonly capture: Capture[];
180
+ /**
181
+ * Whether `call` reaches this observer: its `on` accepts the call's
182
+ * `status` (absent reads as `'success'`) and its filters match the call.
183
+ */
184
+ matches(call: Partial<Call>): boolean;
185
+ /**
186
+ * Resolves once the SDK has acked the observer. A call made after it
187
+ * resolves reaches an active observer, so a provider sends an observer its
188
+ * initial state from here: a call of its own function with
189
+ * `metadata: { for_observer: obs.id }`, which the function's match hook
190
+ * gives to this observer alone, delivered like every call. Rejects with an
191
+ * {@link ObserveRejection} when the observer is rejected first.
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * iii.onObserverAdded('tmux::on-changed', (obs) => {
196
+ * void obs
197
+ * .accepted()
198
+ * .then(() =>
199
+ * iii.call({
200
+ * function_id: 'tmux::on-changed',
201
+ * payload: stateFor(obs.args),
202
+ * metadata: { for_observer: obs.id },
203
+ * action: CallAction.Void(),
204
+ * }),
205
+ * )
206
+ * .catch(() => {
207
+ * // a rejected observer gets nothing
208
+ * })
209
+ * })
210
+ * iii.onObserverMatch('tmux::on-changed', (obs, call) =>
211
+ * call.metadata?.for_observer ? call.metadata.for_observer === obs.id : obs.args.session === call.input.session,
212
+ * )
213
+ * ```
214
+ */
215
+ accepted(): Promise<void>;
216
+ /**
217
+ * Late rejection of an active observer (e.g. after a config reload). It
218
+ * stops receiving calls at once, its `onObserverRemoved` hooks run, and it
219
+ * stays rejected across reconnects until the engine adds it again.
220
+ */
221
+ reject(code: string, message: string): void;
222
+ }
223
+ /**
224
+ * Runs when an observer of a function is added, before the SDK acks it.
225
+ * Throw to reject the observer: an {@link ObserveRejection} sets the code,
226
+ * anything else is `OBSERVE_REJECTED`; after 30 s it is rejected with
227
+ * `OWNER_TIMEOUT`.
228
+ */
229
+ type AddedHook = (obs: Observer) => void | Promise<void>;
230
+ /** Runs once for every accepted observer when it is removed. An error it throws is logged. */
231
+ type RemovedHook = (obs: Observer) => void | Promise<void>;
232
+ /** A match key, or several: an observer wants a call when they share one. */
233
+ type Key = string | readonly string[];
234
+ /** `onObserverMatch` as a predicate: whether this observer wants this call. */
235
+ type MatchPredicate<I = unknown, O = unknown> = (obs: Observer, call: Call<I, O>) => boolean;
236
+ /**
237
+ * `onObserverMatch` as keys: an observer wants a call when they share a key,
238
+ * and the SDK keeps an index instead of asking every observer.
239
+ */
240
+ interface MatchKeys<I = unknown, O = unknown> {
241
+ /** What this observer listens for, computed once when it is accepted. */
242
+ observer: (obs: Observer) => Key;
243
+ /** What this call is. */
244
+ call: (call: Call<I, O>) => Key;
245
+ }
246
+ /**
247
+ * Which observers want each call of a function (`onObserverMatch`). By
248
+ * default every observer wants every call. A predicate is asked once per
249
+ * active observer per call (a throw counts as no match). Keys are computed
250
+ * once per observer, when it is accepted, and once per call. The observers'
251
+ * `on`, filters, policy and `deliver` still apply. A host that sends one
252
+ * observer something of its own (its initial state) calls the function with
253
+ * `metadata: { for_observer: obs.id }`; the hook gives such a call to that
254
+ * observer alone (a predicate compares the ids; keys file each observer under
255
+ * `for_observer:<id>` too).
256
+ */
257
+ type MatchHook<I = unknown, O = unknown> = MatchPredicate<I, O> | MatchKeys<I, O>;
258
+ /**
259
+ * Delivers each call of a function itself (`onObserverDeliver`): it receives
260
+ * the call and the observers that matched it (a snapshot taken when the call
261
+ * started), and what it returns (or throws) is what the caller gets back. A
262
+ * thrown {@link ObserveRejection}, or the error of a call it made, reaches the
263
+ * caller with its code; any other error as `invocation_failed`. iii delivers
264
+ * nothing for that function; the hook calls through observers
265
+ * (`worker.call({ observer, payload })`) and applies their filters with
266
+ * `obs.matches(call)`. It runs inside the function's invocation, so the calls
267
+ * it makes have that invocation as their caller.
268
+ *
269
+ * Browsers have no `AsyncLocalStorage`: the hook runs in the invocation's
270
+ * scope up to its first `await`. A call it makes after one still has the
271
+ * invocation as its caller while that invocation is the only one running on
272
+ * the page; to be sure, read `iii.currentInvocation()` first and re-enter it
273
+ * with `iii.withInvocation(inv, fn)`. A call through an observer is routed to
274
+ * the observer's target either way.
275
+ */
276
+ type DeliverHook<I = unknown, O = unknown, R = O> = (call: Call<I, O>, observers: readonly Observer[]) => R | Promise<R>;
277
+ /**
278
+ * The invocation the current code runs in, in every handler, remote or
279
+ * local (`iii.currentInvocation()`).
280
+ *
281
+ * Browsers have no `AsyncLocalStorage`, so the SDK knows it only while the
282
+ * handler runs synchronously: up to its first `await`. To keep it across an
283
+ * `await`, read it first and re-enter it with `iii.withInvocation(inv, fn)`.
284
+ */
285
+ interface InvocationContext {
286
+ function_id: string;
287
+ invocation_id: string;
288
+ caller?: CallerInfo;
289
+ /** Set when this invocation is the activation of an observer's target. */
290
+ activation?: {
291
+ observer_id: string;
292
+ activation_id?: string;
293
+ };
294
+ observe_depth: number;
295
+ /**
296
+ * The W3C `traceparent` the invocation arrived with (or was called with,
297
+ * for a local call). Calls made inside the handler forward it. Browser SDK
298
+ * only: there is no OpenTelemetry context to carry it.
299
+ */
300
+ traceparent?: string;
301
+ /** The W3C `baggage` that came with `traceparent`. */
302
+ baggage?: string;
303
+ }
304
+ //#endregion
1
305
  //#region src/iii-types.d.ts
2
306
  declare enum MessageType {
3
307
  RegisterFunction = "registerfunction",
4
308
  UnregisterFunction = "unregisterfunction",
5
309
  InvokeFunction = "invokefunction",
6
310
  InvocationResult = "invocationresult",
7
- RegisterTriggerType = "registertriggertype",
8
- RegisterTrigger = "registertrigger",
9
- UnregisterTrigger = "unregistertrigger",
10
- UnregisterTriggerType = "unregistertriggertype",
11
- TriggerRegistrationResult = "triggerregistrationresult",
12
311
  RegistrationRejected = "registrationrejected",
13
312
  WorkerRegistered = "workerregistered",
14
313
  Reattach = "reattach",
@@ -20,17 +319,17 @@ declare enum MessageType {
20
319
  ObserveResult = "observeresult",
21
320
  /** Engine → observing worker: an observer's lifecycle transition. */
22
321
  ObserverStateChanged = "observerstatechanged",
23
- /** Engine → owner: the `registerfunction` ack, with the function's full observer set. */
322
+ /** Engine → host: the `registerfunction` ack, with the function's full observer set. */
24
323
  FunctionRegistered = "functionregistered",
25
- /** Engine → owner: one observer attached to a function this connection hosts. */
324
+ /** Engine → host: one observer attached to a function this connection hosts. */
26
325
  ObserverAdded = "observeradded",
27
- /** Engine → owner: one observer detached. */
326
+ /** Engine → host: one observer detached. */
28
327
  ObserverRemoved = "observerremoved",
29
- /** Owner → engine: accept (or reject) an added observer. */
328
+ /** Host → engine: accept (or reject) an added observer. */
30
329
  ObserverAck = "observerack",
31
- /** Owner → engine: matched local invocations and `obs.emit` events, batched. */
330
+ /** Host → engine: the calls of its functions that observers matched, batched. */
32
331
  InvocationsObserved = "invocationsobserved",
33
- /** Owner → engine: periodic counts of local invocations and report drops. */
332
+ /** Host → engine: periodic counts of local invocations and report drops. */
34
333
  LocalInvocationStats = "localinvocationstats"
35
334
  }
36
335
  /**
@@ -38,36 +337,6 @@ declare enum MessageType {
38
337
  * know instead of failing the frame.
39
338
  */
40
339
  type OpenEnum<T extends string> = T | (string & {});
41
- /** `RegisterFunction.observe`: the part of the observe hooks that travels. Callbacks never do. */
42
- type ObserveDescriptorWire = {
43
- /** `auto` (default) or `owner`. */delivery?: OpenEnum<'auto' | 'owner'>; /** Owner only: validates the observers' `args` in the engine (`INVALID_ARGS`). */
44
- args_format?: RegisterFunctionFormat; /** Phase 5 shim: accept old `registertrigger { trigger_type }` for this type. */
45
- legacy_trigger_type?: string; /** Default `true`; `false` makes every `observe` on it fail with `NOT_OBSERVABLE`. */
46
- allow?: boolean;
47
- };
48
- /** @deprecated Trigger types are replaced by functions with an observe descriptor (`RegisterFunctionMessage.observe`). */
49
- type RegisterTriggerTypeMessage = {
50
- message_type: MessageType.RegisterTriggerType; /** Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`). */
51
- id: string; /** Human-readable description of what this trigger type does. */
52
- description: string;
53
- };
54
- /** @deprecated Replaced by the `observe` message (`iii.observe`). */
55
- type RegisterTriggerMessage = {
56
- /** Wire discriminator; always `MessageType.RegisterTrigger`. */message_type: MessageType.RegisterTrigger; /** Unique trigger identifier, generated by the SDK during registration. */
57
- id: string; /** Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`). */
58
- type: string; /** ID of the function this trigger invokes when it fires. */
59
- function_id: string; /** Trigger-type-specific configuration, matching the shape the trigger type expects. */
60
- config: unknown;
61
- /**
62
- * Namespace the trigger's target function resolves in.
63
- *
64
- * Omitting it does not bind in the engine's default: `registerTrigger` fills
65
- * it from this worker's namespace, because the function a trigger names is
66
- * one this worker registered, and that landed in the worker's namespace. Name
67
- * another namespace, `default` included, to bind elsewhere.
68
- */
69
- namespace?: string;
70
- };
71
340
  type RegisterFunctionFormat = {
72
341
  /**
73
342
  * The name of the parameter
@@ -102,32 +371,56 @@ type RegisterFunctionMessage = {
102
371
  */
103
372
  id: string;
104
373
  /**
105
- * The description of the function
374
+ * Human-readable summary of the function, listed by discovery
375
+ * (`engine::functions::list`).
106
376
  */
107
377
  description?: string;
108
378
  /**
109
- * The request format of the function
379
+ * JSON Schema of the call's input.
110
380
  */
111
381
  request_format?: RegisterFunctionFormat;
112
382
  /**
113
- * The response format of the function
383
+ * JSON Schema of the handler's return value: what the function's observers
384
+ * observe.
114
385
  */
115
386
  response_format?: RegisterFunctionFormat;
387
+ /**
388
+ * Arbitrary metadata attached to the function, stored with it and listed by
389
+ * discovery (`engine::functions::list`). It is distinct from the per-call
390
+ * metadata a handler receives.
391
+ */
116
392
  metadata?: Record<string, unknown>;
117
393
  /**
118
- * The observe descriptor: how observers of this function are delivered.
119
- * Only these four fields travel; the hooks stay in the SDK.
394
+ * JSON Schema of the `args` an observer of this function passes. The
395
+ * engine validates every observer's args against it (`INVALID_ARGS`)
396
+ * before the added hooks run, and refuses a schema that is not valid
397
+ * (`INVALID_ARGS_FORMAT`). A function without it takes no args.
120
398
  */
121
- observe?: ObserveDescriptorWire;
399
+ args_format?: RegisterFunctionFormat;
400
+ /**
401
+ * Only this worker may call the function: the engine answers a call from
402
+ * any other connection with `FORBIDDEN`, and refuses the function as an
403
+ * observer's target. Any worker may observe it, and its observers receive
404
+ * every call this worker makes. For event sources, whose calls from
405
+ * anywhere else would be forged events. This worker's own calls pass the
406
+ * input and the result by reference: the handler and hooks treat both as
407
+ * read-only. Default `false`; sent only when `true`.
408
+ */
409
+ private?: boolean;
410
+ /**
411
+ * `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one
412
+ * whose payloads carry credentials. Default `true`; sent only when `false`.
413
+ */
414
+ observable?: boolean;
122
415
  };
123
416
  /**
124
- * Routing action for {@link TriggerRequest}. Determines how the engine
417
+ * Routing action for {@link CallRequest}. Determines how the engine
125
418
  * handles the invocation.
126
419
  *
127
420
  * - `enqueue`: Routes through a named queue for async processing.
128
421
  * - `void`: Fire-and-forget, no response.
129
422
  */
130
- type TriggerAction = {
423
+ type CallAction = {
131
424
  type: 'enqueue';
132
425
  queue: string;
133
426
  } | {
@@ -160,9 +453,7 @@ type AuthResult = {
160
453
  */
161
454
  namespaces?: Record<string, string[]>; /** Additional function IDs to allow beyond the `expose_functions` config, in the `default` namespace only. Put per-namespace grants in `namespaces`. Defaults to `[]` if omitted. */
162
455
  allowed_functions?: string[]; /** Function IDs to deny even if they match `expose_functions`. Takes precedence over allowed. Defaults to `[]` if omitted. */
163
- forbidden_functions?: string[]; /** Trigger type IDs the worker may register triggers for. When omitted, all types are allowed. */
164
- allowed_trigger_types?: string[]; /** Whether the worker may register new trigger types. Defaults to `false` if omitted. */
165
- allow_trigger_type_registration?: boolean; /** Whether the worker may register new functions. Defaults to `true` if omitted. */
456
+ forbidden_functions?: string[]; /** Whether the worker may register new functions. Defaults to `true` if omitted. */
166
457
  allow_function_registration?: boolean; /** Arbitrary context forwarded to the middleware function on every invocation. Defaults to `{}` if omitted. */
167
458
  context?: Record<string, unknown>; /** Optional prefix applied to all function IDs registered by this worker. */
168
459
  function_registration_prefix?: string;
@@ -175,7 +466,7 @@ type AuthResult = {
175
466
  type MiddlewareFunctionInput = {
176
467
  /** ID of the function being invoked. */function_id: string; /** Payload sent by the caller. */
177
468
  payload: Record<string, unknown>; /** Routing action, if any. */
178
- action?: TriggerAction; /** Auth context returned by the auth function for this session. */
469
+ action?: CallAction; /** Auth context returned by the auth function for this session. */
179
470
  context: Record<string, unknown>;
180
471
  /**
181
472
  * Target namespace the invoke addressed; forward the call here to stay in the
@@ -183,56 +474,6 @@ type MiddlewareFunctionInput = {
183
474
  */
184
475
  namespace?: string;
185
476
  };
186
- /**
187
- * Input passed to the `on_trigger_type_registration_function_id` hook
188
- * when a worker attempts to register a new trigger type through the RBAC port.
189
- * Return an {@link OnTriggerTypeRegistrationResult} with the (possibly mapped)
190
- * fields, or throw to deny the registration.
191
- */
192
- type OnTriggerTypeRegistrationInput = {
193
- /** ID of the trigger type being registered. */trigger_type_id: string; /** Human-readable description of the trigger type. */
194
- description: string; /** Auth context from `AuthResult.context` for this session. */
195
- context: Record<string, unknown>;
196
- };
197
- /**
198
- * Result returned from the `on_trigger_type_registration_function_id` hook.
199
- * All fields are optional; omitted fields keep the original value from the
200
- * registration request.
201
- */
202
- type OnTriggerTypeRegistrationResult = {
203
- /** Mapped trigger type ID. */trigger_type_id?: string; /** Mapped description. */
204
- description?: string;
205
- };
206
- /**
207
- * Input passed to the `on_trigger_registration_function_id` hook
208
- * when a worker attempts to register a trigger through the RBAC port.
209
- * Return an {@link OnTriggerRegistrationResult} with the (possibly mapped)
210
- * fields, or throw to deny the registration.
211
- */
212
- type OnTriggerRegistrationInput = {
213
- /** ID of the trigger being registered. */trigger_id: string; /** Trigger type identifier. */
214
- trigger_type: string; /** ID of the function this trigger is bound to. */
215
- function_id: string; /** Trigger-specific configuration. */
216
- config: unknown;
217
- /**
218
- * Namespace the trigger's target resolves in (explicit, or `default` when
219
- * absent). The same id can exist in several namespaces, so the hook needs this
220
- * to authorize per target namespace.
221
- */
222
- namespace?: string; /** Auth context from `AuthResult.context` for this session. */
223
- context: Record<string, unknown>;
224
- };
225
- /**
226
- * Result returned from the `on_trigger_registration_function_id` hook.
227
- * All fields are optional; omitted fields keep the original value from the
228
- * registration request.
229
- */
230
- type OnTriggerRegistrationResult = {
231
- /** Mapped trigger ID. */trigger_id?: string; /** Mapped trigger type. */
232
- trigger_type?: string; /** Mapped function ID. */
233
- function_id?: string; /** Mapped trigger configuration. */
234
- config?: unknown;
235
- };
236
477
  /**
237
478
  * Input passed to the `on_function_registration_function_id` hook
238
479
  * when a worker attempts to register a function through the RBAC port.
@@ -247,7 +488,10 @@ type OnFunctionRegistrationInput = {
247
488
  * Namespace the function registers in. The same id can exist in several
248
489
  * namespaces, so the hook needs this to authorize per namespace.
249
490
  */
250
- namespace?: string; /** Auth context from `AuthResult.context` for this session. */
491
+ namespace?: string; /** Only the registering worker may call the function; always sent. */
492
+ private: boolean; /** `false`: nobody may observe the function; always sent. */
493
+ observable: boolean; /** JSON Schema of the args its observers pass; sent when the registration sets it. */
494
+ args_format?: Record<string, unknown>; /** Auth context from `AuthResult.context` for this session. */
251
495
  context: Record<string, unknown>;
252
496
  };
253
497
  /**
@@ -258,29 +502,34 @@ type OnFunctionRegistrationInput = {
258
502
  type OnFunctionRegistrationResult = {
259
503
  /** Mapped function ID. */function_id?: string; /** Mapped description. */
260
504
  description?: string; /** Mapped metadata. */
261
- metadata?: Record<string, unknown>;
505
+ metadata?: Record<string, unknown>; /** Replaces the registration's `private`. */
506
+ private?: boolean; /** Replaces the registration's `observable`. */
507
+ observable?: boolean; /** Replaces the registration's `args_format`. */
508
+ args_format?: Record<string, unknown>;
262
509
  };
263
510
  /**
264
- * Result returned when a function is invoked with `TriggerAction.Enqueue`.
511
+ * Result returned when a function is called with `CallAction.Enqueue`.
265
512
  */
266
513
  type EnqueueResult = {
267
514
  /** Unique receipt ID for the enqueued message. */messageReceiptId: string;
268
515
  };
269
516
  /**
270
- * Request object passed to {@link ISdk.trigger}.
517
+ * Request object passed to {@link ISdk.call}: a function by id, or the target
518
+ * of an observer.
271
519
  *
272
520
  * @typeParam TInput - Type of the payload.
273
521
  */
274
- type TriggerRequest<TInput = unknown> = {
275
- /** ID of the function to invoke. */function_id: string; /** Input data passed to the function. */
276
- payload: TInput; /** Sets how the trigger is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `TriggerAction.Enqueue()`, `TriggerAction.Void()`). */
277
- action?: TriggerAction; /** Override the default invocation timeout, in milliseconds. */
522
+ type CallRequest<TInput = unknown> = {
523
+ /** ID of the function to invoke. */function_id: string;
524
+ observer?: never; /** Input data passed to the function. */
525
+ payload: TInput; /** Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `CallAction.Enqueue()`, `CallAction.Void()`). */
526
+ action?: CallAction; /** Override the default invocation timeout, in milliseconds. */
278
527
  timeoutMs?: number; /** Namespace to route this invocation to. Omit to inherit this worker's; say `default` to reach the engine's from a namespaced worker. */
279
528
  namespace?: string;
280
529
  /**
281
- * Per-invocation metadata (any JSON). Travels beside the payload: the
530
+ * Per-invocation metadata (any JSON value). Travels beside the payload: the
282
531
  * handler receives it as its second argument, and observer filters read it
283
- * as `metadata.*`.
532
+ * as `metadata.*`. `null` is the same as no metadata.
284
533
  */
285
534
  metadata?: unknown;
286
535
  /**
@@ -298,7 +547,26 @@ type TriggerRequest<TInput = unknown> = {
298
547
  * engine. Tests use it, and so do callers that rely on engine-side effects.
299
548
  */
300
549
  dispatch?: 'auto' | 'remote';
550
+ } | {
551
+ /**
552
+ * An observer of a function this worker hosts: the call runs the
553
+ * observer's target, with the observer's policy, metadata and loop
554
+ * guard. Only the host of the observed function may call through it
555
+ * (`NOT_FUNCTION_OWNER`).
556
+ */
557
+ observer: Observer;
558
+ function_id?: never; /** Input data passed to the target, as given (the observer's filters are not applied). */
559
+ payload: TInput; /** `CallAction.Void()` for fire-and-forget. Omit for a synchronous request/response. */
560
+ action?: CallAction; /** Override the default invocation timeout, in milliseconds. */
561
+ timeoutMs?: number;
562
+ /**
563
+ * A call through an observer takes no metadata: its target receives the
564
+ * observer's registration metadata. `call` refuses one that names it.
565
+ */
566
+ metadata?: never;
301
567
  };
568
+ /** @deprecated Use {@link CallRequest}, the same type. */
569
+ type TriggerRequest<TInput = unknown> = CallRequest<TInput>;
302
570
  /**
303
571
  * Serializable reference to one end of a streaming channel. Can be included
304
572
  * in invocation payloads to pass channel endpoints between workers.
@@ -381,6 +649,7 @@ declare class ChannelWriter {
381
649
  declare class ChannelReader {
382
650
  private ws;
383
651
  private connected;
652
+ private closedByCaller;
384
653
  private readonly messageCallbacks;
385
654
  private readonly binaryCallbacks;
386
655
  private readonly url;
@@ -390,7 +659,12 @@ declare class ChannelReader {
390
659
  onMessage(callback: (msg: string) => void): void;
391
660
  /** Register a callback to receive binary data from the channel. */
392
661
  onBinary(callback: (data: Uint8Array) => void): void;
393
- /** Read all binary data from the channel until it closes. */
662
+ /**
663
+ * Read all binary data from the channel until it closes.
664
+ *
665
+ * Rejects with an `Error` carrying the close `code` and `reason` when the
666
+ * channel ends abnormally (the writer aborted or the connection was lost).
667
+ */
394
668
  readAll(): Promise<Uint8Array>;
395
669
  /** Close the channel reader. */
396
670
  close(): void;
@@ -426,14 +700,13 @@ type InvocationErrorInit = {
426
700
  };
427
701
  /**
428
702
  * An error the SDK raises itself for an invocation, with a machine-readable
429
- * `code`: observe delivery errors (`NOT_OWNER_DELIVERED`,
430
- * `OBSERVER_NOT_ACTIVE`, `FILTERS_NOT_MATCHED`) and an invalid observe
431
- * descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.
703
+ * `code`: `LOCAL_DEPTH_EXCEEDED` (a local call nested too deep while the
704
+ * socket is closed) and `payload_too_large`. Mirrors the Node SDK.
432
705
  *
433
- * A call the engine answers with an error still rejects with the engine's
434
- * error body (`{ code, message, stacktrace? }`), as in earlier releases, and
435
- * so does a locally dispatched call whose handler throws: both paths reject
436
- * with the same value.
706
+ * A call the engine answers with an error rejects with the engine's error
707
+ * body (`{ code, message, stacktrace? }`), and so does a locally dispatched
708
+ * call whose handler or deliver hook throws: both paths reject with the same
709
+ * value.
437
710
  */
438
711
  declare class InvocationError extends Error {
439
712
  readonly code: string;
@@ -449,11 +722,11 @@ declare class InvocationError extends Error {
449
722
  *
450
723
  * @example
451
724
  * ```typescript
452
- * onObserverAdded(obs) {
725
+ * iii.onObserverAdded('cron::on-tick', (obs) => {
453
726
  * if (!isValidCron(obs.args.expression)) {
454
727
  * throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
455
728
  * }
456
- * }
729
+ * })
457
730
  * ```
458
731
  */
459
732
  declare class ObserveRejection extends Error {
@@ -465,29 +738,29 @@ declare class ObserveRejection extends Error {
465
738
  /**
466
739
  * Constants for the III module.
467
740
  */
468
- /**
469
- * Engine function paths for internal operations.
470
- *
471
- * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
472
- * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
473
- * cover trigger INSTANCES (subscriber rows). The old
474
- * `engine::trigger-types::list` builtin has been removed and is now
475
- * served by `engine::triggers::list`.
476
- */
741
+ /** Engine function paths for internal operations. */
477
742
  declare const EngineFunctions: {
478
743
  readonly LIST_FUNCTIONS: "engine::functions::list";
479
744
  readonly INFO_FUNCTIONS: "engine::functions::info";
480
745
  readonly LIST_WORKERS: "engine::workers::list";
481
746
  readonly INFO_WORKERS: "engine::workers::info";
482
- readonly LIST_TRIGGERS: "engine::triggers::list";
483
- readonly INFO_TRIGGERS: "engine::triggers::info";
484
- readonly LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list";
485
- readonly INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info";
486
747
  readonly REGISTER_WORKER: "engine::workers::register";
487
748
  };
488
- /** Engine trigger types */
489
- declare const EngineTriggers: {
490
- readonly FUNCTIONS_AVAILABLE: "engine::functions-available";
749
+ /**
750
+ * The event sources the engine hosts: private functions whose handler
751
+ * returns the event, observed with `iii.observe(EngineSources.X, target)`.
752
+ * None takes args; filter on the event (`input`) instead.
753
+ */
754
+ declare const EngineSources: {
755
+ /** A function was registered or unregistered; each row carries `observer_count`. */readonly FUNCTIONS_CHANGED: "engine::on-functions-changed"; /** A worker connected or left. */
756
+ readonly WORKERS_CHANGED: "engine::on-workers-changed"; /** An observer changed state: `{ observer_id, function_id, target, state, reason? }`. */
757
+ readonly OBSERVERS_CHANGED: "engine::on-observers-changed"; /** A log record. */
758
+ readonly LOG: "observability::on-log"; /** A finished span. */
759
+ readonly SPAN: "observability::on-span"; /** The engine's configuration was reloaded. */
760
+ readonly CONFIGURATION_UPDATED: "configuration::on-updated"; /** A stream item changed; filter on `input.stream_name`, `input.group_id`. */
761
+ readonly STREAM_CHANGED: "stream::on-changed"; /** A client joined a stream group. */
762
+ readonly STREAM_JOIN: "stream::on-join"; /** A client left a stream group. */
763
+ readonly STREAM_LEAVE: "stream::on-leave";
491
764
  };
492
765
  /** Connection state for the III WebSocket */
493
766
  type IIIConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
@@ -505,306 +778,12 @@ interface IIIReconnectionConfig {
505
778
  maxRetries: number;
506
779
  }
507
780
  //#endregion
508
- //#region src/observe-types.d.ts
509
- /** What an observer ships to its target. Default `['input', 'output', 'caller']`. */
510
- type Capture = 'input' | 'output' | 'error' | 'caller' | 'metadata';
781
+ //#region src/types.d.ts
511
782
  /**
512
- * An observer's lifecycle: `pending` (no owner yet, waiting for the owner's
513
- * ack, or no target yet) → `active` or `error`; `suspended` while its worker
514
- * or target is away; `disposed` at the end.
515
- */
516
- type ObserverState = 'pending' | 'active' | 'suspended' | 'error' | 'disposed';
517
- /**
518
- * A declarative filter over `input`, `output`, `error`, `caller` and
519
- * `metadata`, with explicit operators only:
520
- * `{ 'input.amount': { $gte: 500 } }`. See the filter language reference.
521
- */
522
- type Filter = Record<string, unknown>;
523
- /** The right side of `iii.observe`: a registered function. */
524
- type Target = string | {
525
- function_id: string;
526
- namespace?: string;
527
- };
528
- /** A state reason or an error: a machine-readable code and a message. */
529
- type ObserveReason = {
530
- code: string;
531
- message: string;
532
- };
533
- /**
534
- * Who started an invocation: the worker (`worker_id` / `worker_name`, stamped
535
- * by the engine), and the function and invocation the call was made from.
536
- */
537
- interface Caller {
538
- /** Absent on activations, whose caller is the engine (`worker_name: 'iii-engine'`). */
539
- worker_id?: string;
540
- worker_name?: string;
541
- /** The handler the call was made from; absent for top-level calls. */
542
- function_id?: string;
543
- invocation_id?: string;
544
- /** The caller of that handler, one level only. */
545
- parent?: Omit<Caller, 'parent'>;
546
- }
547
- /**
548
- * A caller as the SDK knows it: every field may be missing (a top-level call
549
- * has no function; a call made before `WorkerRegistered` has no worker id).
550
- */
551
- type CallerInfo = Partial<Omit<Caller, 'parent'>> & {
552
- parent?: Partial<Omit<Caller, 'parent'>>;
553
- };
554
- /**
555
- * What the target of an auto observer (or of `obs.emit`) receives with
556
- * `deliver: 'envelope'` (the default). Fields not in the observer's
557
- * `capture` are absent.
558
- */
559
- interface Observed<I = unknown, O = unknown> {
560
- observer_id: string;
561
- activation_id: string;
562
- function_id: string;
563
- namespace: string;
564
- invocation_id: string;
565
- status: 'success' | 'error';
566
- input?: I;
567
- output?: O;
568
- error?: {
569
- code: string;
570
- message: string;
571
- };
572
- caller?: Caller;
573
- metadata?: Record<string, unknown>;
574
- started_at_ms: number;
575
- duration_ms: number;
576
- }
577
- /** The left side of `iii.observe`: what is observed. */
578
- interface ObserveSource {
579
- /** The observed function. */
580
- function_id: string;
581
- /** Defaults to this worker's namespace (`engine::*` resolves to `default`). */
582
- namespace?: string;
583
- /** Owner-delivered functions only: for the owner; validated against its `args_format`. */
584
- args?: Record<string, unknown>;
585
- /** Which events reach the target; `{}` (or absent) = every event. */
586
- filters?: Filter;
587
- /** Auto only; default `'success'`. */
588
- on?: 'success' | 'error' | 'complete';
589
- /** Auto and `obs.emit`; default `['input', 'output', 'caller']`. */
590
- capture?: Capture[];
591
- /** Auto and `obs.emit`; default `'envelope'`. */
592
- deliver?: 'envelope' | 'input' | 'output';
593
- }
594
- /** The observer itself: its id, policy and metadata. */
595
- interface ObserverOptions {
596
- /** Default: a random UUID, stable across replays. */
597
- id?: string;
598
- /** The observer is disposed after this many activations (`MAX_FIRES`). Default: unlimited. */
599
- max_fires?: number;
600
- /** The observer is disposed this many milliseconds after it is created (`EXPIRED`). Default: never. */
601
- expires_in_ms?: number;
602
- /**
603
- * Activations running at once; further ones queue, then drop as `OVERFLOW`.
604
- * Default: the engine's `observers.default_max_in_flight` (64).
605
- */
606
- max_in_flight?: number;
607
- /** Delivered as the metadata sidecar of every activation. */
608
- metadata?: Record<string, unknown>;
609
- }
610
- /** What `iii.observe` returns, synchronously. */
611
- interface ObserverHandle {
612
- readonly id: string;
613
- readonly state: ObserverState;
614
- /** Why the observer is in its state (`error`, `suspended`, `disposed`). */
615
- readonly reason?: ObserveReason;
616
- /**
617
- * Resolves when the observer is `active`; rejects with an
618
- * {@link ObserveRejection} carrying the code when it turns `error` or
619
- * `disposed` first.
620
- */
621
- ready(): Promise<void>;
622
- /**
623
- * Calls `listener` on every state change, in order; returns the
624
- * unsubscribe function. Listeners are called asynchronously (never on the
625
- * connection's read path), so they may call the client.
626
- */
627
- onStateChange(listener: (state: ObserverState, reason?: ObserveReason) => void): () => void;
628
- /** Removes the observer (`unobserve`). It is not replayed on reconnect. */
629
- dispose(): Promise<void>;
630
- }
631
- /** The document an observer's filters read (filters.md §1). */
632
- type ObserveDoc = {
633
- input?: unknown;
634
- output?: unknown;
635
- error?: unknown;
636
- caller?: CallerInfo;
637
- metadata?: unknown;
638
- };
639
- /**
640
- * An observer as the function's owner sees it (`onObserverAdded`,
641
- * `FunctionRef.observers()`): its args, filters, target, capture and `on`.
642
- * Never its metadata, policy or the observing worker.
643
- */
644
- interface Observer {
645
- readonly id: string;
646
- /** The observed function (the one this worker hosts). */
647
- readonly function_id: string;
648
- /** The observer's args, validated against `args_format` by the engine. */
649
- readonly args: Record<string, unknown>;
650
- /** The observer's filters, normalized; the SDK applies them in `emit` / `call`. */
651
- readonly filters: Filter;
652
- /** The target function id. */
653
- readonly target: string;
654
- readonly capture: Capture[];
655
- /** Auto only. */
656
- readonly on: 'success' | 'error' | 'complete';
657
- /** Set when the engine's legacy shim created the observer from an old `registerTrigger`. */
658
- readonly legacy?: {
659
- trigger_type: string;
660
- config: unknown;
661
- };
662
- /** Evaluates the observer's filters on a document. */
663
- matches(doc: ObserveDoc): boolean;
664
- /**
665
- * Owner delivery, fire-and-forget: hands `event` to this observer. Returns
666
- * `false` and sends nothing when its filters reject the event or the
667
- * observer is no longer active (removed or rejected meanwhile). Throws
668
- * `NOT_OWNER_DELIVERED` on an auto function.
669
- */
670
- emit(event: unknown): boolean;
671
- /**
672
- * Owner delivery, request/response: invokes the target with `payload` and
673
- * resolves with its result. Rejects with `FILTERS_NOT_MATCHED` (nothing is
674
- * sent) when the filters reject the payload, and with `OBSERVER_NOT_ACTIVE`
675
- * when the observer is no longer active.
676
- */
677
- call<R = unknown>(payload: unknown, opts?: {
678
- timeoutMs?: number;
679
- metadata?: never;
680
- }): Promise<R>;
681
- /**
682
- * Late rejection of an active observer (e.g. after a config reload). It
683
- * stops receiving events at once, and stays rejected across reconnects
684
- * until the engine adds it again.
685
- */
686
- reject(code: string, message: string): void;
687
- }
688
- /**
689
- * The `observe` option of `registerFunction`: how the function's observers
690
- * are delivered, and the callbacks that run when one is added or removed.
691
- *
692
- * The callbacks of one function run one at a time, in revision order, with
693
- * one exception: a callback still running after 30 s is treated as failed
694
- * (`OWNER_TIMEOUT`) and the next one starts, so a hung callback cannot stall
695
- * its function forever. It may then overlap with the callbacks after it, and
696
- * if a timed-out `onObserverAdded` completes later, `onObserverRemoved` runs
697
- * for that observer.
698
- */
699
- interface ObserveHooks {
700
- /**
701
- * `auto` (default): every invocation is offered to every observer.
702
- * `owner`: the handler hands each event to the observers it belongs to,
703
- * with `obs.emit` / `obs.call`.
704
- */
705
- delivery?: 'auto' | 'owner';
706
- /** Owner only: JSON Schema of the observers' `args` (the engine answers `INVALID_ARGS`). */
707
- args_format?: RegisterFunctionFormat;
708
- /** Accept old `registerTrigger({ type })` calls for this trigger type. */
709
- legacy_trigger_type?: string;
710
- /** Default `true`; `false` refuses every observer (`NOT_OBSERVABLE`). */
711
- allow?: boolean;
712
- /**
713
- * Runs once per added observer, before the SDK acks it. Throw to reject it
714
- * (an {@link ObserveRejection} sets the code, anything else is
715
- * `OBSERVE_REJECTED`); after 30 s it is rejected with `OWNER_TIMEOUT`.
716
- */
717
- onObserverAdded?(obs: Observer): void | Promise<void>;
718
- /** Runs once per removed observer. Cannot fail: errors are logged. */
719
- onObserverRemoved?(obs: Observer): void | Promise<void>;
720
- }
721
- /**
722
- * The invocation the current code runs in, in every handler, remote or
723
- * local (`iii.currentInvocation()`).
724
- *
725
- * Browsers have no `AsyncLocalStorage`, so the SDK knows it only while the
726
- * handler runs synchronously: up to its first `await`. To keep it across an
727
- * `await`, read it first and re-enter it with `iii.withInvocation(inv, fn)`.
728
- */
729
- interface InvocationContext {
730
- function_id: string;
731
- invocation_id: string;
732
- caller?: CallerInfo;
733
- /** Set when this invocation is the activation of an observer's target. */
734
- activation?: {
735
- observer_id: string;
736
- activation_id?: string;
737
- };
738
- observe_depth: number;
739
- /**
740
- * The W3C `traceparent` the invocation arrived with (or was triggered with,
741
- * for a local call). Calls made inside the handler forward it. Browser SDK
742
- * only: there is no OpenTelemetry context to carry it.
743
- */
744
- traceparent?: string;
745
- /** The W3C `baggage` that came with `traceparent`. */
746
- baggage?: string;
747
- }
748
- //#endregion
749
- //#region src/triggers.d.ts
750
- /**
751
- * Configuration passed to a trigger handler when a trigger instance is
752
- * registered or unregistered.
753
- *
754
- * @deprecated Replaced by the `Observer` an `onObserverAdded` hook
755
- * receives (`{ id, args, filters, target }`). Migration guide:
756
- * https://iii.dev/docs/upgrading/from-0-24-x
757
- *
758
- * @typeParam TConfig - Type of the trigger-specific configuration.
759
- */
760
- type TriggerConfig<TConfig> = {
761
- /** Trigger instance ID. */id: string; /** Function to invoke when the trigger fires. */
762
- function_id: string; /** Trigger-specific configuration. */
763
- config: TConfig;
764
- /**
765
- * Namespace the trigger's target `function_id` resolves in. A provider that
766
- * stores this config and later fires the target must pass this namespace, or
767
- * it fires in `default`.
768
- *
769
- * Omitted, it is filled in with the registering worker's namespace. A trigger
770
- * names a function, and a worker's functions land in the worker's namespace,
771
- * so defaulting anywhere else registers a trigger that resolves nothing. Name
772
- * another namespace, `default` included, to target one.
773
- */
774
- namespace?: string;
775
- };
776
- /**
777
- * Handler interface for custom trigger types. Passed to
778
- * `ISdk.registerTriggerType`.
779
- *
780
- * @deprecated Replaced by `ObserveHooks` (`onObserverAdded` /
781
- * `onObserverRemoved`) on `registerFunction`. Migration guide:
782
- * https://iii.dev/docs/upgrading/from-0-24-x
783
- *
784
- * @typeParam TConfig - Type of the trigger-specific configuration.
785
- *
786
- * @example
787
- * ```typescript
788
- * const handler: TriggerHandler<{ interval: number }> = {
789
- * async registerTrigger({ id, function_id, config }) {
790
- * // Set up periodic invocation
791
- * },
792
- * async unregisterTrigger({ id, function_id, config }) {
793
- * // Clean up
794
- * },
795
- * }
796
- * ```
797
- */
798
- type TriggerHandler<TConfig> = {
799
- /** Called when a trigger instance is registered. */registerTrigger(config: TriggerConfig<TConfig>): Promise<void>; /** Called when a trigger instance is unregistered. */
800
- unregisterTrigger(config: TriggerConfig<TConfig>): Promise<void>;
801
- };
802
- //#endregion
803
- //#region src/types.d.ts
804
- /**
805
- * Async function handler for a registered function. Receives the invocation
806
- * payload and its metadata (`TriggerRequest.metadata` of the call, or an
807
- * observer's metadata sidecar on an activation) and returns the result.
783
+ * Handler of a registered function. Receives the invocation payload and its
784
+ * metadata (`CallRequest.metadata` of the call, or an observer's metadata
785
+ * sidecar on an activation) and returns the result (or a promise of it). The
786
+ * return value is what the function's observers observe.
808
787
  *
809
788
  * @typeParam TInput - Type of the invocation payload.
810
789
  * @typeParam TOutput - Type of the return value.
@@ -815,22 +794,23 @@ type TriggerHandler<TConfig> = {
815
794
  * async (data) => ({ message: `Hello, ${data.name}!` })
816
795
  * ```
817
796
  */
818
- type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput, metadata?: unknown) => Promise<TOutput>;
819
- /** @deprecated Use `iii.observe(source, target, options)` and its {@link ObserveSource}. */
820
- type RegisterTriggerInput = Omit<RegisterTriggerMessage, 'message_type' | 'id'>;
797
+ type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput, metadata?: unknown) => TOutput | Promise<TOutput>;
821
798
  type RegisterFunctionInput = Omit<RegisterFunctionMessage, 'message_type'>;
822
799
  /**
823
- * Options of {@link ISdk.registerFunction}: description, request/response
824
- * formats, metadata, and the observe hooks.
800
+ * Options of {@link ISdk.registerFunction}: what describes the function to
801
+ * the engine (description, formats, metadata, `args_format`, `private`,
802
+ * `observable`), and what the SDK does with it (`standby`, `localDispatch`).
803
+ * What the worker does when the function is observed is set with hooks.
825
804
  */
826
- type RegisterFunctionOptions = Omit<RegisterFunctionMessage, 'message_type' | 'id' | 'observe'> & {
805
+ type RegisterFunctionOptions = Omit<RegisterFunctionMessage, 'message_type' | 'id'> & {
827
806
  /**
828
- * Makes the function observable on its own terms: owner delivery
829
- * (`delivery: 'owner'`, `args_format`), and callbacks when an observer is
830
- * added or removed. Without it the function is still observable (auto
831
- * delivery, no args).
807
+ * When another connection already hosts the id
808
+ * (`FUNCTION_NAMESPACE_CONFLICT`), wait and take over when it leaves: the
809
+ * registration is retried every second (±20 %) until the engine accepts it
810
+ * or the function is unregistered, and the hooks run for every observer
811
+ * once the engine confirms it (default `false`).
832
812
  */
833
- observe?: ObserveHooks;
813
+ standby?: boolean;
834
814
  /**
835
815
  * Calls this worker makes to its own function run in-process once the
836
816
  * engine confirmed it (default `true`). Set `false` for a handler that must
@@ -838,40 +818,36 @@ type RegisterFunctionOptions = Omit<RegisterFunctionMessage, 'message_type' | 'i
838
818
  */
839
819
  localDispatch?: boolean;
840
820
  };
841
- /** @deprecated Register a function with an observe descriptor instead. */
842
- type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, 'message_type'>;
843
821
  interface ISdk {
844
822
  /**
845
- * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.
823
+ * Registers a new function with a local handler that runs in the browser
824
+ * session. HTTP invocation configs are a Node.js SDK feature. The handler's
825
+ * return value is what the function's observers observe; an event source's
826
+ * handler returns the event it is called with.
846
827
  *
847
- * @deprecated Use {@link ISdk.observe} instead: `iii.observe({ function_id, args, filters }, target, { metadata })`.
848
- * Logs a warning once per page. The http, cron, queue, state, stream, pubsub and database workers
849
- * still publish trigger types: keep using `registerTrigger` for them until they ship source functions.
850
- * Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
851
- * <!-- docs:expand-params -->
852
- * @param trigger - The trigger to register
853
- * @returns A trigger object that can be used to unregister the trigger
828
+ * Every call of the function, local or routed, runs the handler and then
829
+ * goes to the observers that want it (`onObserverMatch`; by default all of
830
+ * them): the function's `onObserverDeliver` hook delivers it, or iii does,
831
+ * to those whose `on` and filters match. iii evaluates `on` and filters
832
+ * where the call is: the engine for a call it routes to this worker, and
833
+ * the SDK for a call this worker makes to its own function in-process,
834
+ * through an index of the filters' equality conditions. What the worker
835
+ * does when the function is observed is set with the hooks (`onObserverAdded`,
836
+ * `onObserverRemoved`, `onObserverMatch`, `onObserverDeliver`), by id or on
837
+ * the returned {@link FunctionRef}. The SDK acks no observer before this
838
+ * call returns, so a hook set by id before it, chained on its result, or
839
+ * set later in the same synchronous block runs for every observer.
854
840
  *
855
- * @example
856
- * ```typescript
857
- * const trigger = worker.registerTrigger({
858
- * type: 'cron',
859
- * function_id: 'my-service::process-batch',
860
- * config: { expression: '0 *\/5 * * * * *' },
861
- * })
841
+ * A function that sets `args_format`, `private: true`, `observable: false`,
842
+ * an `onObserverMatch` hook or an `onObserverDeliver` hook needs an engine
843
+ * with `observe.v2`: it is registered once the connection's engine
844
+ * advertised it, and against an older engine it stays unregistered (logged
845
+ * once, `UNSUPPORTED`).
862
846
  *
863
- * // Later, remove the trigger
864
- * trigger.unregister()
865
- * ```
866
- */
867
- registerTrigger(trigger: RegisterTriggerInput): Trigger;
868
- /**
869
- * Registers a new function with a local async handler that runs in the
870
- * browser session. HTTP invocation configs are a Node.js SDK feature.
871
847
  * @param functionId - Unique function identifier
872
- * @param handler - Async handler executed when the function is invoked
873
- * @param options - Optional function registration options (description, request/response formats, metadata)
874
- * @returns A handle that can be used to unregister the function
848
+ * @param handler - Handler executed when the function is invoked
849
+ * @param options - Optional {@link RegisterFunctionOptions}: description, request/response formats, metadata, `args_format`, `private`, `observable`, `standby`, `localDispatch`
850
+ * @returns A {@link FunctionRef}: the hook methods with the id filled in, and `unregister()`
875
851
  *
876
852
  * @example
877
853
  * ```typescript
@@ -882,22 +858,30 @@ interface ISdk {
882
858
  * { description: 'Returns a greeting' },
883
859
  * )
884
860
  *
861
+ * // An event source: observed by everyone, called only by this page, set up
862
+ * // for each observer by its args
863
+ * worker
864
+ * .registerFunction('ui::on-click', (click: Click) => click, { args_format: ClickArgs, private: true })
865
+ * .onObserverAdded((obs) => targets.retain(obs.args.selector as string))
866
+ * .onObserverRemoved((obs) => targets.release(obs.args.selector as string))
867
+ *
885
868
  * // Later, remove the function
886
869
  * ref.unregister()
887
870
  * ```
888
871
  */
889
- registerFunction(functionId: string, handler: RemoteFunctionHandler, options?: RegisterFunctionOptions): FunctionRef;
872
+ registerFunction<I = any, O = any>(functionId: string, handler: RemoteFunctionHandler<I, O>, options?: RegisterFunctionOptions): FunctionRef<I, O>;
890
873
  /**
891
- * Invokes a function using a request object.
874
+ * Invokes a function: by id, or the target of an observer of a function
875
+ * this worker hosts (`{ observer, payload }`).
892
876
  * <!-- docs:expand-params -->
893
877
  *
894
- * @param request - The trigger request containing function_id, payload, and optional action/timeout
878
+ * @param request - The call request: `function_id` (or `observer`), `payload`, and optional action/timeout
895
879
  * @returns The result of the function
896
880
  *
897
881
  * @example
898
882
  * ```typescript
899
883
  * // Synchronous invocation
900
- * const result = await worker.trigger<{ name: string }, { message: string }>({
884
+ * const result = await worker.call<{ name: string }, { message: string }>({
901
885
  * function_id: 'greet',
902
886
  * payload: { name: 'World' },
903
887
  * timeoutMs: 5000,
@@ -905,30 +889,43 @@ interface ISdk {
905
889
  * console.log(result.message) // "Hello, World!"
906
890
  *
907
891
  * // Fire-and-forget
908
- * await worker.trigger({
892
+ * await worker.call({
909
893
  * function_id: 'send-email',
910
894
  * payload: { to: 'user@example.com' },
911
- * action: TriggerAction.Void(),
895
+ * action: CallAction.Void(),
912
896
  * })
913
897
  *
914
898
  * // Enqueue for async processing (the queue must be declared in the
915
899
  * // queue worker's queue_configs)
916
- * const receipt = await worker.trigger({
900
+ * const receipt = await worker.call({
917
901
  * function_id: 'process-order',
918
902
  * payload: { orderId: '123' },
919
- * action: TriggerAction.Enqueue({ queue: 'orders' }),
903
+ * action: CallAction.Enqueue({ queue: 'orders' }),
920
904
  * })
905
+ *
906
+ * // Through an observer, in the function's deliver hook: runs its target,
907
+ * // with its policy and metadata
908
+ * const response = await worker.call({ observer: route.obs, payload: request })
921
909
  * ```
922
910
  */
923
- trigger<TInput = unknown, TOutput = any>(request: TriggerRequest<TInput>): Promise<TOutput>;
911
+ call<TInput = unknown, TOutput = any>(request: CallRequest<TInput>): Promise<TOutput>;
912
+ /**
913
+ * Invokes a function using a request object.
914
+ *
915
+ * @deprecated Use {@link ISdk.call}, the same function.
916
+ */
917
+ trigger<TInput = unknown, TOutput = any>(request: CallRequest<TInput>): Promise<TOutput>;
924
918
  /**
925
- * Observes a function: every event of `source` that passes its `filters`
926
- * invokes `target`, a registered function. Returns synchronously (also
927
- * before the connection is up); the observer is replayed with the same id
928
- * on reconnect. Errors show up as state `error` and reject `ready()`;
929
- * against an engine without observe that is `UNSUPPORTED`.
919
+ * Observes a function: every call of `source` that passes its `filters`
920
+ * runs `target`, a registered function. Returns synchronously (also before
921
+ * the connection is up); the observer is replayed with the same id on
922
+ * reconnect. Errors show up as state `error` and reject `ready()`; against
923
+ * an engine without observe that is `UNSUPPORTED`. An `error` answer to its
924
+ * `observe` is the engine's refusal, the handle's final answer: the engine
925
+ * holds no observer for it, it is not replayed, and its `dispose()` sends
926
+ * nothing.
930
927
  *
931
- * @param source - What is observed: `function_id`, `args` (owner-delivered functions only), `filters`, `on`, `capture`, `deliver`.
928
+ * @param source - What is observed: a function id, or `function_id`, `args` (read by the worker that hosts the function), `filters`, `on`, `capture`, `deliver`.
932
929
  * @param target - The function to invoke.
933
930
  * @param options - `id`, `max_fires`, `expires_in_ms`, `max_in_flight`, `metadata`.
934
931
  *
@@ -936,6 +933,10 @@ interface ISdk {
936
933
  * ```typescript
937
934
  * worker.registerFunction('ui::order-shipped', async ({ input }: Observed) => toast(input))
938
935
  *
936
+ * // every successful call of orders::ship
937
+ * worker.observe('orders::ship', 'ui::order-shipped')
938
+ *
939
+ * // only this customer's
939
940
  * const shipped = worker.observe(
940
941
  * { function_id: 'orders::ship', filters: { 'input.customer_id': { $eq: customerId } } },
941
942
  * 'ui::order-shipped',
@@ -943,10 +944,103 @@ interface ISdk {
943
944
  * await shipped.ready()
944
945
  * ```
945
946
  */
946
- observe(source: ObserveSource, target: Target, options?: ObserverOptions): ObserverHandle;
947
+ observe(source: string | ObserveSource, target: Target, options?: ObserverOptions): ObserverHandle;
948
+ /**
949
+ * Runs `hook` when an observer of any function this worker hosts is added,
950
+ * before the SDK acks it; with a function id, for that function only. When
951
+ * both are set, the worker's runs first. Throw to reject the observer.
952
+ * `null` removes the hook. Hooks set by id stay in place across
953
+ * `unregister()` and a later registration of the same id.
954
+ *
955
+ * A hook set while the function already has active observers runs for each
956
+ * of them at once (a throw late-rejects that observer), and the SDK logs a
957
+ * warning.
958
+ *
959
+ * @example
960
+ * ```typescript
961
+ * // every function this page hosts: keep the event stream open while anything is observed
962
+ * worker.onObserverAdded(async () => { await events.retain() })
963
+ * // one function, by id
964
+ * worker.onObserverAdded('ui::on-click', (obs) => targets.retain(obs.args.selector as string))
965
+ * ```
966
+ */
967
+ onObserverAdded(hook: AddedHook | null): ISdk;
968
+ onObserverAdded(functionId: string, hook: AddedHook | null): ISdk;
969
+ /**
970
+ * Runs `hook` once for every accepted observer when it is removed (on
971
+ * `unobserve`, disposal, unregister, late rejection); with a function id,
972
+ * for that function only. When both are set, the function's runs first. An
973
+ * error it throws is logged. `null` removes the hook.
974
+ */
975
+ onObserverRemoved(hook: RemovedHook | null): ISdk;
976
+ onObserverRemoved(functionId: string, hook: RemovedHook | null): ISdk;
977
+ /**
978
+ * Says which observers want each call of a function. By default every
979
+ * observer wants every call. A predicate `(obs, call) => boolean` is asked
980
+ * once per active observer per call; `{ observer, call }` key functions are
981
+ * computed once per observer, when it is accepted, and once per call, and an
982
+ * observer wants a call when they share a key (the SDK keeps an index). The
983
+ * observers' `on`, filters, policy and `deliver` still apply. A hook set
984
+ * while observers are active rebuilds the index from them. `null` removes
985
+ * the hook.
986
+ *
987
+ * A function with a match hook needs an engine with `observe.v2`: against
988
+ * an older one it stays unregistered, and the SDK logs `UNSUPPORTED` once.
989
+ *
990
+ * @example
991
+ * ```typescript
992
+ * // an observer of selector X gets the clicks on X
993
+ * worker.onObserverMatch('ui::on-click', (obs, call) => obs.args.selector === call.input.selector)
994
+ *
995
+ * // many observers: keys, one lookup per key
996
+ * worker.onObserverMatch('ui::on-click', {
997
+ * observer: (obs) => obs.args.selector as string,
998
+ * call: (call) => call.input.selector,
999
+ * })
1000
+ * ```
1001
+ */
1002
+ onObserverMatch<I = any, O = any>(functionId: string, hook: MatchPredicate<I, O> | null): ISdk;
1003
+ onObserverMatch<I = any, O = any>(functionId: string, hook: MatchKeys<I, O>): ISdk;
1004
+ onObserverMatch<I = any, O = any>(functionId: string, hook: MatchHook<I, O> | null): ISdk;
947
1005
  /**
948
- * The invocation the calling code runs in (remote or local handler), or
949
- * `undefined` outside any handler.
1006
+ * Delivers each call of a function itself: `hook` receives the call and the
1007
+ * observers that matched it (a snapshot taken when the call started), and
1008
+ * what it returns (or throws) is what the caller gets back. iii delivers
1009
+ * nothing for that function: the hook calls through observers and applies
1010
+ * their filters with `obs.matches(call)`. Without it, iii delivers every
1011
+ * call to the matching observers whose `on` and filters accept it, and the
1012
+ * caller gets the handler's result. `null` removes the hook.
1013
+ *
1014
+ * A function with a deliver hook needs an engine with `observe.v2`: against
1015
+ * an older one it stays unregistered, and the SDK logs `UNSUPPORTED` once.
1016
+ *
1017
+ * The hook runs in the function's invocation: up to its first `await` in
1018
+ * its scope, and after it as the invocation the page falls back to while it
1019
+ * is the only one running (see {@link ISdk.withInvocation}).
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * worker.onObserverDeliver('ui::on-command', async (call) => {
1024
+ * const handler = commands.match(call.input)
1025
+ * if (!handler) return { handled: false }
1026
+ * if (!handler.obs.matches(call)) return { handled: false }
1027
+ * return worker.call({ observer: handler.obs, payload: call.input })
1028
+ * })
1029
+ * ```
1030
+ */
1031
+ onObserverDeliver<I = any, O = any, R = O>(functionId: string, hook: DeliverHook<I, O, R> | null): ISdk;
1032
+ /** The active observers of a function this worker hosts (empty for any other). */
1033
+ observers(functionId: string): readonly Observer[];
1034
+ /**
1035
+ * Whether a call of a function this worker hosts would reach anyone.
1036
+ * Without a call: any active observer. With a call, on a function matched
1037
+ * by keys: an observer filed under one of the call's keys. On any other
1038
+ * function the call is not read.
1039
+ */
1040
+ isObserved(functionId: string, call?: Partial<Call>): boolean;
1041
+ /**
1042
+ * The invocation the calling code runs in (remote or local handler, or the
1043
+ * function's deliver hook), or `undefined` outside any handler.
950
1044
  *
951
1045
  * Browsers have no `AsyncLocalStorage`: the SDK knows the invocation while
952
1046
  * the handler runs synchronously, up to its first `await`; after it this
@@ -960,9 +1054,8 @@ interface ISdk {
960
1054
  * whose target awaits before calling back. With several invocations
961
1055
  * running this over-counts, and a legitimate chain may stop early. They
962
1056
  * carry a `caller` and `traceparent` only when that is unambiguous (one
963
- * invocation is running, and it is an observe activation); otherwise none.
964
- * They never get an invocation's metadata: `obs.emit` / `obs.call` filters
965
- * on `metadata.*` see it only inside a real scope. An invocation that never
1057
+ * invocation is running, and it is an observe activation or its function's
1058
+ * deliver hook is running); otherwise none. An invocation that never
966
1059
  * settles stops counting as running after 10 minutes (a local call: at its
967
1060
  * timeout). Local calls nest the same way: a self-recursion that awaits
968
1061
  * before each call goes through the engine past 64 levels, while calls
@@ -978,7 +1071,7 @@ interface ISdk {
978
1071
  * worker.registerFunction('ui::checkout', async (cart) => {
979
1072
  * const inv = worker.currentInvocation() // { function_id, invocation_id, caller, observe_depth, ... }
980
1073
  * const quote = await fetchQuote(cart)
981
- * return worker.withInvocation(inv, () => worker.trigger({ function_id: 'orders::create', payload: quote }))
1074
+ * return worker.withInvocation(inv, () => worker.call({ function_id: 'orders::create', payload: quote }))
982
1075
  * })
983
1076
  * ```
984
1077
  */
@@ -986,11 +1079,11 @@ interface ISdk {
986
1079
  /**
987
1080
  * Runs `fn` inside `invocation` (what {@link ISdk.currentInvocation}
988
1081
  * returned), and returns what `fn` returns. Calls `fn` makes before its own
989
- * first `await` (`trigger`, `obs.emit`, `obs.call`, `currentInvocation`)
990
- * belong to that invocation: they carry its caller, `observe_depth` and
991
- * `traceparent`. When `fn` returns a promise, the invocation counts as
992
- * running until it settles, so `fn`'s code after an `await` gets the
993
- * fallback below. `undefined` runs `fn` outside any invocation.
1082
+ * first `await` (`call`, `currentInvocation`) belong to that invocation:
1083
+ * they carry its caller, `observe_depth` and `traceparent`. When `fn`
1084
+ * returns a promise, the invocation counts as running until it settles, so
1085
+ * `fn`'s code after an `await` gets the fallback below. `undefined` runs
1086
+ * `fn` outside any invocation.
994
1087
  *
995
1088
  * Code after an `await`, outside `withInvocation`, runs outside any
996
1089
  * invocation, but its calls are not treated as new chains: they carry the
@@ -999,9 +1092,8 @@ interface ISdk {
999
1092
  * whose target awaits before calling back. With several invocations
1000
1093
  * running this over-counts, and a legitimate chain may stop early. They
1001
1094
  * carry a `caller` and `traceparent` only when that is unambiguous (one
1002
- * invocation is running, and it is an observe activation); otherwise none.
1003
- * They never get an invocation's metadata: `obs.emit` / `obs.call` filters
1004
- * on `metadata.*` see it only inside a real scope. An invocation that never
1095
+ * invocation is running, and it is an observe activation or its function's
1096
+ * deliver hook is running); otherwise none. An invocation that never
1005
1097
  * settles stops counting as running after 10 minutes (a local call: at its
1006
1098
  * timeout). Local calls nest the same way: a self-recursion that awaits
1007
1099
  * before each call goes through the engine past 64 levels, while calls
@@ -1013,48 +1105,6 @@ interface ISdk {
1013
1105
  * `LOCAL_DEPTH_EXCEEDED` (a runaway recursion must not freeze the page).
1014
1106
  */
1015
1107
  withInvocation<T>(invocation: InvocationContext | undefined, fn: () => T): T;
1016
- /**
1017
- * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.
1018
- *
1019
- * @deprecated Register a function with an observe descriptor instead:
1020
- * `registerFunction(id, handler, { observe: { delivery: 'owner', onObserverAdded, onObserverRemoved } })`.
1021
- * Logs a warning once per page. Migration guide: https://iii.dev/docs/upgrading/from-0-24-x
1022
- * @param triggerType - The trigger type to register
1023
- * @param handler - The handler for the trigger type
1024
- * @returns A trigger type object that can be used to unregister the trigger type
1025
- *
1026
- * @example
1027
- * ```typescript
1028
- * type CronConfig = { expression: string }
1029
- *
1030
- * worker.registerTriggerType<CronConfig>(
1031
- * { id: 'cron', description: 'Fires on a cron schedule' },
1032
- * {
1033
- * async registerTrigger({ id, function_id, config }) {
1034
- * startCronJob(id, config.expression, () =>
1035
- * worker.trigger({ function_id, payload: {} }),
1036
- * )
1037
- * },
1038
- * async unregisterTrigger({ id }) {
1039
- * stopCronJob(id)
1040
- * },
1041
- * },
1042
- * )
1043
- * ```
1044
- */
1045
- registerTriggerType<TConfig>(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>): TriggerTypeRef<TConfig>;
1046
- /**
1047
- * Unregisters a trigger type.
1048
- *
1049
- * @deprecated Trigger types are replaced by functions with an observe descriptor.
1050
- * @param triggerType - The trigger type to unregister
1051
- *
1052
- * @example
1053
- * ```typescript
1054
- * worker.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
1055
- * ```
1056
- */
1057
- unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void;
1058
1108
  /**
1059
1109
  * Gracefully shutdown the iii, cleaning up all resources.
1060
1110
  *
@@ -1091,84 +1141,44 @@ interface ISdk {
1091
1141
  getFatalError(): RegistrationRejectedError | undefined;
1092
1142
  }
1093
1143
  /**
1094
- * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to
1095
- * remove the trigger from the engine.
1096
- *
1097
- * @deprecated `registerTrigger` is replaced by `iii.observe`, which returns an {@link ObserverHandle}.
1098
- */
1099
- type Trigger = {
1100
- /** Removes this trigger from the engine. */unregister(): void;
1101
- };
1102
- /**
1103
- * Handle returned by {@link ISdk.registerFunction}. Contains the function's
1104
- * `id` and an `unregister()` method.
1105
- */
1106
- type FunctionRef = {
1107
- /** The unique function identifier. */id: string; /** Removes this function from the engine. */
1108
- unregister: () => void;
1109
- /**
1110
- * Whether any observer is active on this function (one load, for the emit
1111
- * fast path: skip building an event nobody receives).
1112
- */
1113
- isObserved: () => boolean; /** The active observers, as this owner sees them. */
1114
- observers: () => readonly Observer[];
1115
- };
1116
- /**
1117
- * Typed handle returned by {@link ISdk.registerTriggerType}.
1118
- *
1119
- * @deprecated Trigger types are replaced by functions with an observe
1120
- * descriptor, and these helpers by `iii.observe`. Migration guide:
1121
- * https://iii.dev/docs/upgrading/from-0-24-x
1122
- *
1123
- * Provides convenience methods to register triggers and functions scoped
1124
- * to this trigger type, so callers don't need to repeat the `type` field.
1125
- *
1126
- * @typeParam TConfig - Trigger-specific configuration type.
1144
+ * Handle returned by {@link ISdk.registerFunction}: the client's hook
1145
+ * methods with the function id filled in. Each method returns the handle, so
1146
+ * calls chain.
1127
1147
  *
1128
1148
  * @example
1129
1149
  * ```typescript
1130
- * type CronConfig = { expression: string }
1131
- *
1132
- * const cron = worker.registerTriggerType<CronConfig>(
1133
- * { id: 'cron', description: 'Fires on a cron schedule' },
1134
- * cronHandler,
1135
- * )
1136
- *
1137
- * // Register a trigger; type is inferred as CronConfig
1138
- * cron.registerTrigger('my::fn', { expression: '0 *\/5 * * * * *' })
1139
- *
1140
- * // Register a function and bind a trigger in one call
1141
- * cron.registerFunction(
1142
- * 'my::fn',
1143
- * async (data) => { return { ok: true } },
1144
- * { expression: '0 *\/5 * * * * *' },
1145
- * )
1150
+ * worker.registerFunction('ui::on-click', (click: Click) => click, { private: true })
1151
+ * .onObserverAdded((obs) => targets.retain(obs.args.selector as string))
1152
+ * .onObserverRemoved((obs) => targets.release(obs.args.selector as string))
1146
1153
  * ```
1147
1154
  */
1148
- type TriggerTypeRef<TConfig = unknown> = {
1149
- /** The trigger type identifier. */id: string;
1150
- /**
1151
- * Register a trigger bound to this trigger type.
1152
- *
1153
- * @param functionId - The function to invoke when the trigger fires.
1154
- * @param config - Trigger-specific configuration.
1155
- * @returns A {@link Trigger} handle with an `unregister()` method.
1156
- */
1157
- registerTrigger(functionId: string, config: TConfig): Trigger;
1155
+ interface FunctionRef<I = any, O = any> {
1156
+ /** The unique function identifier. */
1157
+ readonly id: string;
1158
+ /** {@link ISdk.onObserverAdded} for this function. */
1159
+ onObserverAdded(hook: AddedHook | null): FunctionRef<I, O>;
1160
+ /** {@link ISdk.onObserverRemoved} for this function. */
1161
+ onObserverRemoved(hook: RemovedHook | null): FunctionRef<I, O>;
1162
+ /** {@link ISdk.onObserverMatch} for this function. */
1163
+ onObserverMatch(hook: MatchPredicate<I, O> | null): FunctionRef<I, O>;
1164
+ onObserverMatch(hook: MatchKeys<I, O>): FunctionRef<I, O>;
1165
+ onObserverMatch(hook: MatchHook<I, O> | null): FunctionRef<I, O>;
1166
+ /** {@link ISdk.onObserverDeliver} for this function. */
1167
+ onObserverDeliver<R = O>(hook: DeliverHook<I, O, R> | null): FunctionRef<I, O>;
1158
1168
  /**
1159
- * Register a function and immediately bind it to this trigger type.
1160
- *
1161
- * @param functionId - Unique function identifier.
1162
- * @param handler - Local function handler.
1163
- * @param config - Trigger-specific configuration.
1164
- * @returns A {@link FunctionRef} handle.
1169
+ * The active observers of this registration, as this host sees them (none
1170
+ * once the function is unregistered, also after the id is registered again).
1165
1171
  */
1166
- registerFunction(functionId: string, handler: RemoteFunctionHandler, config: TConfig): FunctionRef;
1172
+ observers(): readonly Observer[];
1167
1173
  /**
1168
- * Unregister this trigger type from the engine.
1174
+ * {@link ISdk.isObserved} for this registration: skip building an event
1175
+ * nobody receives. Without a call it is one load of this registration's
1176
+ * active set.
1169
1177
  */
1178
+ isObserved(call?: Partial<Call<I>>): boolean;
1179
+ /** Removes this function from the engine. Its hooks stay in place for a later registration of the id. */
1170
1180
  unregister(): void;
1171
- };
1181
+ }
1172
1182
  /**
1173
1183
  * A streaming channel pair for worker-to-worker data transfer. Created via
1174
1184
  * the `createChannel` helper from `iii-browser-sdk/helpers`.
@@ -1180,7 +1190,7 @@ type Channel = {
1180
1190
  readerRef: StreamChannelRef;
1181
1191
  };
1182
1192
  /**
1183
- * Incoming HTTP request received by a function registered with an HTTP trigger.
1193
+ * The HTTP request an `http::on-request` route's target receives.
1184
1194
  *
1185
1195
  * @typeParam TBody - Type of the parsed request body.
1186
1196
  */
@@ -1192,7 +1202,7 @@ type ApiRequest<TBody = unknown> = {
1192
1202
  method: string;
1193
1203
  };
1194
1204
  /**
1195
- * Structured API response returned from HTTP function handlers.
1205
+ * The response an `http::on-request` route's target returns.
1196
1206
  *
1197
1207
  * @typeParam TStatus - HTTP status code literal type.
1198
1208
  * @typeParam TBody - Type of the response body.
@@ -1212,5 +1222,5 @@ type ApiResponse<TStatus extends number = number, TBody = string | Record<string
1212
1222
  body?: TBody;
1213
1223
  };
1214
1224
  //#endregion
1215
- export { OnTriggerTypeRegistrationInput as $, EngineFunctions as A, ChannelItem as B, ObserveSource as C, ObserverOptions as D, ObserverHandle as E, InvocationErrorInit as F, EnqueueResult as G, ChannelWriter as H, ObserveRejection as I, ObserveDescriptorWire as J, MessageType as K, RegistrationRejectedError as L, IIIConnectionState as M, IIIReconnectionConfig as N, ObserverState as O, InvocationError as P, OnTriggerRegistrationResult as Q, RegistrationRejectedInit as R, ObserveReason as S, Observer as T, AuthInput as U, ChannelReader as V, AuthResult as W, OnFunctionRegistrationResult as X, OnFunctionRegistrationInput as Y, OnTriggerRegistrationInput as Z, Capture as _, ISdk as a, RegisterTriggerTypeMessage as at, ObserveDoc as b, RegisterTriggerInput as c, Trigger as d, OnTriggerTypeRegistrationResult as et, TriggerTypeRef as f, CallerInfo as g, Caller as h, FunctionRef as i, RegisterTriggerMessage as it, EngineTriggers as j, Target as k, RegisterTriggerTypeInput as l, TriggerHandler as m, ApiResponse as n, RegisterFunctionFormat as nt, RegisterFunctionInput as o, StreamChannelRef as ot, TriggerConfig as p, MiddlewareFunctionInput as q, Channel as r, RegisterFunctionMessage as rt, RegisterFunctionOptions as s, TriggerRequest as st, ApiRequest as t, OpenEnum as tt, RemoteFunctionHandler as u, Filter as v, Observed as w, ObserveHooks as x, InvocationContext as y, ChannelDirection as z };
1216
- //# sourceMappingURL=types-BGYN2Z4E.d.cts.map
1225
+ export { ObserverState as $, OpenEnum as A, DeliverHook as B, AuthResult as C, MiddlewareFunctionInput as D, MessageType as E, AddedHook as F, MatchKeys as G, InvocationContext as H, Call as I, ObserveSource as J, MatchPredicate as K, Caller as L, RegisterFunctionMessage as M, StreamChannelRef as N, OnFunctionRegistrationInput as O, TriggerRequest as P, ObserverOptions as Q, CallerInfo as R, AuthInput as S, EnqueueResult as T, Key as U, Filter as V, MatchHook as W, Observer as X, Observed as Y, ObserverHandle as Z, RegistrationRejectedInit as _, ISdk as a, ChannelReader as b, RemoteFunctionHandler as c, IIIConnectionState as d, RemovedHook as et, IIIReconnectionConfig as f, RegistrationRejectedError as g, ObserveRejection as h, FunctionRef as i, RegisterFunctionFormat as j, OnFunctionRegistrationResult as k, EngineFunctions as l, InvocationErrorInit as m, ApiResponse as n, RegisterFunctionInput as o, InvocationError as p, ObserveReason as q, Channel as r, RegisterFunctionOptions as s, ApiRequest as t, Target as tt, EngineSources as u, ChannelDirection as v, CallRequest as w, ChannelWriter as x, ChannelItem as y, Capture as z };
1226
+ //# sourceMappingURL=types-DqyCQ8JS.d.mts.map