@webext-core/messaging 1.0.2 → 1.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/README.md +95 -3
- package/lib/index.cjs +14 -2
- package/lib/index.d.ts +4 -4
- package/lib/index.js +14 -2
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -8,9 +8,10 @@ In addition to adding types, it also includes error handling. Any errors will be
|
|
|
8
8
|
|
|
9
9
|
In your project, create a file that calls `defineExtensionMessaging`, and exports the two functions it returns.
|
|
10
10
|
|
|
11
|
+
###### messaging.ts
|
|
12
|
+
|
|
11
13
|
<!-- prettier-ignore -->
|
|
12
14
|
```ts
|
|
13
|
-
// messaging.ts
|
|
14
15
|
import { defineExtensionMessaging, ProtocolWithReturn } from '@webext-core/messaging';
|
|
15
16
|
|
|
16
17
|
// This defines the data and return types used for each message
|
|
@@ -26,8 +27,9 @@ export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>(
|
|
|
26
27
|
|
|
27
28
|
Then import those functions throughout the rest of the extension.
|
|
28
29
|
|
|
30
|
+
###### src/background.ts
|
|
31
|
+
|
|
29
32
|
```ts
|
|
30
|
-
// src/background.ts
|
|
31
33
|
import { onMessage } from './messaging';
|
|
32
34
|
|
|
33
35
|
onMessage('message4', message => {
|
|
@@ -36,9 +38,99 @@ onMessage('message4', message => {
|
|
|
36
38
|
});
|
|
37
39
|
```
|
|
38
40
|
|
|
41
|
+
###### src/popup.ts
|
|
42
|
+
|
|
39
43
|
```ts
|
|
40
|
-
// src/popup.ts
|
|
41
44
|
import { sendMessage } from './messaging';
|
|
42
45
|
|
|
43
46
|
sendMessage('message4', 'data').then(console.log);
|
|
44
47
|
```
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
### `defineExtensionMessaging`
|
|
52
|
+
|
|
53
|
+
Returns [`sendMessage`](#sendmessage) and [`onMessage`](#onmessage) with types based on your [`TProtocolMap`](#protocolmap).
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
function defineExtensionMessaging<TProtocolMap>(options: ExtensionMessagingConfig): {
|
|
57
|
+
sendMessage: Function;
|
|
58
|
+
onMessage: Function;
|
|
59
|
+
};
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
#### `ExtensionMessagingConfig`
|
|
63
|
+
|
|
64
|
+
Configuration for the [`defineExtensionMessaging`](#defineextensionmessaging).
|
|
65
|
+
|
|
66
|
+
- `logger` (_default: `console`_): custom logger for printing sent and recieved messages to the console. Pass `null` to disable logging.
|
|
67
|
+
|
|
68
|
+
### `sendMessage`
|
|
69
|
+
|
|
70
|
+
Send a message to the background, or include a `tabId` to send a message from the background to a specific tab.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
function sendMessage(
|
|
74
|
+
type: keyof TProtocolMap,
|
|
75
|
+
payload: TPayload,
|
|
76
|
+
tabId?: number,
|
|
77
|
+
): Promise<TReturnType>;
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### `onMessage`
|
|
81
|
+
|
|
82
|
+
Add a `runtime.onMessage` listener for a specific message type:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
function onMessage(
|
|
86
|
+
type: keyof TProtocolMap,
|
|
87
|
+
onRecieved: (message: Message<TPayload>) => TReturnType,
|
|
88
|
+
): RemoveOnMessage;
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
The `onRecieved` callback's `message` includes:
|
|
92
|
+
|
|
93
|
+
- `id: number`: a unique ID for the message that was sent. Useful for debugging.
|
|
94
|
+
- `data: TPayload`: The payload sent when calling `sendMessage`, or `undefined` if no payload was sent.
|
|
95
|
+
- `sender: MessageSender`: The details about who sent the message. See [Chrome's docs on `MessageSender`](https://developer.chrome.com/docs/extensions/reference/runtime/#type-MessageSender) for more details.
|
|
96
|
+
- `timestamp: number`: MS since epoch that the message was sent at.
|
|
97
|
+
|
|
98
|
+
`onMessage` returns a function that removes the listener you just added. It accepts no arguments and returns void (`() => void`)
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const removeListener = onMessage("some-type", ...);
|
|
102
|
+
removeListener();
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### `ProtocolMap`
|
|
106
|
+
|
|
107
|
+
To implement custom types, you need to include a `ProtocolMap` when calling [`defineExtensionMessaging`](#defineextensionmessaging).
|
|
108
|
+
|
|
109
|
+
A protocol map is a record of message types to the payload and/or return type of the message.
|
|
110
|
+
|
|
111
|
+
If I wanted a message called `toRgb` to take in a hex color, and returns the R, G, and B values, it would look like this:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { ProtocolWithReturn, defineExtensionMessaging } from '@webext-core/messaging';
|
|
115
|
+
|
|
116
|
+
interface ProtocolMap {
|
|
117
|
+
toRgb: ProtocolWithReturn<string, { r: number; g: number; b: number }>;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const { sendMessage, onMessage } = defineExtensionMessaging<ProtocolMap>();
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Here's a cheatsheet for defining a protocol map:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
interface ProtocolMap {
|
|
127
|
+
'no-payload-no-return-type': undefined;
|
|
128
|
+
'with-payload-no-return-type': YourPayloadType;
|
|
129
|
+
'no-payload-with-return-type': ProtocolWithReturn<undefined, YourReturnType>;
|
|
130
|
+
'with-payload-with-return-type': ProtocolWithReturn<YourPayloadType, YourReturnType>;
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
> If you don't have a return type, you can just set the value to the payload type.
|
|
135
|
+
|
|
136
|
+
> Use `undefined` when excluding a payload or return type
|
package/lib/index.cjs
CHANGED
|
@@ -75,8 +75,8 @@ function defineExtensionMessaging(config) {
|
|
|
75
75
|
throw err;
|
|
76
76
|
}
|
|
77
77
|
(_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
|
|
78
|
-
const
|
|
79
|
-
for (const [key2, listener] of
|
|
78
|
+
const entries = Object.entries(keyListeners);
|
|
79
|
+
for (const [key2, listener] of entries) {
|
|
80
80
|
if (message.key !== key2)
|
|
81
81
|
continue;
|
|
82
82
|
(_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
|
|
@@ -100,6 +100,11 @@ function defineExtensionMessaging(config) {
|
|
|
100
100
|
return { err: errMessage };
|
|
101
101
|
});
|
|
102
102
|
}
|
|
103
|
+
return Promise.resolve({
|
|
104
|
+
err: `Listener not found for message.type="${message.key}".
|
|
105
|
+
|
|
106
|
+
Did you forget to call \`onMessage("getLength", ...)\`?`
|
|
107
|
+
});
|
|
103
108
|
};
|
|
104
109
|
import_webextension_polyfill.default.runtime.onMessage.addListener(rootListener);
|
|
105
110
|
}
|
|
@@ -112,6 +117,13 @@ function defineExtensionMessaging(config) {
|
|
|
112
117
|
}
|
|
113
118
|
keyListeners[key] = onReceived;
|
|
114
119
|
(_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${key}`);
|
|
120
|
+
return function removeListener() {
|
|
121
|
+
delete keyListeners[key];
|
|
122
|
+
if (Object.entries(keyListeners).length === 0) {
|
|
123
|
+
import_webextension_polyfill.default.runtime.onMessage.removeListener(rootListener);
|
|
124
|
+
rootListener = void 0;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
115
127
|
}
|
|
116
128
|
function sendMessage(key, data, tabId) {
|
|
117
129
|
return __async(this, null, function* () {
|
package/lib/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Runtime } from 'webextension-polyfill';
|
|
2
2
|
|
|
3
|
-
interface
|
|
3
|
+
interface ExtensionMessagingConfig {
|
|
4
4
|
logger?: {
|
|
5
5
|
debug(...args: any[]): void;
|
|
6
6
|
log(...args: any[]): void;
|
|
@@ -22,9 +22,9 @@ interface Message<TProtocolMap, TKey extends keyof TProtocolMap> {
|
|
|
22
22
|
}
|
|
23
23
|
declare type MaybePromise<T> = Promise<T> | T;
|
|
24
24
|
declare type OnMessageReceived<TProtocolMap, TKey extends keyof TProtocolMap> = (message: Message<TProtocolMap, TKey>) => MaybePromise<GetResponse<TProtocolMap[TKey]>>;
|
|
25
|
-
declare function defineExtensionMessaging<TProtocolMap>(config?:
|
|
26
|
-
onMessage: <TKey extends keyof TProtocolMap>(key: TKey, onReceived: OnMessageReceived<TProtocolMap, TKey>) => void;
|
|
25
|
+
declare function defineExtensionMessaging<TProtocolMap>(config?: ExtensionMessagingConfig): {
|
|
26
|
+
onMessage: <TKey extends keyof TProtocolMap>(key: TKey, onReceived: OnMessageReceived<TProtocolMap, TKey>) => () => void;
|
|
27
27
|
sendMessage: <TKey_1 extends keyof TProtocolMap>(key: TKey_1, data: GetData<TProtocolMap[TKey_1]>, tabId?: number) => Promise<GetResponse<TProtocolMap[TKey_1]>>;
|
|
28
28
|
};
|
|
29
29
|
|
|
30
|
-
export { ProtocolWithReturn, defineExtensionMessaging };
|
|
30
|
+
export { ExtensionMessagingConfig, ProtocolWithReturn, defineExtensionMessaging };
|
package/lib/index.js
CHANGED
|
@@ -46,8 +46,8 @@ function defineExtensionMessaging(config) {
|
|
|
46
46
|
throw err;
|
|
47
47
|
}
|
|
48
48
|
(_b2 = config == null ? void 0 : config.logger) == null ? void 0 : _b2.debug("[messaging] Received message", message, sender);
|
|
49
|
-
const
|
|
50
|
-
for (const [key2, listener] of
|
|
49
|
+
const entries = Object.entries(keyListeners);
|
|
50
|
+
for (const [key2, listener] of entries) {
|
|
51
51
|
if (message.key !== key2)
|
|
52
52
|
continue;
|
|
53
53
|
(_c2 = config == null ? void 0 : config.logger) == null ? void 0 : _c2.debug(`[messaging] onMessage {id=${message.id}} \u140A\u2500`, message);
|
|
@@ -71,6 +71,11 @@ function defineExtensionMessaging(config) {
|
|
|
71
71
|
return { err: errMessage };
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
|
+
return Promise.resolve({
|
|
75
|
+
err: `Listener not found for message.type="${message.key}".
|
|
76
|
+
|
|
77
|
+
Did you forget to call \`onMessage("getLength", ...)\`?`
|
|
78
|
+
});
|
|
74
79
|
};
|
|
75
80
|
Browser.runtime.onMessage.addListener(rootListener);
|
|
76
81
|
}
|
|
@@ -83,6 +88,13 @@ function defineExtensionMessaging(config) {
|
|
|
83
88
|
}
|
|
84
89
|
keyListeners[key] = onReceived;
|
|
85
90
|
(_c = config == null ? void 0 : config.logger) == null ? void 0 : _c.log(`[messaging] Added listener for ${key}`);
|
|
91
|
+
return function removeListener() {
|
|
92
|
+
delete keyListeners[key];
|
|
93
|
+
if (Object.entries(keyListeners).length === 0) {
|
|
94
|
+
Browser.runtime.onMessage.removeListener(rootListener);
|
|
95
|
+
rootListener = void 0;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
86
98
|
}
|
|
87
99
|
function sendMessage(key, data, tabId) {
|
|
88
100
|
return __async(this, null, function* () {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webext-core/messaging",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Light weight, type-safe wrapper around the extension messaging APIs",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -48,11 +48,12 @@
|
|
|
48
48
|
"tsup": "^6.4.0",
|
|
49
49
|
"typescript": "^4.8.4",
|
|
50
50
|
"vitest": "^0.24.5",
|
|
51
|
-
"@webext-core/fake-browser": "1.0.
|
|
51
|
+
"@webext-core/fake-browser": "1.0.2",
|
|
52
52
|
"tsconfig": "0.0.0"
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|
|
55
55
|
"build": "tsup src/index.ts --clean --out-dir lib --format esm,cjs --dts",
|
|
56
|
+
"build:dependencies": "cd ../.. && turbo run build --filter=@webext-core/messaging^...",
|
|
56
57
|
"test": "vitest -r src",
|
|
57
58
|
"test:coverage": "vitest run -r src --coverage",
|
|
58
59
|
"compile": "tsc --noEmit"
|