Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/window-link #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
node_modules
.DS_Store
dist
adapter/**/*
link/**/*
types/**/*
/adapter
/link
/types
/relay
/shared
36 changes: 33 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
## **[Chrome extension](https://developer.chrome.com/docs/extensions/mv3/) support for [tRPC](https://trpc.io/)** 🧩

- Easy communication for web extensions.
- Typesafe messaging between content & background scripts.
- Typesafe messaging between window, content & background scripts.
- Ready for Manifest V3.

## Usage
Expand Down Expand Up @@ -59,11 +59,33 @@ import { chromeLink } from 'trpc-chrome/link';
import type { AppRouter } from './background';

const port = chrome.runtime.connect();
export const chromeClient = createTRPCClient<AppRouter>({
export const chromeClient = createTRPCProxyClient<AppRouter>({
links: [/* 👉 */ chromeLink({ port })],
});
```

**4. `(extra)` If you have an injected window script, hook it up too!.**

```typescript
// inpage.ts
import { createTRPCClient } from '@trpc/client';
import { windowLink } from 'trpc-chrome/link';

import type { AppRouter } from './background';

export const windowClient = createTRPCProxyClient<AppRouter>({
links: [/* 👉 */ windowLink({ window })],
});
```

```typescript
// content.ts
import { relay } from 'trpc-chrome/relay';

const port = chrome.runtime.connect();
relay(port, window);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janek26 how do you use this relay?
Could you add like 2-3 line example?

```

## Requirements

Peer dependencies:
Expand All @@ -81,12 +103,20 @@ _For advanced use-cases, please find examples in our [complete test suite](test)

#### ChromeLinkOptions

Please see [full typings here](src/link/index.ts).
Please see [full typings here](src/link/chrome.ts).

| Property | Type | Description | Required |
| -------- | --------------------- | ---------------------------------------------------------------- | -------- |
| `port` | `chrome.runtime.Port` | An open web extension port between content & background scripts. | `true` |

### WindowLinkOptions

Please see [full typings here](src/link/window.ts).

| Property | Type | Description | Required |
| -------- | -------- | ----------------------------------------------- | -------- |
| `window` | `Window` | A window object which is listened to by a relay | `true` |

#### CreateChromeHandlerOptions

Please see [full typings here](src/adapter/index.ts).
Expand Down
54 changes: 27 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
"author": "James Berry <jb@jamesbe.com>",
"private": false,
"license": "MIT",
"files": [
"types",
"adapter",
"link",
"relay",
"shared"
],
"keywords": [
"trpc",
"chrome",
Expand All @@ -21,7 +28,7 @@
],
"scripts": {
"test": "tsc --noEmit && jest --verbose",
"build": "rimraf dist && rimraf adapter && rimraf link && rimraf types && tsc -p tsconfig.build.json && mv dist/* . && rimraf dist"
"build": "rimraf dist && rimraf adapter && rimraf link && rimraf types && rimraf relay && rimraf shared && tsc -p tsconfig.build.json && mv dist/* . && rimraf dist"
},
"peerDependencies": {
"@trpc/client": "^10.0.0",
Expand Down
7 changes: 3 additions & 4 deletions src/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { NodeHTTPCreateContextOption } from '@trpc/server/dist/adapters/nod
import type { BaseHandlerOptions } from '@trpc/server/dist/internals/types';
import { Unsubscribable, isObservable } from '@trpc/server/observable';

import { isTRPCRequest, isTRPCRequestWithId } from '../shared/trpcMessage';
import type { TRPCChromeRequest, TRPCChromeResponse } from '../types';
import { getErrorFromUnknown } from './errors';

Expand Down Expand Up @@ -40,11 +41,9 @@ export const createChromeHandler = <TRouter extends AnyRouter>(
port.onDisconnect.addListener(onDisconnect);
listeners.push(() => port.onDisconnect.removeListener(onDisconnect));

const onMessage = async (message: TRPCChromeRequest) => {
if (!('trpc' in message)) return;
const onMessage = async (message: unknown) => {
if (!isTRPCRequestWithId(message)) return;
const { trpc } = message;
if (!('id' in trpc) || trpc.id === null || trpc.id === undefined) return;
if (!trpc) return;

const { id, jsonrpc, method } = trpc;

Expand Down
30 changes: 30 additions & 0 deletions src/link/chrome.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { TRPCLink } from '@trpc/client';
import type { AnyRouter } from '@trpc/server';

import { createBaseLink } from './internal/base';

export type ChromeLinkOptions = {
port: chrome.runtime.Port;
};

export const chromeLink = <TRouter extends AnyRouter>(
opts: ChromeLinkOptions,
): TRPCLink<TRouter> => {
return createBaseLink({
postMessage(message) {
opts.port.postMessage(message);
},
addMessageListener(listener) {
opts.port.onMessage.addListener(listener);
},
removeMessageListener(listener) {
opts.port.onMessage.removeListener(listener);
},
addCloseListener(listener) {
opts.port.onDisconnect.addListener(listener);
},
removeCloseListener(listener) {
opts.port.onDisconnect.removeListener(listener);
},
});
};
94 changes: 2 additions & 92 deletions src/link/index.ts
Original file line number Diff line number Diff line change
@@ -1,92 +1,2 @@
import { TRPCClientError, TRPCLink } from '@trpc/client';
import type { AnyRouter } from '@trpc/server';
import { observable } from '@trpc/server/observable';

import type { TRPCChromeRequest, TRPCChromeResponse } from '../types';

export type ChromeLinkOptions = {
port: chrome.runtime.Port;
};

export const chromeLink = <TRouter extends AnyRouter>(
opts: ChromeLinkOptions,
): TRPCLink<TRouter> => {
return (runtime) => {
const { port } = opts;
return ({ op }) => {
return observable((observer) => {
const listeners: (() => void)[] = [];

const { id, type, path } = op;

try {
const input = runtime.transformer.serialize(op.input);

const onDisconnect = () => {
observer.error(new TRPCClientError('Port disconnected prematurely'));
};

port.onDisconnect.addListener(onDisconnect);
listeners.push(() => port.onDisconnect.removeListener(onDisconnect));

const onMessage = (message: TRPCChromeResponse) => {
if (!('trpc' in message)) return;
const { trpc } = message;
if (!trpc) return;
if (!('id' in trpc) || trpc.id === null || trpc.id === undefined) return;
if (id !== trpc.id) return;

if ('error' in trpc) {
const error = runtime.transformer.deserialize(trpc.error);
observer.error(TRPCClientError.from({ ...trpc, error }));
return;
}

observer.next({
result: {
...trpc.result,
...((!trpc.result.type || trpc.result.type === 'data') && {
type: 'data',
data: runtime.transformer.deserialize(trpc.result.data),
}),
} as any,
});

if (type !== 'subscription' || trpc.result.type === 'stopped') {
observer.complete();
}
};

port.onMessage.addListener(onMessage);
listeners.push(() => port.onMessage.removeListener(onMessage));

port.postMessage({
trpc: {
id,
jsonrpc: undefined,
method: type,
params: { path, input },
},
} as TRPCChromeRequest);
} catch (cause) {
observer.error(
new TRPCClientError(cause instanceof Error ? cause.message : 'Unknown error'),
);
}

return () => {
listeners.forEach((unsub) => unsub());
if (type === 'subscription') {
port.postMessage({
trpc: {
id,
jsonrpc: undefined,
method: 'subscription.stop',
},
} as TRPCChromeRequest);
}
};
});
};
};
};
export * from './chrome';
export * from './window';
Loading