@contello/client 1.2.2 → 2.0.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/dist/cli.js +1 -1
- package/dist/{generate-PGYNYGNX.js → generate-KWWYQGKR.js} +293 -32
- package/dist/index.cjs +398 -27
- package/dist/index.d.cts +124 -10
- package/dist/index.d.ts +124 -10
- package/dist/index.js +388 -26
- package/package.json +1 -7
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Observable } from 'rxjs';
|
|
2
1
|
import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
|
|
3
2
|
|
|
4
3
|
type HttpAgentOptions = {
|
|
@@ -31,10 +30,54 @@ type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind
|
|
|
31
30
|
type OperationMap = Record<string, OperationDef>;
|
|
32
31
|
type InferResult<T extends OperationDef> = NonNullable<T['__result']>;
|
|
33
32
|
type InferVariables<T extends OperationDef> = NonNullable<T['__variables']>;
|
|
34
|
-
type RpcMethod<T extends OperationDef> = T['kind'] extends 'subscription' ? InferVariables<T> extends Record<string, never> ? () =>
|
|
33
|
+
type RpcMethod<T extends OperationDef> = T['kind'] extends 'subscription' ? InferVariables<T> extends Record<string, never> ? () => AsyncIterable<InferResult<T>> : (variables: InferVariables<T>) => AsyncIterable<InferResult<T>> : InferVariables<T> extends Record<string, never> ? () => Promise<InferResult<T>> : (variables: InferVariables<T>) => Promise<InferResult<T>>;
|
|
35
34
|
type Rpc<T extends OperationMap> = {
|
|
36
35
|
[K in keyof T]: RpcMethod<T[K]>;
|
|
37
36
|
};
|
|
37
|
+
/**
|
|
38
|
+
* Discriminator for how a SourceDef binds to a Subscription field:
|
|
39
|
+
* - `entity` — a Contello entity model collection (`categoriesBatch` etc.), accepts optional `{ ids }` filter
|
|
40
|
+
* - `singleton` — a single Contello entity (`config` etc.), no args
|
|
41
|
+
* - `route` — built-in: `contelloRoutesBatch`, no args
|
|
42
|
+
* - `asset` — built-in: `contelloAssetsBatch`, no args
|
|
43
|
+
* - `i18nMessage` — built-in: `contelloI18nMessagesBatch`, requires `{ collection }`
|
|
44
|
+
*/
|
|
45
|
+
type SourceCardinality = 'entity' | 'singleton' | 'route' | 'asset' | 'i18nMessage';
|
|
46
|
+
type SourceDef<TModel extends string = string, TCardinality extends SourceCardinality = SourceCardinality, TResult = unknown> = {
|
|
47
|
+
/** the GQL fragment text — bundled with transitive deps if any */
|
|
48
|
+
document: string;
|
|
49
|
+
/** the fragment name to spread inside the source subscription — e.g. `Category` */
|
|
50
|
+
fragment: string;
|
|
51
|
+
/** the subscription field this fragment is bound to — `categoriesBatch`, `config`, etc */
|
|
52
|
+
subscription: string;
|
|
53
|
+
__model: TModel;
|
|
54
|
+
__cardinality: TCardinality;
|
|
55
|
+
/** phantom type — exists only at the type level */
|
|
56
|
+
__result?: TResult | undefined;
|
|
57
|
+
};
|
|
58
|
+
type SourceMap = Record<string, SourceDef>;
|
|
59
|
+
/**
|
|
60
|
+
* The bundle emitted by `contello-client generate`. Pass to `createContelloClient({ schema })`
|
|
61
|
+
* (and to `createStore`, `createContello`). Each layer reads what it needs:
|
|
62
|
+
* - client uses `operations` (for `client.rpc.*`) and `sources` (for `client.sources.*`).
|
|
63
|
+
* - store uses `models` (for the dependency resolver) on top of what client uses.
|
|
64
|
+
*/
|
|
65
|
+
type Schema<TOps extends OperationMap = OperationMap, TSources extends SourceMap = SourceMap, TModels extends string = string> = {
|
|
66
|
+
operations: TOps;
|
|
67
|
+
sources: TSources;
|
|
68
|
+
models: Record<TModels, string>;
|
|
69
|
+
};
|
|
70
|
+
type SourceFetcherFor<S> = S extends SourceDef<string, 'singleton', infer R> ? () => Promise<R> : S extends SourceDef<string, 'entity', infer R> ? (vars?: {
|
|
71
|
+
ids?: string[];
|
|
72
|
+
}) => Promise<R[]> : S extends SourceDef<string, 'route', infer R> ? () => Promise<R[]> : S extends SourceDef<string, 'asset', infer R> ? () => Promise<R[]> : S extends SourceDef<string, 'i18nMessage', infer R> ? (vars: {
|
|
73
|
+
collection: string;
|
|
74
|
+
}) => Promise<R[]> : never;
|
|
75
|
+
/** Per-source runtime accessor: `client.sources.category.fetch()` → `Promise<CategoryFragment[]>` etc. */
|
|
76
|
+
type SourceAccessors<TSources extends SourceMap> = {
|
|
77
|
+
[K in keyof TSources]: {
|
|
78
|
+
fetch: SourceFetcherFor<TSources[K]>;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
38
81
|
|
|
39
82
|
type UploadMetadata = {
|
|
40
83
|
name: string;
|
|
@@ -62,11 +105,11 @@ type ConnectionEvents = {
|
|
|
62
105
|
onClosed?: ((context: ConnectionContext) => void) | undefined;
|
|
63
106
|
onError?: ((context: ConnectionContext, error: unknown) => void) | undefined;
|
|
64
107
|
};
|
|
65
|
-
type ContelloClientOptions<
|
|
108
|
+
type ContelloClientOptions<TSchema extends Schema | undefined = undefined> = {
|
|
66
109
|
url: string;
|
|
67
110
|
project: string;
|
|
68
111
|
token: string;
|
|
69
|
-
|
|
112
|
+
schema?: TSchema | undefined;
|
|
70
113
|
connections?: number | undefined;
|
|
71
114
|
http?: HttpAgentOptions | undefined;
|
|
72
115
|
onConnected?: (() => void) | undefined;
|
|
@@ -74,24 +117,95 @@ type ContelloClientOptions<T extends OperationMap | undefined = undefined> = {
|
|
|
74
117
|
onError?: ((error: unknown) => void) | undefined;
|
|
75
118
|
connectionEvents?: ConnectionEvents | undefined;
|
|
76
119
|
};
|
|
77
|
-
declare class ContelloClient<
|
|
120
|
+
declare class ContelloClient<TSchema extends Schema | undefined = undefined> {
|
|
78
121
|
private _pool;
|
|
79
122
|
private _rpc;
|
|
123
|
+
private _sources;
|
|
80
124
|
private _url;
|
|
81
125
|
private _project;
|
|
82
126
|
private _token;
|
|
83
127
|
private _agent;
|
|
84
|
-
constructor(options: ContelloClientOptions<
|
|
85
|
-
get rpc():
|
|
128
|
+
constructor(options: ContelloClientOptions<TSchema>);
|
|
129
|
+
get rpc(): TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : never;
|
|
130
|
+
get sources(): TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : never;
|
|
86
131
|
init(): Promise<void>;
|
|
87
132
|
destroy(): Promise<void>;
|
|
88
133
|
ping(): Promise<void>;
|
|
89
|
-
|
|
134
|
+
/**
|
|
135
|
+
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
136
|
+
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
137
|
+
* down when the iterator is returned (`break`, error, or explicit stop).
|
|
138
|
+
*/
|
|
139
|
+
subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): AsyncIterable<TData>;
|
|
90
140
|
download(fileId: string): Promise<DownloadResult>;
|
|
91
141
|
proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;
|
|
92
142
|
upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;
|
|
93
143
|
execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData>;
|
|
94
144
|
}
|
|
95
|
-
declare function createContelloClient<
|
|
145
|
+
declare function createContelloClient<TSchema extends Schema | undefined = undefined>(options: ContelloClientOptions<TSchema>): ContelloClient<TSchema>;
|
|
146
|
+
|
|
147
|
+
declare function createSourceSubscription(source: SourceDef): string;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Returns the first value yielded by `iter`, then disposes the iterator. Throws if the iterable
|
|
151
|
+
* completes without yielding. Equivalent of rxjs's `firstValueFrom` for AsyncIterables.
|
|
152
|
+
*/
|
|
153
|
+
declare function firstAsync<T>(iter: AsyncIterable<T>): Promise<T>;
|
|
154
|
+
/** Lazy map over an async iterable. Cleanup propagates: breaking the outer iter disposes the inner. */
|
|
155
|
+
declare function mapAsync<T, R>(iter: AsyncIterable<T>, fn: (value: T) => R): AsyncIterable<R>;
|
|
156
|
+
/** Lazy filter over an async iterable. */
|
|
157
|
+
declare function filterAsync<T>(iter: AsyncIterable<T>, predicate: (value: T) => boolean): AsyncIterable<T>;
|
|
158
|
+
/**
|
|
159
|
+
* Concatenates all elements of all arrays yielded by `iter` into a single array. Used to support
|
|
160
|
+
* subscriptions that emit chunks of items before completing.
|
|
161
|
+
*/
|
|
162
|
+
declare function collectAsync<T>(iter: AsyncIterable<T[]>): Promise<T[]>;
|
|
163
|
+
/**
|
|
164
|
+
* Exponential backoff with jitter. `attempt` starts at 0 → ~1s+jitter, 1 → ~2s+jitter, etc.,
|
|
165
|
+
* capped at 30s. Returns a Promise that resolves after the delay.
|
|
166
|
+
*/
|
|
167
|
+
declare function exponentialBackoff(attempt: number): Promise<void>;
|
|
168
|
+
/**
|
|
169
|
+
* Runs `fn` with exponential-backoff retry on rejection. Returns once `fn` resolves successfully.
|
|
170
|
+
* `signal` aborts both the in-flight `fn` (if it observes the signal) and the backoff wait.
|
|
171
|
+
*/
|
|
172
|
+
declare function runWithBackoff(fn: () => Promise<unknown>, signal?: AbortSignal | undefined): Promise<void>;
|
|
173
|
+
/**
|
|
174
|
+
* Long-running stream wrapper: subscribes via `factory()`, yields every value, and on error or
|
|
175
|
+
* unexpected completion re-subscribes with exponential backoff. Stops only when `signal` aborts.
|
|
176
|
+
* Designed for subscriptions that should stay open across reconnects (e.g. the watcher).
|
|
177
|
+
*/
|
|
178
|
+
declare function asyncKeepalive<T>(factory: () => AsyncIterable<T>, signal?: AbortSignal | undefined): AsyncIterable<T>;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Multicast event source with `next` / `error` / `complete` (Subject semantics) plus an
|
|
182
|
+
* `AsyncIterable` view. Two consumption modes that fan out from the same source:
|
|
183
|
+
*
|
|
184
|
+
* - `for await (const v of subject)` — iteration. Each `[Symbol.asyncIterator]()` call returns
|
|
185
|
+
* a fresh per-iterator queue. Stop by `break`ing the loop. On `.error(err)` the iterator's
|
|
186
|
+
* pending `next()` rejects, propagating into the for-await as a thrown exception.
|
|
187
|
+
*
|
|
188
|
+
* - `subject.subscribe(observerOrNext)` — observer style. Pass either a full/partial observer
|
|
189
|
+
* `{ next?, error?, complete? }` or just an `(value) => …` function as the `next`-only shortcut.
|
|
190
|
+
* Returns an unsubscribe function. Missing handlers default to no-ops.
|
|
191
|
+
*
|
|
192
|
+
* Producer side: call `.next(value)` to emit, `.error(err)` to fail the subject (all consumers
|
|
193
|
+
* see the error and are detached), `.complete()` to close cleanly (all consumers see done and
|
|
194
|
+
* are detached). After either `error` or `complete`, further `.next()` calls are dropped and
|
|
195
|
+
* new `.subscribe(...)` calls register a no-op unsubscribe.
|
|
196
|
+
*
|
|
197
|
+
* Backpressure: unbounded queue per pending iterator. Intended for low-frequency events.
|
|
198
|
+
*/
|
|
199
|
+
type AsyncIterableSubject<T> = AsyncIterable<T> & {
|
|
200
|
+
next: (value: T) => void;
|
|
201
|
+
error: (err: unknown) => void;
|
|
202
|
+
complete: () => void;
|
|
203
|
+
subscribe: (observerOrNext: {
|
|
204
|
+
next?: (value: T) => void;
|
|
205
|
+
error?: (err: unknown) => void;
|
|
206
|
+
complete?: () => void;
|
|
207
|
+
} | ((value: T) => void)) => () => void;
|
|
208
|
+
};
|
|
209
|
+
declare function createAsyncIterableSubject<T>(): AsyncIterableSubject<T>;
|
|
96
210
|
|
|
97
|
-
export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
|
|
211
|
+
export { type AsyncIterableSubject, type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type Schema, type SourceAccessors, type SourceCardinality, type SourceDef, type SourceMap, type UploadData, type UploadMetadata, type UploadOptions, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,104 @@
|
|
|
1
1
|
// src/client.ts
|
|
2
2
|
import { createClient } from "graphql-ws";
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
// src/async-iterable-utils.ts
|
|
5
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
6
|
+
var JITTER_MIN_MS = 300;
|
|
7
|
+
var JITTER_MAX_MS = 3e3;
|
|
8
|
+
async function firstAsync(iter) {
|
|
9
|
+
const it = iter[Symbol.asyncIterator]();
|
|
10
|
+
try {
|
|
11
|
+
const result = await it.next();
|
|
12
|
+
if (result.done) {
|
|
13
|
+
throw new Error("firstAsync: async iterable completed without yielding a value");
|
|
14
|
+
}
|
|
15
|
+
return result.value;
|
|
16
|
+
} finally {
|
|
17
|
+
await it.return?.();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function* mapAsync(iter, fn) {
|
|
21
|
+
for await (const value of iter) {
|
|
22
|
+
yield fn(value);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function* filterAsync(iter, predicate) {
|
|
26
|
+
for await (const value of iter) {
|
|
27
|
+
if (predicate(value)) {
|
|
28
|
+
yield value;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function collectAsync(iter) {
|
|
33
|
+
const out = [];
|
|
34
|
+
for await (const chunk of iter) {
|
|
35
|
+
out.push(...chunk);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
function exponentialBackoff(attempt) {
|
|
40
|
+
const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
|
|
41
|
+
const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
|
|
42
|
+
return delay(base + jitter);
|
|
43
|
+
}
|
|
44
|
+
function delay(ms, signal) {
|
|
45
|
+
if (signal?.aborted) {
|
|
46
|
+
return Promise.reject(signal.reason);
|
|
47
|
+
}
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const timer = setTimeout(() => {
|
|
50
|
+
signal?.removeEventListener("abort", onAbort);
|
|
51
|
+
resolve();
|
|
52
|
+
}, ms);
|
|
53
|
+
const onAbort = () => {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
reject(signal.reason);
|
|
56
|
+
};
|
|
57
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async function runWithBackoff(fn, signal) {
|
|
61
|
+
let attempt = 0;
|
|
62
|
+
for (; ; ) {
|
|
63
|
+
if (signal?.aborted) {
|
|
64
|
+
throw signal.reason;
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
await fn();
|
|
68
|
+
return;
|
|
69
|
+
} catch {
|
|
70
|
+
await exponentialBackoffWithSignal(attempt, signal);
|
|
71
|
+
attempt++;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function exponentialBackoffWithSignal(attempt, signal) {
|
|
76
|
+
const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
|
|
77
|
+
const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
|
|
78
|
+
return delay(base + jitter, signal);
|
|
79
|
+
}
|
|
80
|
+
async function* asyncKeepalive(factory, signal) {
|
|
81
|
+
let attempt = 0;
|
|
82
|
+
while (!signal?.aborted) {
|
|
83
|
+
try {
|
|
84
|
+
for await (const value of factory()) {
|
|
85
|
+
if (signal?.aborted) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
yield value;
|
|
89
|
+
attempt = 0;
|
|
90
|
+
}
|
|
91
|
+
attempt = 0;
|
|
92
|
+
} catch (err) {
|
|
93
|
+
if (signal?.aborted) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
void err;
|
|
97
|
+
await exponentialBackoffWithSignal(attempt, signal);
|
|
98
|
+
attempt++;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
4
102
|
|
|
5
103
|
// src/diagnostics.ts
|
|
6
104
|
import dc from "diagnostics_channel";
|
|
@@ -231,9 +329,6 @@ var ConnectionPool = class {
|
|
|
231
329
|
}
|
|
232
330
|
};
|
|
233
331
|
|
|
234
|
-
// src/rpc.ts
|
|
235
|
-
import { firstValueFrom, map } from "rxjs";
|
|
236
|
-
|
|
237
332
|
// src/transform-response.ts
|
|
238
333
|
var FLAT_PREFIX = "_flat_";
|
|
239
334
|
var MODEL_SUFFIXES = ["Entity", "Component"];
|
|
@@ -327,21 +422,86 @@ function resolveNestedRefs(value, flatMap) {
|
|
|
327
422
|
}
|
|
328
423
|
|
|
329
424
|
// src/rpc.ts
|
|
330
|
-
function buildRpc(operations,
|
|
425
|
+
function buildRpc(operations, subscribe) {
|
|
331
426
|
const rpc = {};
|
|
332
427
|
for (const [name, def] of Object.entries(operations)) {
|
|
333
428
|
if (def.kind === "subscription") {
|
|
334
|
-
rpc[name] = (variables) =>
|
|
429
|
+
rpc[name] = (variables) => mapAsync(subscribe(def.document, variables), transformResponse);
|
|
335
430
|
} else {
|
|
336
|
-
rpc[name] = (variables) => wrap(
|
|
337
|
-
`rpc:${name}`,
|
|
338
|
-
() => firstValueFrom(client.subscribe(def.document, variables).pipe(map(transformResponse)))
|
|
339
|
-
);
|
|
431
|
+
rpc[name] = (variables) => wrap(`rpc:${name}`, () => firstAsync(mapAsync(subscribe(def.document, variables), transformResponse)));
|
|
340
432
|
}
|
|
341
433
|
}
|
|
342
434
|
return rpc;
|
|
343
435
|
}
|
|
344
436
|
|
|
437
|
+
// src/source-subscription.ts
|
|
438
|
+
var cache = /* @__PURE__ */ new WeakMap();
|
|
439
|
+
function createSelection(source) {
|
|
440
|
+
const spread = `{ ...${source.fragment} }`;
|
|
441
|
+
switch (source.__cardinality) {
|
|
442
|
+
case "singleton":
|
|
443
|
+
return `subscription { source: ${source.subscription} ${spread} }`;
|
|
444
|
+
case "entity":
|
|
445
|
+
return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
|
|
446
|
+
case "route":
|
|
447
|
+
case "asset":
|
|
448
|
+
return `subscription { source: ${source.subscription} ${spread} }`;
|
|
449
|
+
case "i18nMessage":
|
|
450
|
+
return `subscription($collection: String!) { source: ${source.subscription}(collectionReferenceName: $collection) ${spread} }`;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function createSourceSubscription(source) {
|
|
454
|
+
const cached = cache.get(source);
|
|
455
|
+
if (cached !== void 0) {
|
|
456
|
+
return cached;
|
|
457
|
+
}
|
|
458
|
+
const doc = `${source.document}
|
|
459
|
+
${createSelection(source)}`;
|
|
460
|
+
cache.set(source, doc);
|
|
461
|
+
return doc;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// src/sources.ts
|
|
465
|
+
function createSources(sources, subscribe) {
|
|
466
|
+
const out = {};
|
|
467
|
+
for (const [name, source] of Object.entries(sources)) {
|
|
468
|
+
const def = source;
|
|
469
|
+
const doc = createSourceSubscription(def);
|
|
470
|
+
switch (def.__cardinality) {
|
|
471
|
+
case "singleton":
|
|
472
|
+
out[name] = {
|
|
473
|
+
fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
|
|
474
|
+
};
|
|
475
|
+
break;
|
|
476
|
+
case "entity":
|
|
477
|
+
out[name] = {
|
|
478
|
+
fetch: (vars) => wrap(
|
|
479
|
+
`source:${name}`,
|
|
480
|
+
() => firstAsync(mapAsync(subscribe(doc, { ids: vars?.ids }), (r) => r.source))
|
|
481
|
+
)
|
|
482
|
+
};
|
|
483
|
+
break;
|
|
484
|
+
case "route":
|
|
485
|
+
case "asset":
|
|
486
|
+
out[name] = {
|
|
487
|
+
fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
|
|
488
|
+
};
|
|
489
|
+
break;
|
|
490
|
+
case "i18nMessage":
|
|
491
|
+
out[name] = {
|
|
492
|
+
fetch: (vars) => wrap(
|
|
493
|
+
`source:${name}`,
|
|
494
|
+
() => firstAsync(
|
|
495
|
+
mapAsync(subscribe(doc, { collection: vars.collection }), (r) => r.source)
|
|
496
|
+
)
|
|
497
|
+
)
|
|
498
|
+
};
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return out;
|
|
503
|
+
}
|
|
504
|
+
|
|
345
505
|
// src/upload.ts
|
|
346
506
|
var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
|
347
507
|
function isUint8Array(data) {
|
|
@@ -427,23 +587,24 @@ function upload(url, project, token, data, meta, options) {
|
|
|
427
587
|
|
|
428
588
|
// src/utils.ts
|
|
429
589
|
var MAX_DELAY_MS = 3e4;
|
|
430
|
-
var
|
|
431
|
-
var
|
|
432
|
-
function
|
|
433
|
-
const
|
|
434
|
-
return new Promise((resolve) => setTimeout(resolve,
|
|
590
|
+
var JITTER_MIN_MS2 = 300;
|
|
591
|
+
var JITTER_MAX_MS2 = 3e3;
|
|
592
|
+
function wsRetryWait(retries) {
|
|
593
|
+
const delay2 = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS2 - JITTER_MIN_MS2) + JITTER_MIN_MS2);
|
|
594
|
+
return new Promise((resolve) => setTimeout(resolve, delay2));
|
|
435
595
|
}
|
|
436
596
|
|
|
437
597
|
// src/client.ts
|
|
438
598
|
var ContelloClient = class {
|
|
439
599
|
_pool;
|
|
440
600
|
_rpc;
|
|
601
|
+
_sources;
|
|
441
602
|
_url;
|
|
442
603
|
_project;
|
|
443
604
|
_token;
|
|
444
605
|
_agent;
|
|
445
606
|
constructor(options) {
|
|
446
|
-
const { url, project, token,
|
|
607
|
+
const { url, project, token, schema, connections = 1, connectionEvents } = options;
|
|
447
608
|
this._url = url;
|
|
448
609
|
this._project = project;
|
|
449
610
|
this._token = token;
|
|
@@ -475,7 +636,7 @@ var ContelloClient = class {
|
|
|
475
636
|
lazy: false,
|
|
476
637
|
keepAlive: 3e4,
|
|
477
638
|
retryAttempts: Infinity,
|
|
478
|
-
retryWait:
|
|
639
|
+
retryWait: wsRetryWait,
|
|
479
640
|
shouldRetry: () => true,
|
|
480
641
|
jsonMessageReplacer: (key, value) => {
|
|
481
642
|
if (!key) {
|
|
@@ -505,14 +666,21 @@ var ContelloClient = class {
|
|
|
505
666
|
}
|
|
506
667
|
});
|
|
507
668
|
}, connections);
|
|
508
|
-
this._rpc = operations ? buildRpc(operations, this) : void 0;
|
|
669
|
+
this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
|
|
670
|
+
this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
|
|
509
671
|
}
|
|
510
672
|
get rpc() {
|
|
511
673
|
if (!this._rpc) {
|
|
512
|
-
throw new Error("@contello/client: .rpc accessed without operations");
|
|
674
|
+
throw new Error("@contello/client: .rpc accessed without a schema containing operations");
|
|
513
675
|
}
|
|
514
676
|
return this._rpc;
|
|
515
677
|
}
|
|
678
|
+
get sources() {
|
|
679
|
+
if (!this._sources) {
|
|
680
|
+
throw new Error("@contello/client: .sources accessed without a schema containing sources");
|
|
681
|
+
}
|
|
682
|
+
return this._sources;
|
|
683
|
+
}
|
|
516
684
|
async init() {
|
|
517
685
|
await this._pool.connect();
|
|
518
686
|
}
|
|
@@ -521,13 +689,83 @@ var ContelloClient = class {
|
|
|
521
689
|
await this._agent.close();
|
|
522
690
|
}
|
|
523
691
|
async ping() {
|
|
524
|
-
return ping((query) =>
|
|
692
|
+
return ping((query) => firstAsync(this.subscribe(query)));
|
|
525
693
|
}
|
|
694
|
+
/**
|
|
695
|
+
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
696
|
+
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
697
|
+
* down when the iterator is returned (`break`, error, or explicit stop).
|
|
698
|
+
*/
|
|
526
699
|
subscribe(query, variables) {
|
|
527
|
-
const
|
|
528
|
-
return
|
|
529
|
-
|
|
530
|
-
|
|
700
|
+
const pool = this._pool;
|
|
701
|
+
return {
|
|
702
|
+
[Symbol.asyncIterator]() {
|
|
703
|
+
const wsClient = pool.get();
|
|
704
|
+
const queue = [];
|
|
705
|
+
let pending;
|
|
706
|
+
let done = false;
|
|
707
|
+
let error;
|
|
708
|
+
const unsubscribe = wsClient.subscribe(
|
|
709
|
+
{ query, variables },
|
|
710
|
+
{
|
|
711
|
+
next(msg) {
|
|
712
|
+
const value = msg.data;
|
|
713
|
+
if (value === void 0 || value === null) {
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (pending) {
|
|
717
|
+
const p = pending;
|
|
718
|
+
pending = void 0;
|
|
719
|
+
p.resolve({ value, done: false });
|
|
720
|
+
} else {
|
|
721
|
+
queue.push(value);
|
|
722
|
+
}
|
|
723
|
+
},
|
|
724
|
+
error(err) {
|
|
725
|
+
done = true;
|
|
726
|
+
error = err;
|
|
727
|
+
if (pending) {
|
|
728
|
+
const p = pending;
|
|
729
|
+
pending = void 0;
|
|
730
|
+
p.reject(err);
|
|
731
|
+
}
|
|
732
|
+
},
|
|
733
|
+
complete() {
|
|
734
|
+
done = true;
|
|
735
|
+
if (pending) {
|
|
736
|
+
const p = pending;
|
|
737
|
+
pending = void 0;
|
|
738
|
+
p.resolve({ value: void 0, done: true });
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
);
|
|
743
|
+
return {
|
|
744
|
+
next() {
|
|
745
|
+
if (queue.length > 0) {
|
|
746
|
+
return Promise.resolve({ value: queue.shift(), done: false });
|
|
747
|
+
}
|
|
748
|
+
if (error !== void 0) {
|
|
749
|
+
return Promise.reject(error);
|
|
750
|
+
}
|
|
751
|
+
if (done) {
|
|
752
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
753
|
+
}
|
|
754
|
+
return new Promise((resolve, reject) => {
|
|
755
|
+
pending = { resolve, reject };
|
|
756
|
+
});
|
|
757
|
+
},
|
|
758
|
+
return() {
|
|
759
|
+
unsubscribe();
|
|
760
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
761
|
+
},
|
|
762
|
+
throw(err) {
|
|
763
|
+
unsubscribe();
|
|
764
|
+
return Promise.reject(err);
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
};
|
|
531
769
|
}
|
|
532
770
|
download(fileId) {
|
|
533
771
|
return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
|
|
@@ -542,13 +780,137 @@ var ContelloClient = class {
|
|
|
542
780
|
);
|
|
543
781
|
}
|
|
544
782
|
execute(query, variables) {
|
|
545
|
-
return wrap("@contello/client:execute", () =>
|
|
783
|
+
return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)));
|
|
546
784
|
}
|
|
547
785
|
};
|
|
548
786
|
function createContelloClient(options) {
|
|
549
787
|
return new ContelloClient(options);
|
|
550
788
|
}
|
|
789
|
+
|
|
790
|
+
// src/async-iterable-subject.ts
|
|
791
|
+
function createAsyncIterableSubject() {
|
|
792
|
+
const consumers = /* @__PURE__ */ new Set();
|
|
793
|
+
let status = { state: "open" };
|
|
794
|
+
const next = (value) => {
|
|
795
|
+
if (status.state !== "open") {
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
for (const consumer of consumers) {
|
|
799
|
+
if (consumer.kind === "listener") {
|
|
800
|
+
consumer.next?.(value);
|
|
801
|
+
} else if (consumer.pending) {
|
|
802
|
+
const p = consumer.pending;
|
|
803
|
+
consumer.pending = void 0;
|
|
804
|
+
p.resolve({ value, done: false });
|
|
805
|
+
} else {
|
|
806
|
+
consumer.queue.push(value);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
const error = (err) => {
|
|
811
|
+
if (status.state !== "open") {
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
status = { state: "errored", err };
|
|
815
|
+
for (const consumer of consumers) {
|
|
816
|
+
if (consumer.kind === "listener") {
|
|
817
|
+
consumer.error?.(err);
|
|
818
|
+
} else if (consumer.pending) {
|
|
819
|
+
const p = consumer.pending;
|
|
820
|
+
consumer.pending = void 0;
|
|
821
|
+
p.reject(err);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
consumers.clear();
|
|
825
|
+
};
|
|
826
|
+
const complete = () => {
|
|
827
|
+
if (status.state !== "open") {
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
status = { state: "completed" };
|
|
831
|
+
for (const consumer of consumers) {
|
|
832
|
+
if (consumer.kind === "listener") {
|
|
833
|
+
consumer.complete?.();
|
|
834
|
+
} else if (consumer.pending) {
|
|
835
|
+
const p = consumer.pending;
|
|
836
|
+
consumer.pending = void 0;
|
|
837
|
+
p.resolve({ value: void 0, done: true });
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
consumers.clear();
|
|
841
|
+
};
|
|
842
|
+
const subscribe = (observerOrNext) => {
|
|
843
|
+
if (status.state !== "open") {
|
|
844
|
+
return () => {
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
const observer = typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext;
|
|
848
|
+
const consumer = { kind: "listener", ...observer };
|
|
849
|
+
consumers.add(consumer);
|
|
850
|
+
return () => {
|
|
851
|
+
consumers.delete(consumer);
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
const iterable = {
|
|
855
|
+
[Symbol.asyncIterator]() {
|
|
856
|
+
if (status.state === "errored") {
|
|
857
|
+
const err = status.err;
|
|
858
|
+
return {
|
|
859
|
+
next: () => Promise.reject(err),
|
|
860
|
+
return: () => Promise.resolve({ value: void 0, done: true })
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
if (status.state === "completed") {
|
|
864
|
+
return {
|
|
865
|
+
next: () => Promise.resolve({ value: void 0, done: true }),
|
|
866
|
+
return: () => Promise.resolve({ value: void 0, done: true })
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
const consumer = { kind: "iterator", queue: [] };
|
|
870
|
+
consumers.add(consumer);
|
|
871
|
+
return {
|
|
872
|
+
next() {
|
|
873
|
+
if (consumer.queue.length > 0) {
|
|
874
|
+
return Promise.resolve({ value: consumer.queue.shift(), done: false });
|
|
875
|
+
}
|
|
876
|
+
if (status.state === "errored") {
|
|
877
|
+
return Promise.reject(status.err);
|
|
878
|
+
}
|
|
879
|
+
if (status.state === "completed") {
|
|
880
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
881
|
+
}
|
|
882
|
+
return new Promise((resolve, reject) => {
|
|
883
|
+
consumer.pending = { resolve, reject };
|
|
884
|
+
});
|
|
885
|
+
},
|
|
886
|
+
return() {
|
|
887
|
+
consumers.delete(consumer);
|
|
888
|
+
if (consumer.pending) {
|
|
889
|
+
const p = consumer.pending;
|
|
890
|
+
consumer.pending = void 0;
|
|
891
|
+
p.resolve({ value: void 0, done: true });
|
|
892
|
+
}
|
|
893
|
+
return Promise.resolve({ value: void 0, done: true });
|
|
894
|
+
},
|
|
895
|
+
throw(err) {
|
|
896
|
+
consumers.delete(consumer);
|
|
897
|
+
return Promise.reject(err);
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
return Object.assign(iterable, { next, error, complete, subscribe });
|
|
903
|
+
}
|
|
551
904
|
export {
|
|
552
905
|
ContelloClient,
|
|
553
|
-
|
|
906
|
+
asyncKeepalive,
|
|
907
|
+
collectAsync,
|
|
908
|
+
createAsyncIterableSubject,
|
|
909
|
+
createContelloClient,
|
|
910
|
+
createSourceSubscription,
|
|
911
|
+
exponentialBackoff,
|
|
912
|
+
filterAsync,
|
|
913
|
+
firstAsync,
|
|
914
|
+
mapAsync,
|
|
915
|
+
runWithBackoff
|
|
554
916
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@contello/client",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "GraphQL client for Contello CMS with WebSocket transport, connection pooling, and built-in codegen",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -15,12 +15,6 @@
|
|
|
15
15
|
"graphql-ws": "^6.0.8",
|
|
16
16
|
"undici": "^8.1.0"
|
|
17
17
|
},
|
|
18
|
-
"peerDependencies": {
|
|
19
|
-
"rxjs": "^7.0.0"
|
|
20
|
-
},
|
|
21
|
-
"devDependencies": {
|
|
22
|
-
"rxjs": "^7.8.2"
|
|
23
|
-
},
|
|
24
18
|
"bin": {
|
|
25
19
|
"contello-client": "./dist/cli.js"
|
|
26
20
|
},
|