signalk-plotterext-bus 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +172 -0
- package/dist/chunk-EGWZMA5J.js +159 -0
- package/dist/chunk-EGWZMA5J.js.map +1 -0
- package/dist/chunk-JJEZW66E.js +106 -0
- package/dist/chunk-JJEZW66E.js.map +1 -0
- package/dist/chunk-ZYQKQSOC.js +318 -0
- package/dist/chunk-ZYQKQSOC.js.map +1 -0
- package/dist/extension.cjs +496 -0
- package/dist/extension.cjs.map +1 -0
- package/dist/extension.d.cts +65 -0
- package/dist/extension.d.ts +65 -0
- package/dist/extension.js +31 -0
- package/dist/extension.js.map +1 -0
- package/dist/host.cjs +442 -0
- package/dist/host.cjs.map +1 -0
- package/dist/host.d.cts +53 -0
- package/dist/host.d.ts +53 -0
- package/dist/host.js +29 -0
- package/dist/host.js.map +1 -0
- package/dist/index.cjs +603 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +17 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/dist/wildcard-1_n-MlrD.d.cts +217 -0
- package/dist/wildcard-1_n-MlrD.d.ts +217 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joel Kozikowski
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# signalk-plotterext-bus
|
|
2
|
+
|
|
3
|
+
Reference implementation of the **Signal K plotter extension bus** — the
|
|
4
|
+
message protocol between a chartplotter host application (e.g. Freeboard-SK)
|
|
5
|
+
and extension iframes (panels, widgets, background runtimes) provided by
|
|
6
|
+
Signal K server plugins via the `plotterExtensions` resource type.
|
|
7
|
+
|
|
8
|
+
The **documented wire format below is the contract**; this package is a
|
|
9
|
+
convenience. Any conforming implementation interoperates.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install signalk-plotterext-bus
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- Extensions import `signalk-plotterext-bus/extension`.
|
|
18
|
+
- Hosts import `signalk-plotterext-bus/host`.
|
|
19
|
+
|
|
20
|
+
## Wire Format
|
|
21
|
+
|
|
22
|
+
Every message is a JSON-RPC 2.0 object inside a routing envelope, sent with
|
|
23
|
+
`postMessage` (window-to-iframe or `MessageChannel`):
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{ "bus": "plotterExt/1", "msg": { "jsonrpc": "2.0", "...": "..." } }
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The `bus` field identifies protocol and major version so frames can ignore
|
|
30
|
+
unrelated `postMessage` traffic.
|
|
31
|
+
|
|
32
|
+
### Calls
|
|
33
|
+
|
|
34
|
+
A call is a JSON-RPC request with a fresh per-call correlation `id` (never
|
|
35
|
+
correlate by method name — concurrent calls to the same method must not
|
|
36
|
+
collide):
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{ "jsonrpc": "2.0", "id": "ab12-1", "method": "state.get", "params": { "keys": ["path"] } }
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Exactly one response per request, `result` and `error` mutually exclusive:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{ "jsonrpc": "2.0", "id": "ab12-1", "result": { "values": { "path": "navigation.speedOverGround" } } }
|
|
46
|
+
{ "jsonrpc": "2.0", "id": "ab12-1", "error": { "code": -32602, "message": "…", "data": { "reason": "INVALID_PARAMS" } } }
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Protocol errors use the JSON-RPC reserved codes (`-32601` method not found,
|
|
50
|
+
`-32602` invalid params, `-32603` internal). Host API errors use
|
|
51
|
+
implementation-defined codes (this package defaults to `-32000`) and put a
|
|
52
|
+
stable string identifier in `error.data.reason`. Callers apply timeouts and
|
|
53
|
+
discard the pending-call entry when one fires.
|
|
54
|
+
|
|
55
|
+
### Events
|
|
56
|
+
|
|
57
|
+
An event is a JSON-RPC *notification* (no `id`); its `method` is a
|
|
58
|
+
hierarchical dot-separated event name:
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{ "jsonrpc": "2.0", "method": "sk.navigation.speedOverGround", "params": { "path": "navigation.speedOverGround", "value": 3.6 } }
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`postMessage` is point-to-point, so hosts only forward events a context has
|
|
65
|
+
subscribed to via `events.subscribe` / `events.unsubscribe`. Subscription
|
|
66
|
+
patterns use eventemitter2-style wildcards: `*` matches exactly one segment,
|
|
67
|
+
`**` matches zero or more segments (`map.*`, `sk.navigation.**`).
|
|
68
|
+
|
|
69
|
+
### Connection establishment
|
|
70
|
+
|
|
71
|
+
1. The extension sends the notification `bus.ready` (repeating every ~250 ms
|
|
72
|
+
until answered, in case the host attaches late).
|
|
73
|
+
2. The host replies with the notification `bus.handshake`:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"jsonrpc": "2.0",
|
|
78
|
+
"method": "bus.handshake",
|
|
79
|
+
"params": {
|
|
80
|
+
"host": "freeboard-sk",
|
|
81
|
+
"hostVersion": "2.14.0",
|
|
82
|
+
"apiVersion": "1",
|
|
83
|
+
"capabilities": ["widgets", "panels.iframe", "signalk.stream"],
|
|
84
|
+
"context": { "kind": "widget", "id": "gauge", "instanceId": "…", "targetInstance": null }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Built-in methods
|
|
90
|
+
|
|
91
|
+
Implemented by `HostConnection` automatically:
|
|
92
|
+
|
|
93
|
+
| Method | Params | Result |
|
|
94
|
+
| --- | --- | --- |
|
|
95
|
+
| `events.subscribe` | `{ patterns: string[] }` | `{ subscriptionId }` |
|
|
96
|
+
| `events.unsubscribe` | `{ subscriptionId }` | `{}` |
|
|
97
|
+
|
|
98
|
+
Host API methods (`state.*`, `signalk.*`, `map.*`, …) are supplied by the
|
|
99
|
+
embedding host application; see the plotter extension specification for the
|
|
100
|
+
vocabulary.
|
|
101
|
+
|
|
102
|
+
## Usage — extension side
|
|
103
|
+
|
|
104
|
+
```js
|
|
105
|
+
import { connectExtension } from 'signalk-plotterext-bus/extension'
|
|
106
|
+
|
|
107
|
+
const client = await connectExtension()
|
|
108
|
+
console.log(client.context) // { kind: 'widget', id: 'gauge', instanceId: '…' }
|
|
109
|
+
|
|
110
|
+
// Per-instance configuration
|
|
111
|
+
const { path } = await client.state.get(['path'])
|
|
112
|
+
|
|
113
|
+
// Live Signal K data, relayed by the host
|
|
114
|
+
const stop = await client.signalk.subscribe([path], (ev) => {
|
|
115
|
+
render(ev.value)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// React to configuration changes made by the config panel
|
|
119
|
+
await client.subscribe(['state.changed'], async () => {
|
|
120
|
+
const values = await client.state.get()
|
|
121
|
+
reconfigure(values)
|
|
122
|
+
})
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Usage — host side
|
|
126
|
+
|
|
127
|
+
```js
|
|
128
|
+
import { HostConnection, windowPort } from 'signalk-plotterext-bus/host'
|
|
129
|
+
|
|
130
|
+
const conn = new HostConnection({
|
|
131
|
+
port: windowPort(iframe.contentWindow),
|
|
132
|
+
hostInfo: {
|
|
133
|
+
host: 'my-plotter',
|
|
134
|
+
hostVersion: '1.0.0',
|
|
135
|
+
apiVersion: '1',
|
|
136
|
+
capabilities: ['widgets', 'panels.iframe', 'signalk.stream']
|
|
137
|
+
},
|
|
138
|
+
context: { kind: 'widget', id: 'gauge', instanceId, targetInstance: null },
|
|
139
|
+
methods: {
|
|
140
|
+
'state.get': async ({ keys }) => ({ values: await loadState(instanceId, keys) }),
|
|
141
|
+
'state.set': async ({ values }) => { await saveState(instanceId, values) },
|
|
142
|
+
'signalk.subscribe': ({ paths }) => startRelay(conn, paths),
|
|
143
|
+
'signalk.unsubscribe': ({ subscriptionId }) => stopRelay(subscriptionId)
|
|
144
|
+
},
|
|
145
|
+
onSubscriptionsChanged: (patterns) => updateUpstream(patterns)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
// Later, from the host's data stream:
|
|
149
|
+
conn.publish('sk.navigation.speedOverGround', { path, value, timestamp })
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Throw `RpcError` from method handlers to return structured errors:
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
import { RpcError, RPC_ERRORS } from 'signalk-plotterext-bus/host'
|
|
156
|
+
throw new RpcError('unknown path', { code: RPC_ERRORS.INVALID_PARAMS, reason: 'UNKNOWN_PATH' })
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Conformance testing
|
|
160
|
+
|
|
161
|
+
The test suite drives a real `HostConnection` against a real
|
|
162
|
+
`connectExtension()` over a `MessageChannel` pair with no DOM. A host
|
|
163
|
+
implementing its own endpoint can reuse the same harness shape to verify
|
|
164
|
+
conformance.
|
|
165
|
+
|
|
166
|
+
```sh
|
|
167
|
+
npm test
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
MIT
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BusEndpoint,
|
|
3
|
+
EVENT_HANDSHAKE,
|
|
4
|
+
EVENT_READY,
|
|
5
|
+
RPC_ERRORS,
|
|
6
|
+
RpcError,
|
|
7
|
+
windowPort
|
|
8
|
+
} from "./chunk-ZYQKQSOC.js";
|
|
9
|
+
|
|
10
|
+
// src/extension.ts
|
|
11
|
+
var ExtensionClient = class {
|
|
12
|
+
handshake;
|
|
13
|
+
endpoint;
|
|
14
|
+
constructor(endpoint, handshake) {
|
|
15
|
+
this.endpoint = endpoint;
|
|
16
|
+
this.handshake = handshake;
|
|
17
|
+
}
|
|
18
|
+
get context() {
|
|
19
|
+
return this.handshake.context;
|
|
20
|
+
}
|
|
21
|
+
get apiVersion() {
|
|
22
|
+
return this.handshake.apiVersion;
|
|
23
|
+
}
|
|
24
|
+
get capabilities() {
|
|
25
|
+
return this.handshake.capabilities;
|
|
26
|
+
}
|
|
27
|
+
hasCapability(id) {
|
|
28
|
+
return this.handshake.capabilities.includes(id);
|
|
29
|
+
}
|
|
30
|
+
/** Call a host API method. */
|
|
31
|
+
call(method, params, opts) {
|
|
32
|
+
return this.endpoint.call(method, params, opts);
|
|
33
|
+
}
|
|
34
|
+
/** Send a notification to the host. */
|
|
35
|
+
notify(method, params) {
|
|
36
|
+
this.endpoint.notify(method, params);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Subscribe to host events matching wildcard patterns. Registers both the
|
|
40
|
+
* host-side forwarding subscription and local dispatch; the returned
|
|
41
|
+
* function tears down both.
|
|
42
|
+
*/
|
|
43
|
+
async subscribe(patterns, handler) {
|
|
44
|
+
const off = this.endpoint.onEvent(patterns, handler);
|
|
45
|
+
let subscriptionId;
|
|
46
|
+
try {
|
|
47
|
+
const result = await this.call("events.subscribe", { patterns });
|
|
48
|
+
subscriptionId = result.subscriptionId;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
off();
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
return async () => {
|
|
54
|
+
off();
|
|
55
|
+
await this.call("events.unsubscribe", { subscriptionId }).catch(() => {
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** Host-persisted key/value state (see spec: State Storage). */
|
|
60
|
+
state = {
|
|
61
|
+
get: async (keys, scope) => {
|
|
62
|
+
const result = await this.call("state.get", {
|
|
63
|
+
...scope ? { scope } : {},
|
|
64
|
+
...keys ? { keys } : {}
|
|
65
|
+
});
|
|
66
|
+
return result.values ?? {};
|
|
67
|
+
},
|
|
68
|
+
set: async (values, scope) => {
|
|
69
|
+
await this.call("state.set", {
|
|
70
|
+
...scope ? { scope } : {},
|
|
71
|
+
values
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/** Signal K data relayed by the host (capabilities signalk.stream / .put). */
|
|
76
|
+
signalk = {
|
|
77
|
+
/**
|
|
78
|
+
* Subscribe to Signal K path values. The host publishes them as
|
|
79
|
+
* `sk.<path>` events; this helper hides the event-name mapping and
|
|
80
|
+
* establishes both the event-forwarding subscription and the host's
|
|
81
|
+
* upstream Signal K subscription.
|
|
82
|
+
*/
|
|
83
|
+
subscribe: async (paths, handler) => {
|
|
84
|
+
const patterns = paths.map((p) => `sk.${p}`);
|
|
85
|
+
const offEvents = await this.subscribe(
|
|
86
|
+
patterns,
|
|
87
|
+
(_name, params) => handler(params)
|
|
88
|
+
);
|
|
89
|
+
let subscriptionId;
|
|
90
|
+
try {
|
|
91
|
+
const result = await this.call("signalk.subscribe", { paths });
|
|
92
|
+
subscriptionId = result.subscriptionId;
|
|
93
|
+
} catch (err) {
|
|
94
|
+
await offEvents();
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
return async () => {
|
|
98
|
+
await offEvents();
|
|
99
|
+
await this.call("signalk.unsubscribe", { subscriptionId }).catch(
|
|
100
|
+
() => {
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
put: (path, value) => {
|
|
106
|
+
return this.call("signalk.put", { path, value });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
close() {
|
|
110
|
+
this.endpoint.close();
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
function connectExtension(opts = {}) {
|
|
114
|
+
const port = opts.port ?? windowPort(globalThis.parent, {
|
|
115
|
+
origin: "*"
|
|
116
|
+
});
|
|
117
|
+
const endpoint = new BusEndpoint({
|
|
118
|
+
port,
|
|
119
|
+
callTimeoutMs: opts.callTimeoutMs,
|
|
120
|
+
onError: opts.onError
|
|
121
|
+
});
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
let done = false;
|
|
124
|
+
const off = endpoint.onEvent([EVENT_HANDSHAKE], (_name, params) => {
|
|
125
|
+
if (done) return;
|
|
126
|
+
done = true;
|
|
127
|
+
cleanup();
|
|
128
|
+
resolve(new ExtensionClient(endpoint, params));
|
|
129
|
+
});
|
|
130
|
+
const interval = setInterval(
|
|
131
|
+
() => endpoint.notify(EVENT_READY),
|
|
132
|
+
opts.readyIntervalMs ?? 250
|
|
133
|
+
);
|
|
134
|
+
const timeout = setTimeout(() => {
|
|
135
|
+
if (done) return;
|
|
136
|
+
done = true;
|
|
137
|
+
cleanup();
|
|
138
|
+
endpoint.close();
|
|
139
|
+
reject(
|
|
140
|
+
new RpcError("Timed out waiting for host handshake", {
|
|
141
|
+
code: RPC_ERRORS.TIMEOUT,
|
|
142
|
+
reason: "HANDSHAKE_TIMEOUT"
|
|
143
|
+
})
|
|
144
|
+
);
|
|
145
|
+
}, opts.timeoutMs ?? 1e4);
|
|
146
|
+
const cleanup = () => {
|
|
147
|
+
off();
|
|
148
|
+
clearInterval(interval);
|
|
149
|
+
clearTimeout(timeout);
|
|
150
|
+
};
|
|
151
|
+
endpoint.notify(EVENT_READY);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export {
|
|
156
|
+
ExtensionClient,
|
|
157
|
+
connectExtension
|
|
158
|
+
};
|
|
159
|
+
//# sourceMappingURL=chunk-EGWZMA5J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/extension.ts"],"sourcesContent":["import { BusEndpoint, EventHandler } from './endpoint'\nimport { BusPort, windowPort } from './port'\nimport {\n EVENT_HANDSHAKE,\n EVENT_READY,\n Handshake,\n HandshakeContext,\n RPC_ERRORS,\n RpcError,\n SignalKValueEvent,\n StateScope\n} from './protocol'\n\nexport interface ConnectOptions {\n /** Transport. Defaults to window.postMessage to window.parent. */\n port?: BusPort\n /** Interval for re-sending bus.ready until the handshake arrives. */\n readyIntervalMs?: number\n /** How long to wait for the host handshake before rejecting. */\n timeoutMs?: number\n /** Default timeout for host API calls. */\n callTimeoutMs?: number\n onError?: (err: unknown) => void\n}\n\nexport type Unsubscribe = () => Promise<void>\n\n/**\n * The extension side of the bus: one per iframe context (panel, widget, or\n * background runtime). Create via connectExtension().\n */\nexport class ExtensionClient {\n readonly handshake: Handshake\n readonly endpoint: BusEndpoint\n\n constructor(endpoint: BusEndpoint, handshake: Handshake) {\n this.endpoint = endpoint\n this.handshake = handshake\n }\n\n get context(): HandshakeContext {\n return this.handshake.context\n }\n\n get apiVersion(): string {\n return this.handshake.apiVersion\n }\n\n get capabilities(): string[] {\n return this.handshake.capabilities\n }\n\n hasCapability(id: string): boolean {\n return this.handshake.capabilities.includes(id)\n }\n\n /** Call a host API method. */\n call(\n method: string,\n params?: unknown,\n opts?: { timeoutMs?: number }\n ): Promise<unknown> {\n return this.endpoint.call(method, params, opts)\n }\n\n /** Send a notification to the host. */\n notify(method: string, params?: unknown): void {\n this.endpoint.notify(method, params)\n }\n\n /**\n * Subscribe to host events matching wildcard patterns. Registers both the\n * host-side forwarding subscription and local dispatch; the returned\n * function tears down both.\n */\n async subscribe(\n patterns: string[],\n handler: EventHandler\n ): Promise<Unsubscribe> {\n const off = this.endpoint.onEvent(patterns, handler)\n let subscriptionId: string\n try {\n const result = (await this.call('events.subscribe', { patterns })) as {\n subscriptionId: string\n }\n subscriptionId = result.subscriptionId\n } catch (err) {\n off()\n throw err\n }\n return async () => {\n off()\n await this.call('events.unsubscribe', { subscriptionId }).catch(() => {\n // Best-effort: the host may already have dropped the connection.\n })\n }\n }\n\n /** Host-persisted key/value state (see spec: State Storage). */\n readonly state = {\n get: async (\n keys?: string[],\n scope?: StateScope\n ): Promise<Record<string, unknown>> => {\n const result = (await this.call('state.get', {\n ...(scope ? { scope } : {}),\n ...(keys ? { keys } : {})\n })) as { values: Record<string, unknown> }\n return result.values ?? {}\n },\n set: async (\n values: Record<string, unknown>,\n scope?: StateScope\n ): Promise<void> => {\n await this.call('state.set', {\n ...(scope ? { scope } : {}),\n values\n })\n }\n }\n\n /** Signal K data relayed by the host (capabilities signalk.stream / .put). */\n readonly signalk = {\n /**\n * Subscribe to Signal K path values. The host publishes them as\n * `sk.<path>` events; this helper hides the event-name mapping and\n * establishes both the event-forwarding subscription and the host's\n * upstream Signal K subscription.\n */\n subscribe: async (\n paths: string[],\n handler: (ev: SignalKValueEvent) => void\n ): Promise<Unsubscribe> => {\n const patterns = paths.map((p) => `sk.${p}`)\n const offEvents = await this.subscribe(patterns, (_name, params) =>\n handler(params as SignalKValueEvent)\n )\n let subscriptionId: string\n try {\n const result = (await this.call('signalk.subscribe', { paths })) as {\n subscriptionId: string\n }\n subscriptionId = result.subscriptionId\n } catch (err) {\n await offEvents()\n throw err\n }\n return async () => {\n await offEvents()\n await this.call('signalk.unsubscribe', { subscriptionId }).catch(\n () => {}\n )\n }\n },\n put: (path: string, value: unknown): Promise<unknown> => {\n return this.call('signalk.put', { path, value })\n }\n }\n\n close(): void {\n this.endpoint.close()\n }\n}\n\n/**\n * Connect to the host from inside an extension iframe. Sends `bus.ready`\n * (repeating until answered) and resolves once the host's `bus.handshake`\n * arrives.\n */\nexport function connectExtension(\n opts: ConnectOptions = {}\n): Promise<ExtensionClient> {\n // Default transport: postMessage to the embedding window. Origin checks\n // are relaxed to '*' on the extension side because the host page's origin\n // may legitimately differ from the extension asset origin (e.g. a host dev\n // server embedding extension assets served by the Signal K server); the\n // peer-source check in windowPort still applies, and the host side\n // enforces a strict origin for the extension's frame.\n const port =\n opts.port ??\n windowPort((globalThis as unknown as Window).parent as Window, {\n origin: '*'\n })\n const endpoint = new BusEndpoint({\n port,\n callTimeoutMs: opts.callTimeoutMs,\n onError: opts.onError\n })\n return new Promise<ExtensionClient>((resolve, reject) => {\n let done = false\n const off = endpoint.onEvent([EVENT_HANDSHAKE], (_name, params) => {\n if (done) return\n done = true\n cleanup()\n resolve(new ExtensionClient(endpoint, params as Handshake))\n })\n const interval = setInterval(\n () => endpoint.notify(EVENT_READY),\n opts.readyIntervalMs ?? 250\n )\n const timeout = setTimeout(() => {\n if (done) return\n done = true\n cleanup()\n endpoint.close()\n reject(\n new RpcError('Timed out waiting for host handshake', {\n code: RPC_ERRORS.TIMEOUT,\n reason: 'HANDSHAKE_TIMEOUT'\n })\n )\n }, opts.timeoutMs ?? 10_000)\n const cleanup = () => {\n off()\n clearInterval(interval)\n clearTimeout(timeout)\n }\n endpoint.notify(EVENT_READY)\n })\n}\n\nexport * from './protocol'\nexport * from './wildcard'\nexport { BusEndpoint } from './endpoint'\nexport type { MethodHandler, MethodContext, EventHandler } from './endpoint'\nexport * from './port'\n"],"mappings":";;;;;;;;;;AA+BO,IAAM,kBAAN,MAAsB;AAAA,EAClB;AAAA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eAAe,GAAG,CAAC,OAAO,WAAW;AACjE,UAAI,KAAM;AACV,aAAO;AACP,cAAQ;AACR,cAAQ,IAAI,gBAAgB,UAAU,MAAmB,CAAC;AAAA,IAC5D,CAAC;AACD,UAAM,WAAW;AAAA,MACf,MAAM,SAAS,OAAO,WAAW;AAAA,MACjC,KAAK,mBAAmB;AAAA,IAC1B;AACA,UAAM,UAAU,WAAW,MAAM;AAC/B,UAAI,KAAM;AACV,aAAO;AACP,cAAQ;AACR,eAAS,MAAM;AACf;AAAA,QACE,IAAI,SAAS,wCAAwC;AAAA,UACnD,MAAM,WAAW;AAAA,UACjB,QAAQ;AAAA,QACV,CAAC;AAAA,MACH;AAAA,IACF,GAAG,KAAK,aAAa,GAAM;AAC3B,UAAM,UAAU,MAAM;AACpB,UAAI;AACJ,oBAAc,QAAQ;AACtB,mBAAa,OAAO;AAAA,IACtB;AACA,aAAS,OAAO,WAAW;AAAA,EAC7B,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BusEndpoint,
|
|
3
|
+
EVENT_HANDSHAKE,
|
|
4
|
+
EVENT_READY,
|
|
5
|
+
RPC_ERRORS,
|
|
6
|
+
RpcError,
|
|
7
|
+
matchesAny
|
|
8
|
+
} from "./chunk-ZYQKQSOC.js";
|
|
9
|
+
|
|
10
|
+
// src/host.ts
|
|
11
|
+
var HostConnection = class {
|
|
12
|
+
endpoint;
|
|
13
|
+
context;
|
|
14
|
+
hostInfo;
|
|
15
|
+
subs = /* @__PURE__ */ new Map();
|
|
16
|
+
onSubscriptionsChanged;
|
|
17
|
+
subSeq = 0;
|
|
18
|
+
constructor(opts) {
|
|
19
|
+
this.hostInfo = opts.hostInfo;
|
|
20
|
+
this.context = opts.context;
|
|
21
|
+
this.onSubscriptionsChanged = opts.onSubscriptionsChanged;
|
|
22
|
+
this.endpoint = new BusEndpoint({
|
|
23
|
+
port: opts.port,
|
|
24
|
+
callTimeoutMs: opts.callTimeoutMs,
|
|
25
|
+
onError: opts.onError
|
|
26
|
+
});
|
|
27
|
+
for (const [name, handler] of Object.entries(opts.methods ?? {})) {
|
|
28
|
+
this.endpoint.registerMethod(name, handler);
|
|
29
|
+
}
|
|
30
|
+
this.endpoint.registerMethod(
|
|
31
|
+
"events.subscribe",
|
|
32
|
+
(params) => this.handleSubscribe(params)
|
|
33
|
+
);
|
|
34
|
+
this.endpoint.registerMethod(
|
|
35
|
+
"events.unsubscribe",
|
|
36
|
+
(params) => this.handleUnsubscribe(params)
|
|
37
|
+
);
|
|
38
|
+
this.endpoint.onEvent([EVENT_READY], () => this.sendHandshake());
|
|
39
|
+
}
|
|
40
|
+
registerMethod(name, handler) {
|
|
41
|
+
this.endpoint.registerMethod(name, handler);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Publish an event to this context. Delivered only when the context has a
|
|
45
|
+
* matching subscription; returns whether it was delivered.
|
|
46
|
+
*/
|
|
47
|
+
publish(eventName, params) {
|
|
48
|
+
if (!this.hasSubscriber(eventName)) return false;
|
|
49
|
+
this.endpoint.notify(eventName, params);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
hasSubscriber(eventName) {
|
|
53
|
+
for (const [, patterns] of this.subs) {
|
|
54
|
+
if (matchesAny(patterns, eventName)) return true;
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
/** Union of currently subscribed patterns. */
|
|
59
|
+
subscribedPatterns() {
|
|
60
|
+
const all = /* @__PURE__ */ new Set();
|
|
61
|
+
for (const [, patterns] of this.subs) {
|
|
62
|
+
for (const p of patterns) all.add(p);
|
|
63
|
+
}
|
|
64
|
+
return [...all];
|
|
65
|
+
}
|
|
66
|
+
close() {
|
|
67
|
+
this.endpoint.close();
|
|
68
|
+
this.subs.clear();
|
|
69
|
+
}
|
|
70
|
+
sendHandshake() {
|
|
71
|
+
this.endpoint.notify(EVENT_HANDSHAKE, {
|
|
72
|
+
...this.hostInfo,
|
|
73
|
+
context: this.context
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
handleSubscribe(params) {
|
|
77
|
+
const patterns = params?.patterns;
|
|
78
|
+
if (!Array.isArray(patterns) || patterns.length === 0 || !patterns.every((p) => typeof p === "string" && p.length > 0)) {
|
|
79
|
+
throw new RpcError("events.subscribe requires a non-empty patterns array", {
|
|
80
|
+
code: RPC_ERRORS.INVALID_PARAMS,
|
|
81
|
+
reason: "INVALID_PATTERNS"
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const subscriptionId = `sub-${++this.subSeq}`;
|
|
85
|
+
this.subs.set(subscriptionId, patterns);
|
|
86
|
+
this.onSubscriptionsChanged?.(this.subscribedPatterns());
|
|
87
|
+
return { subscriptionId };
|
|
88
|
+
}
|
|
89
|
+
handleUnsubscribe(params) {
|
|
90
|
+
const id = params?.subscriptionId;
|
|
91
|
+
if (typeof id !== "string" || !this.subs.has(id)) {
|
|
92
|
+
throw new RpcError("Unknown subscriptionId", {
|
|
93
|
+
code: RPC_ERRORS.INVALID_PARAMS,
|
|
94
|
+
reason: "UNKNOWN_SUBSCRIPTION"
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
this.subs.delete(id);
|
|
98
|
+
this.onSubscriptionsChanged?.(this.subscribedPatterns());
|
|
99
|
+
return {};
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export {
|
|
104
|
+
HostConnection
|
|
105
|
+
};
|
|
106
|
+
//# sourceMappingURL=chunk-JJEZW66E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/host.ts"],"sourcesContent":["import { BusEndpoint, MethodHandler } from './endpoint'\nimport { BusPort } from './port'\nimport {\n EVENT_HANDSHAKE,\n EVENT_READY,\n HandshakeContext,\n RPC_ERRORS,\n RpcError\n} from './protocol'\nimport { matchesAny } from './wildcard'\n\nexport interface HostInfo {\n host: string\n hostVersion: string\n apiVersion: string\n capabilities: string[]\n}\n\nexport interface HostConnectionOptions {\n port: BusPort\n hostInfo: HostInfo\n context: HandshakeContext\n /** Host API methods (e.g. 'state.get', 'signalk.subscribe', 'map.center'). */\n methods?: Record<string, MethodHandler>\n callTimeoutMs?: number\n onError?: (err: unknown) => void\n /**\n * Called whenever the union of subscribed event patterns changes, with the\n * current pattern list. Lets the host start/stop upstream work lazily.\n */\n onSubscriptionsChanged?: (patterns: string[]) => void\n}\n\n/**\n * The host side of one extension context (one iframe). Sends the handshake\n * in reply to `bus.ready`, dispatches host API methods, and tracks the\n * context's event subscriptions so `publish()` only forwards events the\n * context asked for.\n */\nexport class HostConnection {\n readonly endpoint: BusEndpoint\n readonly context: HandshakeContext\n\n private readonly hostInfo: HostInfo\n private readonly subs = new Map<string, string[]>()\n private readonly onSubscriptionsChanged?: (patterns: string[]) => void\n private subSeq = 0\n\n constructor(opts: HostConnectionOptions) {\n this.hostInfo = opts.hostInfo\n this.context = opts.context\n this.onSubscriptionsChanged = opts.onSubscriptionsChanged\n this.endpoint = new BusEndpoint({\n port: opts.port,\n callTimeoutMs: opts.callTimeoutMs,\n onError: opts.onError\n })\n for (const [name, handler] of Object.entries(opts.methods ?? {})) {\n this.endpoint.registerMethod(name, handler)\n }\n this.endpoint.registerMethod('events.subscribe', (params) =>\n this.handleSubscribe(params)\n )\n this.endpoint.registerMethod('events.unsubscribe', (params) =>\n this.handleUnsubscribe(params)\n )\n this.endpoint.onEvent([EVENT_READY], () => this.sendHandshake())\n }\n\n registerMethod(name: string, handler: MethodHandler): void {\n this.endpoint.registerMethod(name, handler)\n }\n\n /**\n * Publish an event to this context. Delivered only when the context has a\n * matching subscription; returns whether it was delivered.\n */\n publish(eventName: string, params?: unknown): boolean {\n if (!this.hasSubscriber(eventName)) return false\n this.endpoint.notify(eventName, params)\n return true\n }\n\n hasSubscriber(eventName: string): boolean {\n for (const [, patterns] of this.subs) {\n if (matchesAny(patterns, eventName)) return true\n }\n return false\n }\n\n /** Union of currently subscribed patterns. */\n subscribedPatterns(): string[] {\n const all = new Set<string>()\n for (const [, patterns] of this.subs) {\n for (const p of patterns) all.add(p)\n }\n return [...all]\n }\n\n close(): void {\n this.endpoint.close()\n this.subs.clear()\n }\n\n private sendHandshake(): void {\n this.endpoint.notify(EVENT_HANDSHAKE, {\n ...this.hostInfo,\n context: this.context\n })\n }\n\n private handleSubscribe(params: unknown): { subscriptionId: string } {\n const patterns = (params as { patterns?: unknown })?.patterns\n if (\n !Array.isArray(patterns) ||\n patterns.length === 0 ||\n !patterns.every((p) => typeof p === 'string' && p.length > 0)\n ) {\n throw new RpcError('events.subscribe requires a non-empty patterns array', {\n code: RPC_ERRORS.INVALID_PARAMS,\n reason: 'INVALID_PATTERNS'\n })\n }\n const subscriptionId = `sub-${++this.subSeq}`\n this.subs.set(subscriptionId, patterns as string[])\n this.onSubscriptionsChanged?.(this.subscribedPatterns())\n return { subscriptionId }\n }\n\n private handleUnsubscribe(params: unknown): Record<string, never> {\n const id = (params as { subscriptionId?: unknown })?.subscriptionId\n if (typeof id !== 'string' || !this.subs.has(id)) {\n throw new RpcError('Unknown subscriptionId', {\n code: RPC_ERRORS.INVALID_PARAMS,\n reason: 'UNKNOWN_SUBSCRIPTION'\n })\n }\n this.subs.delete(id)\n this.onSubscriptionsChanged?.(this.subscribedPatterns())\n return {}\n }\n}\n\nexport * from './protocol'\nexport * from './wildcard'\nexport { BusEndpoint } from './endpoint'\nexport type { MethodHandler, MethodContext, EventHandler } from './endpoint'\nexport * from './port'\n"],"mappings":";;;;;;;;;;AAuCO,IAAM,iBAAN,MAAqB;AAAA,EACjB;AAAA,EACA;AAAA,EAEQ;AAAA,EACA,OAAO,oBAAI,IAAsB;AAAA,EACjC;AAAA,EACT,SAAS;AAAA,EAEjB,YAAY,MAA6B;AACvC,SAAK,WAAW,KAAK;AACrB,SAAK,UAAU,KAAK;AACpB,SAAK,yBAAyB,KAAK;AACnC,SAAK,WAAW,IAAI,YAAY;AAAA,MAC9B,MAAM,KAAK;AAA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