Skip to content

Commit bc2ffdb

Browse files
yangshunclaude
andauthored
feat(routes): check SSE and live stream client URLs with typedRoutes (#741)
## Summary With `routing.typedRoutes` on, the `url` argument of `connectEventStream()` (`void/sse/client`) and `connectLiveStream()` (`void/live/client`) is now checked against the app's routes, like `Link`, router methods and `c.rewrite()`. Both clients accept: - one of the app's route URLs, including template literals for dynamic routes and a query/hash suffix (`` `/api/users/${id}` ``), - an absolute `http://` or `https://` URL, for a stream on another origin, - a `URL` object. They reject unknown paths, `ws://`/`wss://`, `mailto:`, `tel:`, same-page `?`/`#` URLs and unchecked `string` values. A string TypeScript can't check is cast with `as RouteUrl`, which turns the check off for that URL. ```ts connectEventStream('/api/logs'); // ok connectEventStream(`/api/users/${id}`); // ok connectEventStream('https://example.com/events'); // ok connectEventStream(path as RouteUrl); // ok, unchecked connectEventStream('/api/lgos'); // type error connectLiveStream('wss://example.com/live'); // type error ``` With the flag off, the parameter stays `string | URL`. Neither client has a base-URL option: a path always resolves against the page's origin, so route checking applies to every relative string. The accepted string type (`RequestUrl` in `route-url.ts`) stays internal rather than being exported from `void/routes`; `Href` was not reused because it also allows `mailto:`, `tel:` and same-page URLs. ## Docs - `docs/guide/sse.md`, `docs/guide/live.md`: what `typedRoutes` checks for the client URL and how to cast. - `docs/guide/type-safety.md`: "Checked URL strings" list, a paragraph on stream URLs, and the "What Gets Checked" table. - `docs/reference/config.md`: `routing.typedRoutes`. ## Tests - `packages/void/test/integration/route-url-builder.test.ts`: the typed fixture (generated and package declarations) accepts a known route, a dynamic template literal, a `RouteUrl`, `http(s)` URLs, a `URL` and a `RouteUrl` cast; it rejects an unknown path, `ws://`/`wss://`, `#details` and an unchecked `string`. Reverting the SSE client's parameter to `string | URL` in `dist` makes the four SSE `@ts-expect-error` lines fail. - `packages/void/test/unit/typed-navigation.typecheck.ts`: with the flag off, both parameters are exactly `string | URL`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f66a211 commit bc2ffdb

9 files changed

Lines changed: 88 additions & 18 deletions

File tree

‎docs/guide/live.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ stream.close();
7777

7878
Subscription IDs are scoped to a connection. Reusing an ID replaces its subscription. After reconnecting, the helper restores active subscriptions and sends their latest `eventId` as `lastEventId`.
7979

80+
With [`routing.typedRoutes`](../reference/config.md#routing-typedroutes), the URL must match one of your routes or be an `http://` or `https://` URL. Cast a `string` that TypeScript can't check with `as RouteUrl` from `void/routes`. The cast turns off the check for that URL.
81+
8082
## Publish
8183

8284
Publish from any server-side code that has a Void runtime env:

‎docs/guide/sse.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ stream.close();
141141

142142
The client wraps native `EventSource`. It supports cookie credentials and typed event handlers, but it does not support request bodies or arbitrary headers. Use cookie auth, signed URLs, or a fetch-based streaming route when you need custom headers.
143143

144+
With [`routing.typedRoutes`](../reference/config.md#routing-typedroutes), the URL must match one of your routes, such as `` `/api/jobs/${id}` ``, or be an `http://` or `https://` URL. Cast a `string` that TypeScript can't check with `as RouteUrl` from `void/routes`. The cast turns off the check for that URL.
145+
144146
JSON parsing is the default. Set `parse: 'text'` or pass a custom parser for non-JSON payloads:
145147

146148
```ts

‎docs/guide/type-safety.md‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ await revalidate({ paths: ['/', '/blog/hello-world'] satisfies RouteUrl[] });
257257

258258
### Checked URL strings
259259

260-
[`routing.typedRoutes`](../reference/config.md#routing-typedroutes) checks plain URL strings in `Link`'s `href`, `router.visit()`, `router.prefetch()`, `router.flush()`, `c.rewrite()`, and `useIslandForm()`'s `post()`, `put()`, `patch()`, `delete()`, and `submit()`. Apps created with `void init` have it on. To turn it on in an existing app:
260+
[`routing.typedRoutes`](../reference/config.md#routing-typedroutes) checks plain URL strings in `Link`'s `href`, `router.visit()`, `router.prefetch()`, `router.flush()`, `c.rewrite()`, `connectEventStream()`, `connectLiveStream()`, and `useIslandForm()`'s `post()`, `put()`, `patch()`, `delete()`, and `submit()`. Apps created with `void init` have it on. To turn it on in an existing app:
261261

262262
```ts
263263
// void.config.ts
@@ -324,6 +324,8 @@ import { routeUrl } from 'void/routes';
324324

325325
Links can also point to the current page (`?page=2`, `#comments`) and to `http://`, `https://`, `mailto:`, and `tel:` URLs. Relative paths such as `../settings` are rejected; use the absolute path. A fixed part with spaces or non-ASCII characters can be written as is (`/café menu`) or percent-encoded in uppercase, as `routeUrl()` returns it (`/caf%C3%A9%20menu`). A dynamic segment matches any text, including none, so `/users/:id` also accepts `/users/` and `/users/42/edit`. With a root dynamic page such as `pages/[slug].tsx`, `.vue`, or `.svelte`, a protocol-relative URL like `//example.com` passes too.
326326

327+
The [SSE](./sse.md#client) and [live stream](./live.md#subscribe-from-the-browser) clients, `connectEventStream()` and `connectLiveStream()`, take one of your routes or an `http://` or `https://` URL for a stream on another origin. They reject same-page, `mailto:`, `tel:`, and `ws://` URLs. Cast a stream URL that TypeScript can't check with `as RouteUrl`; the cast turns off the check for that URL.
328+
327329
`c.redirect()` is not part of that check. It still accepts any string. Build an internal path with `routeUrl()`, or annotate a full path with `satisfies RouteUrl`. With `routing.typedRoutes` on, a path that matches no route is a type error. An external URL stays a plain string:
328330

329331
```ts
@@ -395,20 +397,20 @@ Route types update with the dev server. For CI or standalone typechecking, run `
395397

396398
## What Gets Checked
397399

398-
| Layer | What's type-checked |
399-
| ------------------- | --------------------------------------------------------------------------------------------------------------------- |
400-
| Database | Table columns, value types, insert/update shapes from Drizzle schema |
401-
| Handlers | `c.env` bindings, validator input, return type |
402-
| Fetch client | Route paths, HTTP methods, `body`/`query`/`params`, response type |
403-
| Navigation | Route patterns and required parameter names and values in `routeUrl()` and destination objects |
404-
| Links | With `routing.typedRoutes`, URL strings in `Link`, router methods, `c.rewrite()`, and `useIslandForm()` |
405-
| `c.redirect` | An internal path built with `routeUrl()`, or a full path annotated with `satisfies RouteUrl` |
406-
| `useParams` | Page patterns and the names of the params they return |
407-
| `c.req.param` | Page param names, when the result is annotated with `PageParams` |
408-
| `getPrerenderPaths` | Page param names, when the return type is annotated with `PageParams` |
409-
| `revalidate` | `paths`, and `routing.prerender`, when the array is annotated with `satisfies RouteUrl[]` |
410-
| `useForm` | Action URLs, `data` fields, `errors` keys, `reset()` args (including `{ initial: true }`), `params`, `resetOnSuccess` |
411-
| `action()` | Action URLs, `data` payload, `params` |
400+
| Layer | What's type-checked |
401+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
402+
| Database | Table columns, value types, insert/update shapes from Drizzle schema |
403+
| Handlers | `c.env` bindings, validator input, return type |
404+
| Fetch client | Route paths, HTTP methods, `body`/`query`/`params`, response type |
405+
| Navigation | Route patterns and required parameter names and values in `routeUrl()` and destination objects |
406+
| Links | With `routing.typedRoutes`, URL strings in `Link`, router methods, `c.rewrite()`, `useIslandForm()`, and SSE and live stream clients |
407+
| `c.redirect` | An internal path built with `routeUrl()`, or a full path annotated with `satisfies RouteUrl` |
408+
| `useParams` | Page patterns and the names of the params they return |
409+
| `c.req.param` | Page param names, when the result is annotated with `PageParams` |
410+
| `getPrerenderPaths` | Page param names, when the return type is annotated with `PageParams` |
411+
| `revalidate` | `paths`, and `routing.prerender`, when the array is annotated with `satisfies RouteUrl[]` |
412+
| `useForm` | Action URLs, `data` fields, `errors` keys, `reset()` args (including `{ initial: true }`), `params`, `resetOnSuccess` |
413+
| `action()` | Action URLs, `data` payload, `params` |
412414

413415
## Serialization
414416

‎docs/reference/config.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ routing: {
378378

379379
#### `routing.typedRoutes`
380380

381-
Type-check URL strings against your app's routes in `Link`'s `href`, `router.visit()`, `router.prefetch()`, `router.flush()`, `c.rewrite()`, and `useIslandForm()`. Omitted or `false` means off; `void init` turns it on for new apps. It changes types only, not navigation at runtime. Link and router strings may also be same-page queries or hashes, or `http://`, `https://`, `mailto:`, and `tel:` URLs. `useIslandForm()` takes a route URL. `c.redirect()`, `revalidate({ paths })`, and `routing.prerender` stay plain strings until you annotate them. See [Checked URL strings](../guide/type-safety#checked-url-strings).
381+
Type-check URL strings against your app's routes in `Link`'s `href`, `router.visit()`, `router.prefetch()`, `router.flush()`, `c.rewrite()`, `useIslandForm()`, `connectEventStream()`, and `connectLiveStream()`. Omitted or `false` means off; `void init` turns it on for new apps. It changes types only, not navigation at runtime. Link and router strings may also be same-page queries or hashes, or `http://`, `https://`, `mailto:`, and `tel:` URLs. `useIslandForm()` takes a route URL; `connectEventStream()` and `connectLiveStream()` also take `http://` and `https://` URLs. `c.redirect()`, `revalidate({ paths })`, and `routing.prerender` stay plain strings until you annotate them. See [Checked URL strings](../guide/type-safety#checked-url-strings).
382382

383383
```ts
384384
routing: {

‎packages/void/src/runtime/live-client.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { LiveClientEvent, LiveControlOperation, LiveControlResponse } from './live.ts';
2+
import type { RequestUrl } from './route-url.ts';
23

34
export type LiveSubscribeOptions<Data = unknown> = {
45
id: string;
@@ -47,8 +48,16 @@ type PendingOperation = {
4748
reject: (error: unknown) => void;
4849
};
4950

51+
/**
52+
* Open one `EventSource` to a `defineLiveStream()` route and send subscribe and
53+
* unsubscribe requests to the same URL.
54+
*
55+
* With `routing.typedRoutes`, a string `url` must match one of the app's routes
56+
* or be an absolute `http://`/`https://` URL. Cast a path built at runtime with
57+
* `as RouteUrl`.
58+
*/
5059
export function connectLiveStream(
51-
url: string | URL,
60+
url: RequestUrl | URL,
5261
options: ConnectLiveStreamOptions = {},
5362
): LiveClient {
5463
const EventSourceCtor =

‎packages/void/src/runtime/route-url.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,15 @@ export type Href = TypedRoutes extends true
105105
? RouteUrl | `${'?' | '#'}${string}` | `${'http://' | 'https://' | 'mailto:' | 'tel:'}${string}`
106106
: string;
107107

108+
/**
109+
* A URL an HTTP request can target: one of the app's routes or an absolute
110+
* `http://`/`https://` URL. A plain string unless `routing.typedRoutes` is on.
111+
*/
112+
// Not re-exported from `void/routes`: apps cast runtime strings with `as RouteUrl`.
113+
export type RequestUrl = TypedRoutes extends true
114+
? RouteUrl | `${'http://' | 'https://'}${string}`
115+
: string;
116+
108117
export type RouteQueryValue = string | number | boolean | null | undefined;
109118
export type RouteQuery = Record<string, RouteQueryValue | ReadonlyArray<RouteQueryValue>>;
110119

‎packages/void/src/runtime/sse-client.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { RequestUrl } from './route-url.ts';
2+
13
export type SseClientEvent<T = unknown> = {
24
data: T;
35
event: string;
@@ -38,8 +40,15 @@ type EventSourceConstructor = new (
3840
options?: { withCredentials?: boolean },
3941
) => EventSourceLike;
4042

43+
/**
44+
* Open an `EventSource` to a route that returns `eventStream()`.
45+
*
46+
* With `routing.typedRoutes`, a string `url` must match one of the app's routes
47+
* or be an absolute `http://`/`https://` URL. Cast a path built at runtime with
48+
* `as RouteUrl`.
49+
*/
4150
export function connectEventStream<Events extends SseEventMap = SseEventMap>(
42-
url: string | URL,
51+
url: RequestUrl | URL,
4352
options: ConnectEventStreamOptions = {},
4453
): SseClient<Events> {
4554
const EventSourceCtor = (globalThis as { EventSource?: EventSourceConstructor }).EventSource;

‎packages/void/test/integration/route-url-builder.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ const typedCheck = `import { routeUrl, type Href, type RouteUrl } from 'void/rou
2727
import { defineConfig } from 'void/config';
2828
import type { VoidRouter } from 'void/pages-client';
2929
import { defineMiddleware, type CloudContext } from 'void/handler';
30+
import { connectLiveStream } from 'void/live/client';
31+
import { connectEventStream } from 'void/sse/client';
3032
import type { IslandFormState } from 'void/pages-client';
3133
declare const id: number;
3234
declare const dynamic: string;
@@ -93,6 +95,30 @@ void context.rewrite('https://example.com');
9395
// @ts-expect-error rewrites do not take same-page hashes
9496
void context.rewrite('#details');
9597
context.redirect('https://example.com/elsewhere');
98+
connectEventStream('/api/legacy');
99+
connectEventStream(\`/api/users/\${id}\`);
100+
connectEventStream(user);
101+
connectEventStream('https://example.com/events');
102+
connectEventStream(new URL('https://example.com/events'));
103+
connectEventStream(dynamic as RouteUrl);
104+
// @ts-expect-error event streams reject unknown routes
105+
connectEventStream('/unknown');
106+
// @ts-expect-error event streams do not take WebSocket URLs
107+
connectEventStream('ws://example.com/events');
108+
// @ts-expect-error event streams do not take same-page hashes
109+
connectEventStream('#details');
110+
// @ts-expect-error event streams reject unchecked strings
111+
connectEventStream(dynamic);
112+
connectLiveStream('/api/legacy');
113+
connectLiveStream(\`/api/users/\${id}?room=1\`);
114+
connectLiveStream('http://localhost:5173/live');
115+
connectLiveStream(new URL('https://example.com/live'));
116+
// @ts-expect-error live streams reject unknown routes
117+
connectLiveStream('/unknown');
118+
// @ts-expect-error live streams do not take WebSocket URLs
119+
connectLiveStream('wss://example.com/live');
120+
// @ts-expect-error live streams reject unchecked strings
121+
connectLiveStream(dynamic);
96122
declare const island: IslandFormState<{ title: string }, 'setters'>;
97123
void island.post('/about');
98124
void island.post('/users/42?update');

‎packages/void/test/unit/typed-navigation.typecheck.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
type CloudContext,
1515
type CloudEnv,
1616
} from '../../src/runtime/handler.ts';
17+
import { connectLiveStream } from '../../src/runtime/live-client.ts';
18+
import { connectEventStream } from '../../src/runtime/sse-client.ts';
1719

1820
declare module 'void/routes' {
1921
interface RoutePathMap {
@@ -80,3 +82,12 @@ export function checkUntypedRouteStrings(): void {
8082
expectTypeOf<Href>().toEqualTypeOf<string>();
8183
expectTypeOf(routeUrl('/typed-navigation')).toEqualTypeOf<string>();
8284
}
85+
86+
export function checkUntypedStreamUrls(url: string): void {
87+
expectTypeOf<Parameters<typeof connectEventStream>[0]>().toEqualTypeOf<string | URL>();
88+
expectTypeOf<Parameters<typeof connectLiveStream>[0]>().toEqualTypeOf<string | URL>();
89+
connectEventStream(url);
90+
connectLiveStream(url);
91+
connectEventStream('/unknown');
92+
connectLiveStream('ws://example.com/live');
93+
}

0 commit comments

Comments
 (0)