iii-browser-sdk 0.25.0-rc.1 → 0.25.0-rc.3

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/README.md CHANGED
@@ -11,7 +11,7 @@ The browser SDK turns your frontend into an iii Worker enabling:
11
11
 
12
12
  - **Persistent connection** — one WebSocket replaces many HTTP round-trips.
13
13
  - **Bi-directional communication** — the engine can invoke functions registered in the browser. Backend workers push data to the frontend with `trigger()`, enabling real-time patterns without polling.
14
- - **Same API** — `registerFunction`, `trigger`, `registerTrigger` — all the primitives you use server-side work identically in the browser.
14
+ - **Same API** — `registerFunction`, `trigger`, `observe` — all the primitives you use server-side work identically in the browser.
15
15
  - **Zero Node.js dependencies** — runs in any browser environment with native `WebSocket`.
16
16
 
17
17
  ## Install
@@ -48,16 +48,17 @@ const users = await iii.trigger({
48
48
 
49
49
  ## API
50
50
 
51
- | Operation | Signature | Description |
52
- | ------------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------- |
53
- | Initialize | `registerWorker(url, options?)` | Connect to the engine via browser WebSocket. Returns `ISdk` |
54
- | Register function | `iii.registerFunction(id, handler, options?)` | Register a function the engine (or backend) can invoke |
55
- | Register trigger | `iii.registerTrigger({ type, function_id, config })` | Bind a trigger to a function |
56
- | Invoke (await) | `await iii.trigger({ function_id, payload })` | Invoke a function and wait for the result |
57
- | Invoke (fire-and-forget) | `iii.trigger({ function_id, payload, action: TriggerAction.Void() })` | Invoke without waiting |
58
- | Invoke (enqueue) | `iii.trigger({ function_id, payload, action: TriggerAction.Enqueue({ queue }) })` | Route invocation through a named queue |
59
- | Create channel | `iii.createChannel()` | Create a streaming channel pair (writer + reader) |
60
- | Shutdown | `iii.shutdown()` | Gracefully disconnect from the engine |
51
+ | Operation | Signature | Description |
52
+ | ------------------------ | --------------------------------------------------------------------------------- | -------------------------------------------------------------- |
53
+ | Initialize | `registerWorker(url, options?)` | Connect to the engine via browser WebSocket. Returns `ISdk` |
54
+ | Register function | `iii.registerFunction(id, handler, options?)` | Register a function the engine (or backend) can invoke |
55
+ | Invoke (await) | `await iii.trigger({ function_id, payload })` | Invoke a function and wait for the result |
56
+ | Invoke (fire-and-forget) | `iii.trigger({ function_id, payload, action: TriggerAction.Void() })` | Invoke without waiting |
57
+ | Invoke (enqueue) | `iii.trigger({ function_id, payload, action: TriggerAction.Enqueue({ queue }) })` | Route invocation through a named queue |
58
+ | Observe | `iii.observe({ function_id, args?, filters? }, target, options?)` | Invoke `target` on every matching invocation of a function |
59
+ | Current invocation | `iii.currentInvocation()` / `iii.withInvocation(inv, fn)` | The invocation the running handler serves (caller, activation) |
60
+ | Create channel | `createChannel(iii)` (from `iii-browser-sdk/helpers`) | Create a streaming channel pair (writer + reader) |
61
+ | Shutdown | `iii.shutdown()` | Gracefully disconnect from the engine |
61
62
 
62
63
  ### Registering Functions
63
64
 
@@ -81,6 +82,105 @@ const users = await iii.trigger({
81
82
  })
82
83
  ```
83
84
 
85
+ A call can carry `metadata` (any JSON, handed to the handler as its second
86
+ argument and readable by observer filters as `metadata.*`), and a W3C
87
+ `traceparent` / `baggage` to continue a trace. The browser SDK has no
88
+ OpenTelemetry: it never makes up a trace context. Inside a handler, calls
89
+ forward the `traceparent` the handler was invoked with; a top-level call sends
90
+ the one you pass, or none.
91
+
92
+ ```typescript
93
+ await iii.trigger({
94
+ function_id: 'orders::create',
95
+ payload: cart,
96
+ metadata: { page: 'checkout' },
97
+ traceparent: document.querySelector('meta[name="traceparent"]')?.getAttribute('content') ?? undefined,
98
+ })
99
+ ```
100
+
101
+ A call to a function this worker registered itself runs in-process once the
102
+ engine confirmed it (no frames on the wire unless someone observes it). Pass
103
+ `dispatch: 'remote'` to go through the engine anyway, or register the function
104
+ with `localDispatch: false`.
105
+
106
+ ### Observing Functions
107
+
108
+ Every function is observable. The target is a registered function; it receives
109
+ the `Observed` envelope (`input`, `output` or `error`, `caller`, ...).
110
+
111
+ ```typescript
112
+ iii.registerFunction('ui::order-shipped', async ({ input }: Observed<{ order_id: string }>) => {
113
+ showToast(`Order ${input?.order_id} shipped`)
114
+ return null
115
+ })
116
+
117
+ const shipped = iii.observe(
118
+ { function_id: 'orders::ship', filters: { 'input.customer_id': { $eq: customerId } }, capture: ['input'] },
119
+ 'ui::order-shipped',
120
+ )
121
+ await shipped.ready()
122
+ // later
123
+ await shipped.dispose()
124
+ ```
125
+
126
+ A function can also hand its own events to the observers they belong to (owner
127
+ delivery, `registerFunction(id, handler, { observe: { delivery: 'owner', onObserverAdded, onObserverRemoved } })`)
128
+ and check `FunctionRef.isObserved()` before building an event nobody receives.
129
+
130
+ ### The current invocation across `await`
131
+
132
+ `iii.currentInvocation()` returns the invocation the running handler serves
133
+ (its id, caller, activation, `observe_depth`, `traceparent`). Calls made from a
134
+ handler carry it, so the engine can tell who called whom and stop observe
135
+ loops.
136
+
137
+ Browsers have no `AsyncLocalStorage`, so the SDK knows the invocation only
138
+ while the handler runs synchronously, **up to its first `await`**; after it,
139
+ `currentInvocation()` returns `undefined`. Read the invocation first and
140
+ re-enter it with `withInvocation` for what comes after:
141
+
142
+ ```typescript
143
+ iii.registerFunction('ui::checkout', async (cart) => {
144
+ const inv = iii.currentInvocation() // before the first await
145
+ const quote = await fetchQuote(cart)
146
+ return iii.withInvocation(inv, () => iii.trigger({ function_id: 'orders::create', payload: quote }))
147
+ })
148
+ ```
149
+
150
+ `withInvocation(inv, fn)` runs `fn` in that invocation and returns what `fn`
151
+ returns; `obs.emit` and `obs.call` made inside it belong to the invocation too.
152
+ When `fn` is async, the invocation counts as running until its promise settles.
153
+
154
+ Calls made after an `await` without `withInvocation` are not treated as new
155
+ chains. They carry the `observe_depth` of the deepest invocation running on the
156
+ page, so the engine's loop guard (`max_observe_depth`, 8 by default) still
157
+ stops an observer cycle whose target awaits before it calls back. The cost of
158
+ guessing: with several invocations running at once the depth is over-counted,
159
+ and a legitimate chain may be stopped early. Such calls carry a `caller` and
160
+ `traceparent` only when that is unambiguous (exactly one invocation is running,
161
+ and it is an observe activation); otherwise they carry neither. They never
162
+ borrow an invocation's metadata, so `obs.emit` / `obs.call` filters on
163
+ `metadata.*` only see it inside a real scope. An invocation that never settles
164
+ stops counting as running after 10 minutes (a local call: at its timeout).
165
+ Local calls to this worker's own functions are nested the same way: a recursion
166
+ that awaits before each call still goes through the engine past 64 levels,
167
+ while calls started together (a loop, `Promise.all`) count as one level. A
168
+ known limitation: local calls started in separate ticks while earlier ones are
169
+ still running look nested too, so a long-running, wide fan-out may send some of
170
+ its calls through the engine (same results, more frames). While the socket is
171
+ closed that never happens, since the engine could not take the call anyway: a
172
+ function this worker hosts then runs here up to 256 local calls deep, and past
173
+ that the call fails at once with the code `LOCAL_DEPTH_EXCEEDED`, so a runaway
174
+ recursion neither overflows the stack nor freezes the page. Use
175
+ `withInvocation` to say exactly which invocation a call belongs to.
176
+
177
+ ### Trigger APIs (deprecated)
178
+
179
+ `registerTrigger` and `registerTriggerType` keep working in 0.25 but are
180
+ deprecated: they log a warning once per page. Use `iii.observe(source,
181
+ target)` and `registerFunction(id, handler, { observe })` instead. See the
182
+ [migration guide](https://iii.dev/docs/upgrading/from-0-24-x).
183
+
84
184
  ### Receiving Live Invocations
85
185
 
86
186
  Backend workers can push data to the browser in real time. No polling required:
package/dist/helpers.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils-CJV1pMqe.cjs');
2
+ const require_utils = require('./utils-BUI0XQTZ.cjs');
3
3
 
4
4
  //#region src/helpers.ts
5
5
  /**
@@ -15,6 +15,8 @@ function createChannel(iii, bufferSize) {
15
15
  * to `stream::get/set/delete/list/list_groups`.
16
16
  *
17
17
  * Free-function form of the previous `ISdk.createStream` instance method.
18
+ *
19
+ * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams
18
20
  */
19
21
  function createStream(iii, streamName, stream) {
20
22
  iii.__helpers_create_stream(streamName, stream);
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.cjs","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["/**\n * Helper free functions that operate on an {@link ISdk} instance.\n *\n * These were previously instance methods on the SDK. They take the iii\n * instance as the first argument so the public API surface of `ISdk` stays\n * focused on the core lifecycle and registration methods.\n */\nimport type { Channel, ISdk } from './types'\nimport type { IStream } from './stream'\n\nexport { ChannelDirection, ChannelItem } from './channels'\nexport { extractChannelRefs, isChannelRef } from './utils'\n\ntype IIIWithHelperShims = ISdk & {\n __helpers_create_channel(bufferSize?: number): Promise<Channel>\n __helpers_create_stream<T>(name: string, stream: IStream<T>): void\n}\n\n/**\n * Create a streaming channel pair for worker-to-worker data transfer.\n *\n * Free-function form of the previous `ISdk.createChannel` instance method.\n */\nexport function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel> {\n return (iii as IIIWithHelperShims).__helpers_create_channel(bufferSize)\n}\n\n/**\n * Register a custom stream implementation by wiring its 5 callable methods\n * to `stream::get/set/delete/list/list_groups`.\n *\n * Free-function form of the previous `ISdk.createStream` instance method.\n */\nexport function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void {\n ;(iii as IIIWithHelperShims).__helpers_create_stream(streamName, stream)\n}\n"],"mappings":";;;;;;;;;AAuBA,SAAgB,cAAc,KAAW,YAAuC;AAC9E,QAAQ,IAA2B,yBAAyB,WAAW;;;;;;;;AASzE,SAAgB,aAAoB,KAAW,YAAoB,QAA8B;AAC9F,CAAC,IAA2B,wBAAwB,YAAY,OAAO"}
1
+ {"version":3,"file":"helpers.cjs","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["/**\n * Helper free functions that operate on an {@link ISdk} instance.\n *\n * These were previously instance methods on the SDK. They take the iii\n * instance as the first argument so the public API surface of `ISdk` stays\n * focused on the core lifecycle and registration methods.\n */\nimport type { Channel, ISdk } from './types'\nimport type { IStream } from './stream'\n\nexport { ChannelDirection, ChannelItem } from './channels'\nexport { extractChannelRefs, isChannelRef } from './utils'\n\ntype IIIWithHelperShims = ISdk & {\n __helpers_create_channel(bufferSize?: number): Promise<Channel>\n __helpers_create_stream<T>(name: string, stream: IStream<T>): void\n}\n\n/**\n * Create a streaming channel pair for worker-to-worker data transfer.\n *\n * Free-function form of the previous `ISdk.createChannel` instance method.\n */\nexport function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel> {\n return (iii as IIIWithHelperShims).__helpers_create_channel(bufferSize)\n}\n\n/**\n * Register a custom stream implementation by wiring its 5 callable methods\n * to `stream::get/set/delete/list/list_groups`.\n *\n * Free-function form of the previous `ISdk.createStream` instance method.\n *\n * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams\n */\nexport function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void {\n ;(iii as IIIWithHelperShims).__helpers_create_stream(streamName, stream)\n}\n"],"mappings":";;;;;;;;;AAuBA,SAAgB,cAAc,KAAW,YAAuC;AAC9E,QAAQ,IAA2B,yBAAyB,WAAW;;;;;;;;;;AAWzE,SAAgB,aAAoB,KAAW,YAAoB,QAA8B;AAC9F,CAAC,IAA2B,wBAAwB,YAAY,OAAO"}
@@ -1,4 +1,4 @@
1
- import { B as StreamChannelRef, S as ChannelItem, a as ISdk, r as Channel, x as ChannelDirection } from "./types-fqr5SRfu.cjs";
1
+ import { B as ChannelItem, a as ISdk, ot as StreamChannelRef, r as Channel, z as ChannelDirection } from "./types-BGYN2Z4E.cjs";
2
2
  import { IStream } from "./stream.cjs";
3
3
 
4
4
  //#region src/utils.d.ts
@@ -31,6 +31,8 @@ declare function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel>
31
31
  * to `stream::get/set/delete/list/list_groups`.
32
32
  *
33
33
  * Free-function form of the previous `ISdk.createStream` instance method.
34
+ *
35
+ * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams
34
36
  */
35
37
  declare function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void;
36
38
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/utils.ts","../src/helpers.ts"],"mappings":";;;;;;;;;;cAmCa,YAAA,GAAgB,KAAA,cAAiB,KAAA,IAAS,gBAAA;AAkBvD;;;;;;;;AAAA,cAAa,kBAAA,GAAsB,IAAA,cAAgB,KAAA,UAAe,gBAAA;;;;;AAAlE;;;iBC9BgB,aAAA,CAAc,GAAA,EAAK,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,OAAA;;;;;;;iBAUvD,YAAA,OAAA,CAAoB,GAAA,EAAK,IAAA,EAAM,UAAA,UAAoB,MAAA,EAAQ,OAAA,CAAQ,KAAA"}
1
+ {"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/utils.ts","../src/helpers.ts"],"mappings":";;;;;;;;;;cAmCa,YAAA,GAAgB,KAAA,cAAiB,KAAA,IAAS,gBAAA;AAkBvD;;;;;;;;AAAA,cAAa,kBAAA,GAAsB,IAAA,cAAgB,KAAA,UAAe,gBAAA;;;;;AAAlE;;;iBC9BgB,aAAA,CAAc,GAAA,EAAK,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,OAAA;;;;;;;;;iBAYvD,YAAA,OAAA,CAAoB,GAAA,EAAK,IAAA,EAAM,UAAA,UAAoB,MAAA,EAAQ,OAAA,CAAQ,KAAA"}
@@ -1,4 +1,4 @@
1
- import { B as StreamChannelRef, S as ChannelItem, a as ISdk, r as Channel, x as ChannelDirection } from "./types-DeNafz-M.mjs";
1
+ import { B as ChannelItem, a as ISdk, ot as StreamChannelRef, r as Channel, z as ChannelDirection } from "./types-Crw4auK5.mjs";
2
2
  import { IStream } from "./stream.mjs";
3
3
 
4
4
  //#region src/utils.d.ts
@@ -31,6 +31,8 @@ declare function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel>
31
31
  * to `stream::get/set/delete/list/list_groups`.
32
32
  *
33
33
  * Free-function form of the previous `ISdk.createStream` instance method.
34
+ *
35
+ * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams
34
36
  */
35
37
  declare function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void;
36
38
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.mts","names":[],"sources":["../src/utils.ts","../src/helpers.ts"],"mappings":";;;;;;;;;;cAmCa,YAAA,GAAgB,KAAA,cAAiB,KAAA,IAAS,gBAAA;AAkBvD;;;;;;;;AAAA,cAAa,kBAAA,GAAsB,IAAA,cAAgB,KAAA,UAAe,gBAAA;;;;;AAAlE;;;iBC9BgB,aAAA,CAAc,GAAA,EAAK,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,OAAA;;;;;;;iBAUvD,YAAA,OAAA,CAAoB,GAAA,EAAK,IAAA,EAAM,UAAA,UAAoB,MAAA,EAAQ,OAAA,CAAQ,KAAA"}
1
+ {"version":3,"file":"helpers.d.mts","names":[],"sources":["../src/utils.ts","../src/helpers.ts"],"mappings":";;;;;;;;;;cAmCa,YAAA,GAAgB,KAAA,cAAiB,KAAA,IAAS,gBAAA;AAkBvD;;;;;;;;AAAA,cAAa,kBAAA,GAAsB,IAAA,cAAgB,KAAA,UAAe,gBAAA;;;;;AAAlE;;;iBC9BgB,aAAA,CAAc,GAAA,EAAK,IAAA,EAAM,UAAA,YAAsB,OAAA,CAAQ,OAAA;;;;;;;;;iBAYvD,YAAA,OAAA,CAAoB,GAAA,EAAK,IAAA,EAAM,UAAA,UAAoB,MAAA,EAAQ,OAAA,CAAQ,KAAA"}
package/dist/helpers.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ChannelItem, i as ChannelDirection, n as isChannelRef, t as extractChannelRefs } from "./utils-nQQPFFRM.mjs";
1
+ import { n as isChannelRef, o as ChannelDirection, s as ChannelItem, t as extractChannelRefs } from "./utils-Bz5eP_hN.mjs";
2
2
 
3
3
  //#region src/helpers.ts
4
4
  /**
@@ -14,6 +14,8 @@ function createChannel(iii, bufferSize) {
14
14
  * to `stream::get/set/delete/list/list_groups`.
15
15
  *
16
16
  * Free-function form of the previous `ISdk.createStream` instance method.
17
+ *
18
+ * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams
17
19
  */
18
20
  function createStream(iii, streamName, stream) {
19
21
  iii.__helpers_create_stream(streamName, stream);
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.mjs","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["/**\n * Helper free functions that operate on an {@link ISdk} instance.\n *\n * These were previously instance methods on the SDK. They take the iii\n * instance as the first argument so the public API surface of `ISdk` stays\n * focused on the core lifecycle and registration methods.\n */\nimport type { Channel, ISdk } from './types'\nimport type { IStream } from './stream'\n\nexport { ChannelDirection, ChannelItem } from './channels'\nexport { extractChannelRefs, isChannelRef } from './utils'\n\ntype IIIWithHelperShims = ISdk & {\n __helpers_create_channel(bufferSize?: number): Promise<Channel>\n __helpers_create_stream<T>(name: string, stream: IStream<T>): void\n}\n\n/**\n * Create a streaming channel pair for worker-to-worker data transfer.\n *\n * Free-function form of the previous `ISdk.createChannel` instance method.\n */\nexport function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel> {\n return (iii as IIIWithHelperShims).__helpers_create_channel(bufferSize)\n}\n\n/**\n * Register a custom stream implementation by wiring its 5 callable methods\n * to `stream::get/set/delete/list/list_groups`.\n *\n * Free-function form of the previous `ISdk.createStream` instance method.\n */\nexport function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void {\n ;(iii as IIIWithHelperShims).__helpers_create_stream(streamName, stream)\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,cAAc,KAAW,YAAuC;AAC9E,QAAQ,IAA2B,yBAAyB,WAAW;;;;;;;;AASzE,SAAgB,aAAoB,KAAW,YAAoB,QAA8B;AAC9F,CAAC,IAA2B,wBAAwB,YAAY,OAAO"}
1
+ {"version":3,"file":"helpers.mjs","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["/**\n * Helper free functions that operate on an {@link ISdk} instance.\n *\n * These were previously instance methods on the SDK. They take the iii\n * instance as the first argument so the public API surface of `ISdk` stays\n * focused on the core lifecycle and registration methods.\n */\nimport type { Channel, ISdk } from './types'\nimport type { IStream } from './stream'\n\nexport { ChannelDirection, ChannelItem } from './channels'\nexport { extractChannelRefs, isChannelRef } from './utils'\n\ntype IIIWithHelperShims = ISdk & {\n __helpers_create_channel(bufferSize?: number): Promise<Channel>\n __helpers_create_stream<T>(name: string, stream: IStream<T>): void\n}\n\n/**\n * Create a streaming channel pair for worker-to-worker data transfer.\n *\n * Free-function form of the previous `ISdk.createChannel` instance method.\n */\nexport function createChannel(iii: ISdk, bufferSize?: number): Promise<Channel> {\n return (iii as IIIWithHelperShims).__helpers_create_channel(bufferSize)\n}\n\n/**\n * Register a custom stream implementation by wiring its 5 callable methods\n * to `stream::get/set/delete/list/list_groups`.\n *\n * Free-function form of the previous `ISdk.createStream` instance method.\n *\n * @deprecated createStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams\n */\nexport function createStream<TData>(iii: ISdk, streamName: string, stream: IStream<TData>): void {\n ;(iii as IIIWithHelperShims).__helpers_create_stream(streamName, stream)\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,cAAc,KAAW,YAAuC;AAC9E,QAAQ,IAA2B,yBAAyB,WAAW;;;;;;;;;;AAWzE,SAAgB,aAAoB,KAAW,YAAoB,QAA8B;AAC9F,CAAC,IAA2B,wBAAwB,YAAY,OAAO"}