@eleven-am/golem-client 0.0.0-stage → 0.1.1

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 CHANGED
@@ -1,3 +1,208 @@
1
- # Temporary Holding Version
1
+ # @eleven-am/golem-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Live GraphQL for golem servers, without a UI framework: `GolemClient`, the live protocol, the HTTP and WebSocket transport, the TanStack Query cache patcher and typed errors. Works with TanStack Query core, so any framework adapter can sit on top. For React use [`@eleven-am/golem-react`](https://www.npmjs.com/package/@eleven-am/golem-react), which wraps this package in hooks.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @eleven-am/golem-client @tanstack/query-core graphql graphql-ws
9
+ ```
10
+
11
+ Peer dependencies: `@tanstack/query-core` ^5, `graphql` ^16, `graphql-ws` ^6.
12
+
13
+ ## GolemClient
14
+
15
+ ```ts
16
+ import { QueryClient } from '@tanstack/query-core'
17
+ import { GolemClient } from '@eleven-am/golem-client'
18
+ import { golemClientManifest } from './zz_golem_client.gen'
19
+
20
+ export const queryClient = new QueryClient()
21
+
22
+ export const golem = new GolemClient({
23
+ queryClient,
24
+ url: 'https://api.example.com/graphql',
25
+ manifest: golemClientManifest,
26
+ credentials: () => ({
27
+ headers: { authorization: `Bearer ${session.token()}` },
28
+ connectionParams: { token: session.token() },
29
+ }),
30
+ })
31
+ ```
32
+
33
+ | Option | Meaning |
34
+ |---|---|
35
+ | `queryClient` | Required. Your application's TanStack `QueryClient`. A second `GolemClient` on a `QueryClient` that already has one throws `GolemConfigurationError`. |
36
+ | `url` | The GraphQL endpoint. HTTP requests go to it; the WebSocket connects to the same URL. |
37
+ | `manifest` | The generated `zz_golem_client.gen.ts` of your golem server (go/v0.8.2 or later). |
38
+ | `credentials` | Optional function returning `{ headers, connectionParams }`. Called again for every request and every connection, including after the server closes a socket at its credential deadline, so return the current token each time. |
39
+ | `createSocket` | Optional `(url, protocols, credentials) => socket` factory, for a WebSocket implementation of your own (for example in Node). |
40
+ | `fetch` | Optional `fetch` implementation for HTTP requests. Defaults to `globalThis.fetch`. |
41
+
42
+ ## Without React
43
+
44
+ ```ts
45
+ import { QueryObserver } from '@tanstack/query-core'
46
+
47
+ const POSTS = `
48
+ query PublishedPosts {
49
+ posts(where: { published: { equals: true } }) { id title }
50
+ }
51
+ `
52
+
53
+ const stop = golem.live.start()
54
+ const observer = new QueryObserver(queryClient, golem.queryOptions(POSTS))
55
+ const unsubscribe = observer.subscribe((result) => render(result.data))
56
+ ```
57
+
58
+ - `golem.live.start()` starts live sync and returns a function that stops it. Start it before you observe a query, so no query is fetched before its subscriptions are open.
59
+ - `golem.queryOptions(document, variables?)` returns TanStack options for a live query. It throws `GolemNotLiveError` for a document that cannot be live.
60
+ - `golem.infiniteQueryOptions(document, variables?)` returns options for `InfiniteQueryObserver` over a list query with a `take`. Give `take` a variable with a default, or a literal; never write `cursor` or `skip`.
61
+ - `golem.staticQueryOptions(document, variables?)` returns options for a document that cannot be live (aggregates, group-by, counts, update-many roots). It is fetched once and never patched.
62
+ - `golem.mutate(document, variables?)` runs a mutation over HTTP and returns its data. A document holds exactly one operation; one with several is refused with `GolemMultipleOperationsError`.
63
+
64
+ ```ts
65
+ const data = await golem.mutate(
66
+ `mutation Retitle($id: UUID!, $title: String!) {
67
+ updatePost(where: { ID: $id }, data: { title: { set: $title } }) { id title }
68
+ }`,
69
+ { id, title: 'New title' },
70
+ )
71
+ ```
72
+
73
+ ## Transport status and dispose
74
+
75
+ `golem.transport.status` is the state of the WebSocket: `idle`, `connecting`, `open`, `reconnecting`, `unauthenticated`, `forbidden`, `invalid`, `protocol-mismatch`, `contract-mismatch` or `deadline-required`. `golem.transport.onStatus(listener)` calls you on every change and returns an unsubscribe function.
76
+
77
+ ```ts
78
+ const off = golem.transport.onStatus((status) => console.log(status))
79
+ ```
80
+
81
+ The status of one query (below) is separate from this connection state.
82
+
83
+ `golem.dispose()` stops live sync, closes the transport and releases the `QueryClient` for another `GolemClient`.
84
+
85
+ ## Live status
86
+
87
+ `golem.live.statusOf(query)` returns `{ state, error }` for a TanStack `Query`, or `undefined` before live sync tracks it. `golem.live.subscribeStatus(listener)` calls you on every change.
88
+
89
+ | State | Meaning |
90
+ |---|---|
91
+ | `CONNECTING` | Subscriptions are being opened; the first fetch waits for their acks. |
92
+ | `LIVE` | Every stream is acknowledged; the cache follows the server. |
93
+ | `RECOVERING` | A stream or the socket was lost; it is reopening and the query will refetch once after the acks. |
94
+ | `LIMIT` | The connection's subscription cap was reached. The data is still fetched, but not live until a slot frees. |
95
+ | `FORBIDDEN` | The server stopped a stream because the principal lost access. The query refetches once and does not resubscribe. |
96
+ | `NOT_FOUND` | A row held in a single result slot left the result; the query refetches. |
97
+ | `FAILED` | A stream failed for good (`error` holds the cause). |
98
+
99
+ TanStack's own `isFetching`, `isError` and `data` keep their usual meaning.
100
+
101
+ ## The manifest
102
+
103
+ GraphQL does not say which subscription root carries a model's events, what its primary key is, whether a root returns rows or a count, whether a single-row root can be `null`, which unique input a cursor uses, or which contract the server was built from. The manifest carries those facts. It has one owner, the server's generator: `golem generate` writes `zz_golem_client.gen.ts` beside your schema, and `golem check` fails when it falls behind. The client reads it and never guesses. Regenerate it after every schema change; never edit it. See [The client manifest](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#the-client-manifest).
104
+
105
+ ## How live queries work
106
+
107
+ #### Connections
108
+
109
+ A `GolemClient` opens one WebSocket (graphql-ws), and only when the first stream needs it. The socket is lazy and reconnects forever, with backoff, except when the server refuses the handshake for good (protocol or contract mismatch, a missing deadline). Queries, refetches and mutations are plain HTTP `fetch` requests.
110
+
111
+ #### Subscriptions
112
+
113
+ The client reads your query document and opens one subscription per (model, filter) pair in it.
114
+
115
+ - A literal or variable `where` gives an `exact`-scoped stream: the server sends only events for rows that match.
116
+ - No `where` gives a `policy-only` stream: the server sends every event the caller's policy allows for that model.
117
+ - A nested relation is a pair of its own. When the parent has a `where` and the manifest knows the relation's inverse, the child stream is scoped by that parent filter. Otherwise it is `policy-only` unless the relation has its own `where`.
118
+ - Two selections with the same model and filter share one stream. Different filters do not. (Two selections that select the same response key differently get separate streams.)
119
+ - Components that run the same query with the same variables share one TanStack query, and so one set of streams.
120
+
121
+ | Document | Streams |
122
+ |---|---|
123
+ | `posts(where: { published: { equals: true } }) { id title }` | 1 (`Post`, exact) |
124
+ | `posts { id comments { id } }` | 2 (`Post` and `Comment`, both policy-only) |
125
+ | Two lists, both `posts(where: { published: { equals: true } })` | 1 |
126
+ | `posts(where: { published: { equals: true } })` and `posts(where: { published: { equals: false } })` | 2 |
127
+
128
+ A model without events (no `golem.Subscriptions`) makes the document not live: `useGolemQuery` throws `GolemNotLiveError`.
129
+
130
+ #### Filtering is automatic
131
+
132
+ You never filter events in the client. The server judges each event against the caller's policy and the stream's filter, and sends one of four event types: `CREATED` and `UPDATED` for a row that matches, `EXITED` for a row that stops matching or that the caller may no longer read, and `DELETED` for a removed row. A row that starts to match arrives as `CREATED` or `UPDATED`. See [Rows that leave a list](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#rows-that-leave-a-list).
133
+
134
+ #### Patch or refetch
135
+
136
+ - `UPDATED` is patched into the cache in place only when the stream's selection is plain: a top-level list or single-row root, arguments limited to `where` (or the unique selector of a single-row root), no `orderBy`, `distinct`, `take`, `skip` or cursor, and scalar fields only. Every other `UPDATED` refetches the query.
137
+ - `CREATED` refetches.
138
+ - `DELETED` and `EXITED` remove the held row from the cache at once. The query then refetches, because a removal changes a list or empties a slot.
139
+ - A response that carries an older row version than the cache already holds is discarded, and the query refetches.
140
+ - A mutation result is never written into the cache. A committed mutation invalidates the cached queries over the models it touches (TanStack marks them stale and refetches the ones in use).
141
+ - Refetches that arrive close together are coalesced into one.
142
+
143
+ #### Row versions
144
+
145
+ The client adds `_version` and `__typename` to every selection of a model with events, and the primary key fields (`id` for most models) when you left them out. It compares `_version` to decide which copy of a row is newer. You can select them yourself, but not alias another field to those names. See [Row versions](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#row-versions).
146
+
147
+ #### Status is per query
148
+
149
+ `golem.live.statusOf` reports one query, keyed by its document and variables. It is not a global connection state. For that, read the transport:
150
+
151
+ - `golem.transport.status`: `idle`, `connecting`, `open`, `reconnecting`, `unauthenticated`, `forbidden`, `invalid`, `protocol-mismatch`, `contract-mismatch` or `deadline-required`.
152
+ - `golem.transport.onStatus(listener)`: calls you on every change and returns an unsubscribe function.
153
+
154
+ Wrap them in your framework's external-store primitive. In React that is `useSyncExternalStore`:
155
+
156
+ ```tsx
157
+ import { useSyncExternalStore } from 'react'
158
+
159
+ function useConnection() {
160
+ return useSyncExternalStore(
161
+ (notify) => golem.transport.onStatus(notify),
162
+ () => golem.transport.status,
163
+ )
164
+ }
165
+ ```
166
+
167
+ #### Why there is a manifest
168
+
169
+ GraphQL does not say which subscription root carries a model's events, what its primary key is, whether a root returns rows or a count, whether a single-row root can be `null`, which unique input a cursor uses, or which contract the server was built from. The manifest carries those facts. It has one owner, the server's generator (`golem generate` writes `zz_golem_client.gen.ts`), and `golem check` fails when it falls behind the schema. The client reads it and never guesses. See [The client manifest](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#the-client-manifest).
170
+
171
+ #### Server concepts
172
+
173
+ - [Subscriptions and events](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#subscriptions-and-events)
174
+ - [Row versions](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#row-versions)
175
+ - [Rows that leave a list](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#rows-that-leave-a-list)
176
+ - [The live handshake and the subscription ack](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#the-live-handshake-and-the-subscription-ack)
177
+ - [The socket deadline](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#the-socket-deadline)
178
+
179
+ For a walkthrough from a model to a live component, see [Using golem from React](https://github.com/eleven-am/golem/blob/main/docs/golem-go/REACT.md).
180
+
181
+ ## Errors
182
+
183
+ All server errors are `GolemError` (`code`, `path`, `extensions`, `retryable`) or a subclass:
184
+
185
+ - `GolemProtocolMismatchError`, `GolemContractMismatchError`: the client and server disagree on the live protocol or the contract. Regenerate the manifest.
186
+ - `GolemDeadlineRequiredError` (`GOLEM_PRINCIPAL_DEADLINE_REQUIRED`): the server refused a live socket because the principal has no deadline. This is a server fix.
187
+ - `GolemUnauthenticatedError`, `GolemHttpError`.
188
+ - `GolemPartialCommitError`, `GolemCommitUnknownError`: a mutation whose commit state is partial or unknown. Affected live queries are invalidated for you, as they are after every committed mutation.
189
+
190
+ Client-side failures: `GolemConfigurationError` (bad setup), `GolemDocumentError` (a document the client cannot run, for example one that sets `cursor` or `skip` itself) and its subclass `GolemMultipleOperationsError` (a document with more than one operation), `GolemNotLiveError`, `GolemNotFoundError`, `GolemProtocolError`.
191
+
192
+ ## Requirements
193
+
194
+ - golem **go/v0.8.2 or later** on the server, with `golem.Subscriptions` on every model a live query reaches.
195
+ - `@tanstack/query-core` 5.
196
+ - A socket deadline for every principal. See [The socket deadline](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md#the-socket-deadline).
197
+
198
+ ## React
199
+
200
+ Use [`@eleven-am/golem-react`](https://www.npmjs.com/package/@eleven-am/golem-react) for hooks and a provider on top of this client.
201
+
202
+ ## Links
203
+
204
+ - [Using golem from React](https://github.com/eleven-am/golem/blob/main/docs/golem-go/REACT.md): a walkthrough from a model to a live component.
205
+ - [golem Go guide](https://github.com/eleven-am/golem/blob/main/docs/golem-go/GUIDE.md): models, policies, events, the manifest and the socket deadline.
206
+ - [Client workspace overview](https://github.com/eleven-am/golem/blob/main/client/README.md)
207
+
208
+ License: GPL-3.0.
@@ -0,0 +1,40 @@
1
+ import { OperationTypeNode, type DocumentNode, type OperationDefinitionNode } from 'graphql';
2
+ import { GolemNotLiveError } from './errors.js';
3
+ import type { ClientManifest } from './manifest.js';
4
+ import type { SubscriptionRequest } from './session.js';
5
+ export interface StreamPlan {
6
+ readonly key: string;
7
+ readonly model: string;
8
+ readonly eventsRoot: string;
9
+ readonly patchable: boolean;
10
+ readonly scope: 'exact' | 'policy-only';
11
+ readonly paths: ReadonlyArray<string>;
12
+ readonly query: string;
13
+ readonly variableNames: ReadonlyArray<string>;
14
+ }
15
+ export interface DocumentAnalysis {
16
+ readonly document: DocumentNode;
17
+ readonly query: string;
18
+ readonly streams: ReadonlyArray<StreamPlan>;
19
+ readonly nullableRoots: ReadonlySet<string>;
20
+ readonly notLive: ReadonlyArray<GolemNotLiveError>;
21
+ readonly live: boolean;
22
+ }
23
+ export declare function assertLive(analysis: DocumentAnalysis): void;
24
+ export declare function streamRequest(stream: StreamPlan, variables?: Readonly<Record<string, unknown>>): SubscriptionRequest;
25
+ export declare function operationOf(document: DocumentNode, kind: OperationTypeNode): OperationDefinitionNode;
26
+ export declare class DocumentAnalyzer {
27
+ private readonly manifest;
28
+ private readonly byText;
29
+ private readonly byNode;
30
+ constructor(manifest: ClientManifest);
31
+ analyze(document: DocumentNode | string): DocumentAnalysis;
32
+ }
33
+ export interface MutationAnalysis {
34
+ readonly query: string;
35
+ readonly roots: ReadonlyArray<{
36
+ readonly name: string;
37
+ readonly models: ReadonlyArray<string>;
38
+ }>;
39
+ }
40
+ export declare function analyzeMutation(document: DocumentNode | string, manifest: ClientManifest): MutationAnalysis;