@wargasipil/connectrpc-service-worker 0.0.0-stage → 0.1.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/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.md +404 -2
- package/dist/caller.d.ts +30 -0
- package/dist/caller.d.ts.map +1 -0
- package/dist/caller.js +15 -0
- package/dist/caller.js.map +1 -0
- package/dist/client.d.ts +63 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +304 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime.d.ts +75 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +22 -0
- package/dist/runtime.js.map +1 -0
- package/dist/server.d.ts +43 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +285 -0
- package/dist/server.js.map +1 -0
- package/dist/wire.d.ts +73 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +113 -0
- package/dist/wire.js.map +1 -0
- package/package.json +63 -4
- package/src/caller.ts +34 -0
- package/src/client.ts +400 -0
- package/src/index.ts +22 -0
- package/src/runtime.ts +82 -0
- package/src/server.ts +337 -0
- package/src/wire.ts +158 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are listed here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0]
|
|
10
|
+
|
|
11
|
+
First release.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- `createServiceWorkerTransport()`: a Connect transport that calls services in
|
|
16
|
+
an extension's service worker over a `chrome.runtime` port. Works from the
|
|
17
|
+
extension's pages, its content scripts, and websites listed in
|
|
18
|
+
`externally_connectable`.
|
|
19
|
+
- `serveServiceWorker()`: serves Connect services from the service worker.
|
|
20
|
+
The extension's own pages and content scripts may always call; outside
|
|
21
|
+
callers only when their origin is in `allowOrigins`.
|
|
22
|
+
- `callerKey`: the caller (extension page, content script or website, its
|
|
23
|
+
origin and tab) for service code, interceptors and request gates.
|
|
24
|
+
- Unary and server-streaming methods. Client-streaming and bidirectional
|
|
25
|
+
methods fail with `unimplemented`.
|
|
26
|
+
- Keep-alive pings while a call is open, so Chrome doesn't stop the service
|
|
27
|
+
worker in the middle of a long call or stream.
|
|
28
|
+
- Raw bytes in messages for extensions that use structured clone
|
|
29
|
+
(`"message_serialization": "structured_clone"`, Chrome 148+); base64 text
|
|
30
|
+
otherwise.
|
|
31
|
+
- Peer dependencies: `@connectrpc/connect` ^2.3.0 and `@bufbuild/protobuf`
|
|
32
|
+
^2.7.0.
|
|
33
|
+
|
|
34
|
+
[Unreleased]: https://github.com/wargasipil/connectrpc-service-worker/compare/v0.1.0...HEAD
|
|
35
|
+
[0.1.0]: https://github.com/wargasipil/connectrpc-service-worker/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wargasipil
|
|
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
CHANGED
|
@@ -1,3 +1,405 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @wargasipil/connectrpc-service-worker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Call [Connect](https://connectrpc.com/) services that run in a Chrome
|
|
4
|
+
extension's service worker, from the extension's popup, side panel, options
|
|
5
|
+
page and content scripts, and from websites you allow. Calls go over
|
|
6
|
+
`chrome.runtime` ports instead of HTTP.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { createClient } from "@connectrpc/connect";
|
|
10
|
+
import { createServiceWorkerTransport } from "@wargasipil/connectrpc-service-worker";
|
|
11
|
+
|
|
12
|
+
const transport = createServiceWorkerTransport();
|
|
13
|
+
const tabs = createClient(TabService, transport);
|
|
14
|
+
|
|
15
|
+
const { title } = await tabs.getTitle({ tabId: 1 });
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Instead of `chrome.runtime.sendMessage({ type: "getTitle", ... })` and a
|
|
19
|
+
`switch` in the service worker, you get typed clients and services from a
|
|
20
|
+
`.proto` file, errors with codes, deadlines, cancellation, server streaming and
|
|
21
|
+
interceptors. The client code does not depend on where the service runs: the
|
|
22
|
+
same client works against a real Connect server, or `createRouterTransport` in
|
|
23
|
+
tests.
|
|
24
|
+
|
|
25
|
+
- [What you get](#what-you-get)
|
|
26
|
+
- [Install](#install)
|
|
27
|
+
- [Quick start](#quick-start)
|
|
28
|
+
- [Calling from a website](#calling-from-a-website)
|
|
29
|
+
- [Knowing who called](#knowing-who-called)
|
|
30
|
+
- [Security](#security)
|
|
31
|
+
- [The service worker's lifecycle](#the-service-workers-lifecycle)
|
|
32
|
+
- [API](#api)
|
|
33
|
+
- [Errors](#errors)
|
|
34
|
+
- [Testing your services](#testing-your-services)
|
|
35
|
+
- [Example extension](#example-extension)
|
|
36
|
+
- [Compatibility](#compatibility)
|
|
37
|
+
- [How it works](docs/protocol.md)
|
|
38
|
+
- [Development](CONTRIBUTING.md)
|
|
39
|
+
|
|
40
|
+
## What you get
|
|
41
|
+
|
|
42
|
+
| | |
|
|
43
|
+
|---|---|
|
|
44
|
+
| Unary methods | Yes |
|
|
45
|
+
| Server-streaming methods | Yes |
|
|
46
|
+
| Client-streaming and bidirectional methods | Not yet: they fail with `unimplemented` |
|
|
47
|
+
| Callers inside the extension (pages, content scripts) | Always allowed |
|
|
48
|
+
| Websites in `externally_connectable`, other extensions | Only origins you list in `allowOrigins` |
|
|
49
|
+
| Protobuf binary and JSON formats | Yes (`useBinaryFormat`) |
|
|
50
|
+
| Interceptors, request gates, deadlines, cancellation | Yes, as in Connect |
|
|
51
|
+
| Long calls and streams | Kept alive with pings, so Chrome doesn't stop the service worker mid-call |
|
|
52
|
+
| Structured clone messaging (Chrome 148+) | Used automatically: raw bytes instead of base64 |
|
|
53
|
+
| Runtime dependencies | None besides the peer dependencies `@connectrpc/connect` (2.3+) and `@bufbuild/protobuf` (2.7+) |
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
npm install @wargasipil/connectrpc-service-worker @connectrpc/connect @bufbuild/protobuf
|
|
59
|
+
npm install --save-dev @bufbuild/buf @bufbuild/protoc-gen-es
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Generate TypeScript from your `.proto` files with `protoc-gen-es`, as for any
|
|
63
|
+
Connect-ES v2 project. A `buf.gen.yaml`:
|
|
64
|
+
|
|
65
|
+
```yaml
|
|
66
|
+
version: v2
|
|
67
|
+
inputs:
|
|
68
|
+
- directory: proto
|
|
69
|
+
plugins:
|
|
70
|
+
- local: protoc-gen-es
|
|
71
|
+
out: src/gen
|
|
72
|
+
opt: [target=ts]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`@types/chrome` is not needed: the package declares the few `chrome.runtime`
|
|
76
|
+
types it uses.
|
|
77
|
+
|
|
78
|
+
## Quick start
|
|
79
|
+
|
|
80
|
+
### 1. Define the service
|
|
81
|
+
|
|
82
|
+
```proto
|
|
83
|
+
syntax = "proto3";
|
|
84
|
+
package tabs.v1;
|
|
85
|
+
|
|
86
|
+
service TabService {
|
|
87
|
+
rpc GetTitle(GetTitleRequest) returns (GetTitleResponse);
|
|
88
|
+
// Server streaming: one message per tab update.
|
|
89
|
+
rpc WatchTab(WatchTabRequest) returns (stream TabUpdate);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
message GetTitleRequest { int32 tab_id = 1; }
|
|
93
|
+
message GetTitleResponse { string title = 1; }
|
|
94
|
+
message WatchTabRequest { int32 tab_id = 1; }
|
|
95
|
+
message TabUpdate { string status = 1; string url = 2; }
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Run `npx buf generate`.
|
|
99
|
+
|
|
100
|
+
### 2. Serve it from the service worker
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// background.ts, the extension's service worker
|
|
104
|
+
import { Code, ConnectError } from "@connectrpc/connect";
|
|
105
|
+
import { serveServiceWorker } from "@wargasipil/connectrpc-service-worker";
|
|
106
|
+
import { TabService } from "./gen/tabs/v1/tabs_pb";
|
|
107
|
+
|
|
108
|
+
serveServiceWorker({
|
|
109
|
+
routes: (router) =>
|
|
110
|
+
router.service(TabService, {
|
|
111
|
+
async getTitle(req) {
|
|
112
|
+
const tab = await chrome.tabs.get(req.tabId).catch(() => undefined);
|
|
113
|
+
if (!tab) throw new ConnectError(`no tab ${req.tabId}`, Code.NotFound);
|
|
114
|
+
return { title: tab.title ?? "" };
|
|
115
|
+
},
|
|
116
|
+
async *watchTab(req, ctx) {
|
|
117
|
+
// One message a second, until the caller stops reading or cancels.
|
|
118
|
+
while (!ctx.signal.aborted) {
|
|
119
|
+
const tab = await chrome.tabs.get(req.tabId);
|
|
120
|
+
yield { status: tab.status ?? "", url: tab.url ?? "" };
|
|
121
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Call `serveServiceWorker` at the top level of the script, not inside an
|
|
129
|
+
`async` function after an `await`. When a call wakes a stopped service worker,
|
|
130
|
+
Chrome only delivers the connection to listeners that were added while the
|
|
131
|
+
script first ran.
|
|
132
|
+
|
|
133
|
+
### 3. Call it from the popup, side panel, options page or a content script
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// popup.ts, sidepanel.ts, content.ts: the same code everywhere
|
|
137
|
+
import { createClient } from "@connectrpc/connect";
|
|
138
|
+
import { createServiceWorkerTransport } from "@wargasipil/connectrpc-service-worker";
|
|
139
|
+
import { TabService } from "./gen/tabs/v1/tabs_pb";
|
|
140
|
+
|
|
141
|
+
const tabs = createClient(TabService, createServiceWorkerTransport());
|
|
142
|
+
|
|
143
|
+
const { title } = await tabs.getTitle({ tabId: 42 });
|
|
144
|
+
|
|
145
|
+
for await (const update of tabs.watchTab({ tabId: 42 })) {
|
|
146
|
+
console.log(update.status, update.url);
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Everything else works as with any Connect client: call options such as
|
|
151
|
+
`{ timeoutMs: 5000 }`, `{ signal }`, `{ headers }`, `onHeader` and
|
|
152
|
+
`onTrailer`, and `ConnectError` with a `code` when something fails.
|
|
153
|
+
|
|
154
|
+
No manifest permission is needed for this; ports between an extension's own
|
|
155
|
+
parts are always available.
|
|
156
|
+
|
|
157
|
+
## Calling from a website
|
|
158
|
+
|
|
159
|
+
A website can call the extension too. Two things have to allow it:
|
|
160
|
+
|
|
161
|
+
1. **Chrome:** the site must match the manifest's `externally_connectable`.
|
|
162
|
+
Chrome doesn't let other sites connect to the extension at all.
|
|
163
|
+
|
|
164
|
+
```json
|
|
165
|
+
{
|
|
166
|
+
"externally_connectable": { "matches": ["https://app.example.com/*"] }
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
2. **The service worker:** the site's origin must be in `allowOrigins`. Without
|
|
171
|
+
it, every outside call is refused with `permission_denied`.
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
serveServiceWorker({
|
|
175
|
+
routes,
|
|
176
|
+
allowOrigins: ["https://app.example.com"],
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
On the website, pass the extension's ID:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
const transport = createServiceWorkerTransport({ extensionId: "abcdefghijklmnopabcdefghijklmnop" });
|
|
184
|
+
const tabs = createClient(TabService, transport);
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Creating the transport never throws. If the extension is not installed, or the
|
|
188
|
+
site is not allowed, calls fail with `unavailable` (or `permission_denied`), so
|
|
189
|
+
the site can show a "please install the extension" message.
|
|
190
|
+
|
|
191
|
+
`allowOrigins` can also be a function, `(origin, sender) => boolean`, for
|
|
192
|
+
example to allow every subdomain you own.
|
|
193
|
+
|
|
194
|
+
Other extensions call the same way, with your extension's ID. List them in
|
|
195
|
+
`externally_connectable.ids` (once the manifest has `externally_connectable`,
|
|
196
|
+
Chrome only lets in the extensions listed there), and their origin,
|
|
197
|
+
`chrome-extension://<their id>`, in `allowOrigins`.
|
|
198
|
+
|
|
199
|
+
## Knowing who called
|
|
200
|
+
|
|
201
|
+
The service worker sees who called through `callerKey`, in service methods,
|
|
202
|
+
interceptors and request gates:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { callerKey } from "@wargasipil/connectrpc-service-worker";
|
|
206
|
+
|
|
207
|
+
router.service(TabService, {
|
|
208
|
+
async getTitle(req, ctx) {
|
|
209
|
+
const caller = ctx.values.get(callerKey);
|
|
210
|
+
caller?.external; // true for websites and other extensions
|
|
211
|
+
caller?.origin; // "chrome-extension://<id>", or the web page's origin
|
|
212
|
+
caller?.sender.tab; // set for content scripts and websites: the calling tab
|
|
213
|
+
caller?.sender.url; // the calling page or frame
|
|
214
|
+
return { title: (await chrome.tabs.get(req.tabId)).title ?? "" };
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
For a content script, `origin` and `sender.url` are those of the web page it
|
|
220
|
+
runs in, and `external` is false: it is part of your extension.
|
|
221
|
+
|
|
222
|
+
## Security
|
|
223
|
+
|
|
224
|
+
- **Your own pages and content scripts can always call.** Content scripts run
|
|
225
|
+
inside web pages, which may be hostile. Treat what a content script sends as
|
|
226
|
+
you would treat input from that page. `caller.sender.tab` tells you a call
|
|
227
|
+
came from a tab.
|
|
228
|
+
- **Outside callers are refused unless you allow them.** Chrome enforces
|
|
229
|
+
`externally_connectable`, and the service worker checks `allowOrigins`
|
|
230
|
+
(exact origin match, so `https://app.example.com` does not let in
|
|
231
|
+
`https://app.example.com.evil.net`). A function in `allowOrigins` that
|
|
232
|
+
throws counts as "no".
|
|
233
|
+
- **Limit methods per caller** with a request gate. It runs before the request
|
|
234
|
+
message is read:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
serveServiceWorker({
|
|
238
|
+
routes,
|
|
239
|
+
allowOrigins: ["https://app.example.com"],
|
|
240
|
+
requestGate(ctx) {
|
|
241
|
+
if (ctx.values.get(callerKey)?.external && ctx.method.name !== "GetTitle") {
|
|
242
|
+
throw new ConnectError("only GetTitle is open to websites", Code.PermissionDenied);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
- **Messages are checked.** A malformed message ends the call with
|
|
249
|
+
`invalid_argument`. Set `readMaxBytes` to bound request size; the service
|
|
250
|
+
worker stops a caller that sends more, before the request is complete.
|
|
251
|
+
|
|
252
|
+
## The service worker's lifecycle
|
|
253
|
+
|
|
254
|
+
- **Starting.** A call to a stopped service worker starts it. The caller waits
|
|
255
|
+
up to `acceptTimeoutMs` (10 s) for it to answer.
|
|
256
|
+
- **Long calls.** Chrome stops an idle service worker after about 30 seconds.
|
|
257
|
+
While a call is open, the caller sends a ping every 20 seconds, which counts
|
|
258
|
+
as activity (Chrome 114+). A slow method or a long stream is not cut off.
|
|
259
|
+
The pings stop when the call ends.
|
|
260
|
+
- **Stopping.** If Chrome stops or reloads the service worker anyway, every
|
|
261
|
+
call in flight fails with `unavailable`. The next call starts it again. Keep
|
|
262
|
+
state in `chrome.storage`, not in variables, as for any extension service worker.
|
|
263
|
+
- **From the service worker itself.** `chrome.runtime.connect` does not reach
|
|
264
|
+
listeners in the same context, so the service worker can't call its own
|
|
265
|
+
services through this transport. Use `createRouterTransport` with the same
|
|
266
|
+
routes, or call your functions directly.
|
|
267
|
+
|
|
268
|
+
## API
|
|
269
|
+
|
|
270
|
+
### `createServiceWorkerTransport(options?)`
|
|
271
|
+
|
|
272
|
+
Returns a Connect `Transport`. All options are optional.
|
|
273
|
+
|
|
274
|
+
| Option | Default | |
|
|
275
|
+
|---|---|---|
|
|
276
|
+
| `extensionId` | this extension | The extension to call. Required on websites. |
|
|
277
|
+
| `portName` | `"connectrpc-service-worker"` | Must match the server's. |
|
|
278
|
+
| `useBinaryFormat` | `true` | `false` sends JSON. |
|
|
279
|
+
| `interceptors` | `[]` | Connect interceptors. |
|
|
280
|
+
| `jsonOptions`, `binaryOptions` | | As in Connect. |
|
|
281
|
+
| `defaultTimeoutMs` | none | Timeout for calls that don't set one. |
|
|
282
|
+
| `readMaxBytes`, `writeMaxBytes` | ~4 GiB | Largest response / request message. |
|
|
283
|
+
| `acceptTimeoutMs` | `10000` | How long to wait for the service worker to take the call. `0` waits forever. |
|
|
284
|
+
| `keepAliveIntervalMs` | `20000` | Ping interval while a call is open. `0` turns pings off. |
|
|
285
|
+
| `maxChunkBytes` | 1 MiB | Largest piece of a body per port message. |
|
|
286
|
+
| `payloadEncoding` | `"auto"` | `"auto"`, `"base64"` or `"raw"`; see below. |
|
|
287
|
+
| `runtime` | `chrome.runtime` | A `chrome.runtime` to use instead of the global one. |
|
|
288
|
+
|
|
289
|
+
Invalid option values throw a `TypeError` when the transport is created.
|
|
290
|
+
|
|
291
|
+
### `serveServiceWorker(options)`
|
|
292
|
+
|
|
293
|
+
Starts serving and returns `{ close() }`. `close()` stops taking calls and ends
|
|
294
|
+
the calls in flight with `unavailable`.
|
|
295
|
+
|
|
296
|
+
| Option | Default | |
|
|
297
|
+
|---|---|---|
|
|
298
|
+
| `routes` | required | `(router) => router.service(MyService, impl)`. |
|
|
299
|
+
| `allowOrigins` | `[]` | Origins of outside callers that may call, or `(origin, sender) => boolean`. |
|
|
300
|
+
| `portName` | `"connectrpc-service-worker"` | Must match the transport's. |
|
|
301
|
+
| `maxChunkBytes` | 1 MiB | Largest piece of a body per port message. |
|
|
302
|
+
| `payloadEncoding` | `"auto"` | See below. |
|
|
303
|
+
| `runtime` | `chrome.runtime` | For tests. |
|
|
304
|
+
| `interceptors`, `requestGate`, `readMaxBytes`, `writeMaxBytes`, `maxTimeoutMs`, `jsonOptions`, `binaryOptions`, `shutdownSignal`, `requireConnectProtocolHeader` | Connect's | Passed to `createConnectRouter`. |
|
|
305
|
+
|
|
306
|
+
It throws if `chrome.runtime.onConnect` is missing (not in an extension) or an
|
|
307
|
+
option is invalid.
|
|
308
|
+
|
|
309
|
+
### `callerKey`, `Caller`
|
|
310
|
+
|
|
311
|
+
A context key holding `{ external, origin, sender }` for the current call. It
|
|
312
|
+
is `undefined` when the service runs some other way, for example under
|
|
313
|
+
`createRouterTransport`.
|
|
314
|
+
|
|
315
|
+
### `payloadEncoding`
|
|
316
|
+
|
|
317
|
+
Chrome copies port messages as JSON unless the manifest sets
|
|
318
|
+
`"message_serialization": "structured_clone"` (Chrome 148+). JSON can't carry
|
|
319
|
+
a `Uint8Array`, so bytes go as base64 text by default. With `"auto"`, an
|
|
320
|
+
extension that uses structured clone sends raw bytes, which saves the base64
|
|
321
|
+
work and a third of the size. Web pages can't read the manifest and always
|
|
322
|
+
send base64; the service worker reads both. Set `"base64"` to force text
|
|
323
|
+
everywhere.
|
|
324
|
+
|
|
325
|
+
## Errors
|
|
326
|
+
|
|
327
|
+
| Situation | Code |
|
|
328
|
+
|---|---|
|
|
329
|
+
| Extension not installed, site not in `externally_connectable`, service worker not serving, port closed mid-call | `unavailable` |
|
|
330
|
+
| Outside caller not in `allowOrigins` | `permission_denied` |
|
|
331
|
+
| Method not served, or a client-streaming / bidirectional method | `unimplemented` |
|
|
332
|
+
| Deadline passed | `deadline_exceeded` |
|
|
333
|
+
| Caller aborted | `canceled` |
|
|
334
|
+
| Request bigger than the server's `readMaxBytes` | `resource_exhausted` |
|
|
335
|
+
| Error thrown by your service code | its own code, message and metadata |
|
|
336
|
+
|
|
337
|
+
`unavailable` is the one to retry. The full list is in
|
|
338
|
+
[docs/protocol.md](docs/protocol.md#failures-and-their-codes).
|
|
339
|
+
|
|
340
|
+
## Testing your services
|
|
341
|
+
|
|
342
|
+
Service code doesn't need Chrome to be tested. Run it with Connect's
|
|
343
|
+
`createRouterTransport`, and set a caller with a server interceptor when the
|
|
344
|
+
code reads `callerKey`:
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
import { createClient, createRouterTransport } from "@connectrpc/connect";
|
|
348
|
+
import { callerKey } from "@wargasipil/connectrpc-service-worker";
|
|
349
|
+
|
|
350
|
+
const transport = createRouterTransport(routes, {
|
|
351
|
+
router: {
|
|
352
|
+
interceptors: [
|
|
353
|
+
(next) => (req) => {
|
|
354
|
+
req.contextValues.set(callerKey, { external: true, origin: "https://app.example.com", sender: {} });
|
|
355
|
+
return next(req);
|
|
356
|
+
},
|
|
357
|
+
],
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
const client = createClient(TabService, transport);
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
## Example extension
|
|
364
|
+
|
|
365
|
+
[`example/`](example/) is a small extension that serves a test service and
|
|
366
|
+
calls it from its popup, a content script and a website. The package's
|
|
367
|
+
end-to-end tests load it into Chromium.
|
|
368
|
+
|
|
369
|
+
```sh
|
|
370
|
+
npm install
|
|
371
|
+
npm run build
|
|
372
|
+
npm run example:build
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Then open `chrome://extensions`, turn on Developer mode, choose **Load
|
|
376
|
+
unpacked** and pick `example/dist/extension`. Click the extension's icon to
|
|
377
|
+
open the popup. See [example/README.md](example/README.md).
|
|
378
|
+
|
|
379
|
+
## Linking the package locally
|
|
380
|
+
|
|
381
|
+
When an app uses this package from a folder (`npm install ../connectrpc-service-worker`)
|
|
382
|
+
or a git submodule, Vite can load two copies of the shared libraries. Add them
|
|
383
|
+
to `resolve.dedupe` in the app's `vite.config.ts`:
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
resolve: { dedupe: ["@connectrpc/connect", "@bufbuild/protobuf"] }
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
## Compatibility
|
|
390
|
+
|
|
391
|
+
- Chrome and Chromium with Manifest V3. Chrome 114 or newer, for the
|
|
392
|
+
keep-alive pings to count. Structured clone messaging needs Chrome 148.
|
|
393
|
+
- `@connectrpc/connect` 2.3.0 or newer, and the `@bufbuild/protobuf` it
|
|
394
|
+
needs (2.7.0 or newer). Older Connect 2.x releases lack `requestGate`
|
|
395
|
+
(before 2.2.0), and don't cancel a stream when the reader stops early
|
|
396
|
+
(before 2.3.0): the service worker would keep sending to a page that
|
|
397
|
+
stopped reading.
|
|
398
|
+
- Code generated by `protoc-gen-es` needs a `@bufbuild/protobuf` at least as
|
|
399
|
+
new as the generator; keep the two on the same version.
|
|
400
|
+
- The end-to-end tests run in Playwright's Chromium. Other Chromium browsers
|
|
401
|
+
(Edge, Brave) and Firefox have not been tested.
|
|
402
|
+
|
|
403
|
+
## License
|
|
404
|
+
|
|
405
|
+
[MIT](LICENSE)
|
package/dist/caller.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Sender } from "./runtime.js";
|
|
2
|
+
/** Who made a call, as seen by the service worker. */
|
|
3
|
+
export interface Caller {
|
|
4
|
+
/**
|
|
5
|
+
* True when the call came from outside this extension: a web page listed
|
|
6
|
+
* in the manifest's `externally_connectable`, or another extension.
|
|
7
|
+
* False for this extension's own pages and content scripts.
|
|
8
|
+
*/
|
|
9
|
+
external: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Origin of the page or frame that opened the port, such as
|
|
12
|
+
* "https://app.example.com" or "chrome-extension://<id>". For a content
|
|
13
|
+
* script this is the origin of the web page it runs in.
|
|
14
|
+
*/
|
|
15
|
+
origin: string | undefined;
|
|
16
|
+
/** Chrome's `MessageSender` for the port. `sender.tab` is set for content scripts and web pages. */
|
|
17
|
+
sender: Sender;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Context key holding the Caller of the current call. Read it in a service
|
|
21
|
+
* method, an interceptor or a request gate:
|
|
22
|
+
*
|
|
23
|
+
* const caller = ctx.values.get(callerKey);
|
|
24
|
+
* if (caller?.external) throw new ConnectError("not for websites", Code.PermissionDenied);
|
|
25
|
+
*
|
|
26
|
+
* It is undefined when the service runs without serveServiceWorker, for
|
|
27
|
+
* example under createRouterTransport in tests.
|
|
28
|
+
*/
|
|
29
|
+
export declare const callerKey: import("@connectrpc/connect").ContextKey<Caller | undefined>;
|
|
30
|
+
//# sourceMappingURL=caller.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"caller.d.ts","sourceRoot":"","sources":["../src/caller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,sDAAsD;AACtD,MAAM,WAAW,MAAM;IACrB;;;;OAIG;IACH,QAAQ,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,oGAAoG;IACpG,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,8DAEpB,CAAC"}
|
package/dist/caller.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createContextKey } from "@connectrpc/connect";
|
|
2
|
+
/**
|
|
3
|
+
* Context key holding the Caller of the current call. Read it in a service
|
|
4
|
+
* method, an interceptor or a request gate:
|
|
5
|
+
*
|
|
6
|
+
* const caller = ctx.values.get(callerKey);
|
|
7
|
+
* if (caller?.external) throw new ConnectError("not for websites", Code.PermissionDenied);
|
|
8
|
+
*
|
|
9
|
+
* It is undefined when the service runs without serveServiceWorker, for
|
|
10
|
+
* example under createRouterTransport in tests.
|
|
11
|
+
*/
|
|
12
|
+
export const callerKey = createContextKey(undefined, {
|
|
13
|
+
description: "@wargasipil/connectrpc-service-worker caller",
|
|
14
|
+
});
|
|
15
|
+
//# sourceMappingURL=caller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"caller.js","sourceRoot":"","sources":["../src/caller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAqBvD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,gBAAgB,CAAqB,SAAS,EAAE;IACvE,WAAW,EAAE,8CAA8C;CAC5D,CAAC,CAAC"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { BinaryReadOptions, BinaryWriteOptions, JsonReadOptions, JsonWriteOptions } from "@bufbuild/protobuf";
|
|
2
|
+
import { type Interceptor, type Transport } from "@connectrpc/connect";
|
|
3
|
+
import { type ClientRuntime } from "./runtime.js";
|
|
4
|
+
import { type PayloadEncoding } from "./wire.js";
|
|
5
|
+
/** Options for createServiceWorkerTransport. All are optional. */
|
|
6
|
+
export interface ServiceWorkerTransportOptions {
|
|
7
|
+
/**
|
|
8
|
+
* The extension to call. Leave it out inside the extension itself (popup,
|
|
9
|
+
* side panel, options page, content scripts). A web page must set it, and
|
|
10
|
+
* must be listed in the extension's `externally_connectable`.
|
|
11
|
+
*/
|
|
12
|
+
extensionId?: string;
|
|
13
|
+
/** Port name; must match serveServiceWorker's. Default "connectrpc-service-worker". */
|
|
14
|
+
portName?: string;
|
|
15
|
+
/** Protobuf binary (true, the default) or JSON (false) for messages. */
|
|
16
|
+
useBinaryFormat?: boolean;
|
|
17
|
+
/** Interceptors that run on every call, as with any Connect transport. */
|
|
18
|
+
interceptors?: Interceptor[];
|
|
19
|
+
/** Options for the JSON format. */
|
|
20
|
+
jsonOptions?: Partial<JsonReadOptions & JsonWriteOptions>;
|
|
21
|
+
/** Options for the binary format. */
|
|
22
|
+
binaryOptions?: Partial<BinaryReadOptions & BinaryWriteOptions>;
|
|
23
|
+
/** Timeout for calls that don't set one. Default: none. */
|
|
24
|
+
defaultTimeoutMs?: number;
|
|
25
|
+
/** Largest response message accepted. Default ~4 GiB. */
|
|
26
|
+
readMaxBytes?: number;
|
|
27
|
+
/** Largest request message sent. Default ~4 GiB. */
|
|
28
|
+
writeMaxBytes?: number;
|
|
29
|
+
/**
|
|
30
|
+
* How long to wait for the service worker to accept a call before failing
|
|
31
|
+
* with `unavailable`. This covers starting a stopped service worker.
|
|
32
|
+
* Default 10000. 0 waits forever.
|
|
33
|
+
*/
|
|
34
|
+
acceptTimeoutMs?: number;
|
|
35
|
+
/**
|
|
36
|
+
* While a call is open, a ping is sent this often. Messages on a port keep
|
|
37
|
+
* the service worker running (Chrome 114+); without them Chrome stops it
|
|
38
|
+
* after about 30 s idle, ending long calls and streams. Default 20000. 0 sends none.
|
|
39
|
+
*/
|
|
40
|
+
keepAliveIntervalMs?: number;
|
|
41
|
+
/** Largest piece of a body per message, before base64. Default 1 MiB. */
|
|
42
|
+
maxChunkBytes?: number;
|
|
43
|
+
/** How bytes are put into messages. Default "auto"; see PayloadEncoding. */
|
|
44
|
+
payloadEncoding?: PayloadEncoding;
|
|
45
|
+
/** chrome.runtime to use. Default: the global one. For tests and wrappers. */
|
|
46
|
+
runtime?: ClientRuntime;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Creates a Connect transport that calls services served by
|
|
50
|
+
* serveServiceWorker in an extension's service worker, over a
|
|
51
|
+
* `chrome.runtime` port. Use it like any other transport:
|
|
52
|
+
*
|
|
53
|
+
* const transport = createServiceWorkerTransport();
|
|
54
|
+
* const client = createClient(MyService, transport);
|
|
55
|
+
*
|
|
56
|
+
* Unary and server-streaming methods are supported. Client-streaming and
|
|
57
|
+
* bidirectional methods fail with `unimplemented`.
|
|
58
|
+
*
|
|
59
|
+
* Creating the transport never throws for a missing extension; calls fail
|
|
60
|
+
* with `unavailable` instead, so a web page can create it unconditionally.
|
|
61
|
+
*/
|
|
62
|
+
export declare function createServiceWorkerTransport(options?: ServiceWorkerTransportOptions): Transport;
|
|
63
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,kBAAkB,EAGlB,eAAe,EACf,gBAAgB,EAEjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAA0C,KAAK,WAAW,EAAuB,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAQpI,OAAO,EAAsC,KAAK,aAAa,EAAa,MAAM,cAAc,CAAC;AACjG,OAAO,EAaL,KAAK,eAAe,EACrB,MAAM,WAAW,CAAC;AAEnB,kEAAkE;AAClE,MAAM,WAAW,6BAA6B;IAC5C;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uFAAuF;IACvF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,0EAA0E;IAC1E,YAAY,CAAC,EAAE,WAAW,EAAE,CAAC;IAC7B,mCAAmC;IACnC,WAAW,CAAC,EAAE,OAAO,CAAC,eAAe,GAAG,gBAAgB,CAAC,CAAC;IAC1D,qCAAqC;IACrC,aAAa,CAAC,EAAE,OAAO,CAAC,iBAAiB,GAAG,kBAAkB,CAAC,CAAC;IAChE,2DAA2D;IAC3D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yDAAyD;IACzD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oDAAoD;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yEAAyE;IACzE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,4EAA4E;IAC5E,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,8EAA8E;IAC9E,OAAO,CAAC,EAAE,aAAa,CAAC;CACzB;AAgBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,4BAA4B,CAAC,OAAO,GAAE,6BAAkC,GAAG,SAAS,CAwDnG"}
|