@contello/client 1.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 +15 -0
- package/dist/generate-OTWB5J56.js +827 -0
- package/dist/index.cjs +476 -0
- package/dist/index.d.cts +83 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.js +438 -0
- package/package.json +46 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { createClient } from "graphql-ws";
|
|
3
|
+
import { Observable, firstValueFrom as firstValueFrom2, map as map2 } from "rxjs";
|
|
4
|
+
|
|
5
|
+
// src/diagnostics.ts
|
|
6
|
+
import dc from "diagnostics_channel";
|
|
7
|
+
var channels = {
|
|
8
|
+
start: "@contello/client:start",
|
|
9
|
+
end: "@contello/client:end",
|
|
10
|
+
error: "@contello/client:error",
|
|
11
|
+
/** subscribe to decorate outgoing GraphQL WebSocket messages (e.g. inject traceparent) */
|
|
12
|
+
message: "@contello/client:message"
|
|
13
|
+
};
|
|
14
|
+
var onStart = dc.channel(channels.start);
|
|
15
|
+
var onEnd = dc.channel(channels.end);
|
|
16
|
+
var onError = dc.channel(channels.error);
|
|
17
|
+
var onMessage = dc.channel(channels.message);
|
|
18
|
+
function hasOperationSubscribers() {
|
|
19
|
+
return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
|
|
20
|
+
}
|
|
21
|
+
function wrap(name, fn) {
|
|
22
|
+
if (!hasOperationSubscribers()) {
|
|
23
|
+
return fn();
|
|
24
|
+
}
|
|
25
|
+
const start = performance.now();
|
|
26
|
+
onStart.publish({ name });
|
|
27
|
+
let result;
|
|
28
|
+
try {
|
|
29
|
+
result = fn();
|
|
30
|
+
} catch (error) {
|
|
31
|
+
onError.publish({ name, error, durationMs: performance.now() - start });
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
if (result instanceof Promise) {
|
|
35
|
+
return result.then(
|
|
36
|
+
(r) => {
|
|
37
|
+
onEnd.publish({ name, durationMs: performance.now() - start });
|
|
38
|
+
return r;
|
|
39
|
+
},
|
|
40
|
+
(error) => {
|
|
41
|
+
onError.publish({ name, error, durationMs: performance.now() - start });
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
onEnd.publish({ name, durationMs: performance.now() - start });
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
function decorateMessage(message) {
|
|
50
|
+
if (!onMessage.hasSubscribers) {
|
|
51
|
+
return message;
|
|
52
|
+
}
|
|
53
|
+
const msg = { message };
|
|
54
|
+
onMessage.publish(msg);
|
|
55
|
+
return msg.message;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/download.ts
|
|
59
|
+
async function downloadFile(url, token, fileId) {
|
|
60
|
+
const response = await fetch(`${url}/api/v1/assets/files/${fileId}`, {
|
|
61
|
+
headers: { token }
|
|
62
|
+
});
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
throw new Error(`download failed: ${response.status} ${response.statusText}`);
|
|
65
|
+
}
|
|
66
|
+
if (!response.body) {
|
|
67
|
+
throw new Error("download response has no body");
|
|
68
|
+
}
|
|
69
|
+
const mimeType = response.headers.get("content-type") ?? "application/octet-stream";
|
|
70
|
+
const size = Number(response.headers.get("content-length") ?? 0);
|
|
71
|
+
return {
|
|
72
|
+
mimeType,
|
|
73
|
+
size,
|
|
74
|
+
bytes: () => response.arrayBuffer().then((buf) => new Uint8Array(buf)),
|
|
75
|
+
stream: () => response.body
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/ping.ts
|
|
80
|
+
var PING_QUERY = `query ContelloPing { contelloPing { response } }`;
|
|
81
|
+
async function ping(execute) {
|
|
82
|
+
const data = await execute(PING_QUERY);
|
|
83
|
+
if (data.contelloPing.response !== "pong") {
|
|
84
|
+
throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/pool.ts
|
|
89
|
+
var ConnectionPool = class {
|
|
90
|
+
constructor(createClient2, poolSize) {
|
|
91
|
+
this.createClient = createClient2;
|
|
92
|
+
this.poolSize = poolSize;
|
|
93
|
+
}
|
|
94
|
+
clients = [];
|
|
95
|
+
currentIndex = 0;
|
|
96
|
+
async connect() {
|
|
97
|
+
const connected = [];
|
|
98
|
+
for (let i = 0; i < this.poolSize; i++) {
|
|
99
|
+
const client = this.createClient(`${i + 1}`);
|
|
100
|
+
this.clients.push(client);
|
|
101
|
+
connected.push(
|
|
102
|
+
new Promise((resolve) => {
|
|
103
|
+
const unsubscribe = client.on("connected", () => {
|
|
104
|
+
unsubscribe();
|
|
105
|
+
resolve();
|
|
106
|
+
});
|
|
107
|
+
})
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
await Promise.all(connected);
|
|
111
|
+
}
|
|
112
|
+
get() {
|
|
113
|
+
if (this.clients.length === 0) {
|
|
114
|
+
throw new Error("Connection pool is empty. Please call connect() first.");
|
|
115
|
+
}
|
|
116
|
+
const client = this.clients[this.currentIndex];
|
|
117
|
+
this.currentIndex = (this.currentIndex + 1) % this.poolSize;
|
|
118
|
+
if (!client) {
|
|
119
|
+
throw new Error("No available WebSocket client");
|
|
120
|
+
}
|
|
121
|
+
return client;
|
|
122
|
+
}
|
|
123
|
+
async disconnect() {
|
|
124
|
+
const closed = this.clients.map(
|
|
125
|
+
(client) => new Promise((resolve) => {
|
|
126
|
+
const unsubscribe = client.on("closed", () => {
|
|
127
|
+
unsubscribe();
|
|
128
|
+
resolve();
|
|
129
|
+
});
|
|
130
|
+
client.dispose();
|
|
131
|
+
})
|
|
132
|
+
);
|
|
133
|
+
this.clients = [];
|
|
134
|
+
await Promise.all(closed);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// src/rpc.ts
|
|
139
|
+
import { firstValueFrom, map } from "rxjs";
|
|
140
|
+
|
|
141
|
+
// src/transform-response.ts
|
|
142
|
+
var FLAT_PREFIX = "_flat_";
|
|
143
|
+
var MODEL_SUFFIXES = ["Entity", "Component"];
|
|
144
|
+
function deriveModel(typename) {
|
|
145
|
+
for (const suffix of MODEL_SUFFIXES) {
|
|
146
|
+
if (typename.endsWith(suffix)) {
|
|
147
|
+
const stripped = typename.slice(0, -suffix.length);
|
|
148
|
+
return stripped.charAt(0).toLowerCase() + stripped.slice(1);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return void 0;
|
|
152
|
+
}
|
|
153
|
+
function transformResponse(data) {
|
|
154
|
+
if (data === null || data === void 0 || typeof data !== "object") {
|
|
155
|
+
return data;
|
|
156
|
+
}
|
|
157
|
+
if (Array.isArray(data)) {
|
|
158
|
+
for (const item of data) {
|
|
159
|
+
transformResponse(item);
|
|
160
|
+
}
|
|
161
|
+
return data;
|
|
162
|
+
}
|
|
163
|
+
const obj = data;
|
|
164
|
+
const typename = obj["__typename"];
|
|
165
|
+
if (typeof typename === "string") {
|
|
166
|
+
const model = deriveModel(typename);
|
|
167
|
+
if (model) {
|
|
168
|
+
obj["__model"] = model;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const flatKeys = Object.keys(obj).filter((k) => k.startsWith(FLAT_PREFIX));
|
|
172
|
+
for (const flatKey of flatKeys) {
|
|
173
|
+
const fieldKey = flatKey.slice(FLAT_PREFIX.length);
|
|
174
|
+
const flatArray = obj[flatKey];
|
|
175
|
+
const refArray = obj[fieldKey];
|
|
176
|
+
if (!flatArray || !refArray) {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const flatMap = /* @__PURE__ */ new Map();
|
|
180
|
+
for (const component of flatArray) {
|
|
181
|
+
if (component._flatId) {
|
|
182
|
+
flatMap.set(component._flatId, component);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
obj[fieldKey] = resolveRefs(refArray, flatMap);
|
|
186
|
+
delete obj[flatKey];
|
|
187
|
+
}
|
|
188
|
+
for (const key of Object.keys(obj)) {
|
|
189
|
+
const value = obj[key];
|
|
190
|
+
if (value && typeof value === "object") {
|
|
191
|
+
if (Array.isArray(value)) {
|
|
192
|
+
for (const item of value) {
|
|
193
|
+
if (item && typeof item === "object") {
|
|
194
|
+
transformResponse(item);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} else {
|
|
198
|
+
transformResponse(value);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return data;
|
|
203
|
+
}
|
|
204
|
+
function resolveRefs(refs, flatMap) {
|
|
205
|
+
return refs.flatMap((ref) => {
|
|
206
|
+
if (!ref._flatId) return [];
|
|
207
|
+
const component = flatMap.get(ref._flatId);
|
|
208
|
+
if (!component) return [];
|
|
209
|
+
for (const [key, value] of Object.entries(component)) {
|
|
210
|
+
if (Array.isArray(value) && value.length > 0 && value[0]?._flatId !== void 0) {
|
|
211
|
+
component[key] = resolveRefs(value, flatMap);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
transformResponse(component);
|
|
215
|
+
return [component];
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/rpc.ts
|
|
220
|
+
function buildRpc(operations, client) {
|
|
221
|
+
const rpc = {};
|
|
222
|
+
for (const [name, def] of Object.entries(operations)) {
|
|
223
|
+
if (def.kind === "subscription") {
|
|
224
|
+
rpc[name] = (variables) => client.subscribe(def.document, variables).pipe(map(transformResponse));
|
|
225
|
+
} else {
|
|
226
|
+
rpc[name] = (variables) => wrap(
|
|
227
|
+
`rpc:${name}`,
|
|
228
|
+
() => firstValueFrom(client.subscribe(def.document, variables).pipe(map(transformResponse)))
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return rpc;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/upload.ts
|
|
236
|
+
var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
|
237
|
+
function isUint8Array(data) {
|
|
238
|
+
return data instanceof Uint8Array;
|
|
239
|
+
}
|
|
240
|
+
function upload(url, project, token, data, meta, options) {
|
|
241
|
+
const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
242
|
+
const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
|
|
243
|
+
const size = isUint8Array(data) ? data.length : meta.size;
|
|
244
|
+
return new Promise((resolve, reject) => {
|
|
245
|
+
const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
|
|
246
|
+
let done = false;
|
|
247
|
+
const cleanup = () => {
|
|
248
|
+
options?.abort?.removeEventListener("abort", abortHandler);
|
|
249
|
+
};
|
|
250
|
+
const abortHandler = () => {
|
|
251
|
+
if (!done) {
|
|
252
|
+
ws.close();
|
|
253
|
+
reject(new Error("upload aborted"));
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
options?.abort?.addEventListener("abort", abortHandler);
|
|
257
|
+
function sendBuffer(buf) {
|
|
258
|
+
let offset = 0;
|
|
259
|
+
while (offset < buf.length) {
|
|
260
|
+
const chunk = buf.subarray(offset, offset + chunkSize);
|
|
261
|
+
ws.send(chunk);
|
|
262
|
+
offset += chunk.length;
|
|
263
|
+
}
|
|
264
|
+
ws.send(JSON.stringify({ type: "done" }));
|
|
265
|
+
}
|
|
266
|
+
async function sendStream(stream) {
|
|
267
|
+
const reader = stream.getReader();
|
|
268
|
+
try {
|
|
269
|
+
while (true) {
|
|
270
|
+
const { done: streamDone, value } = await reader.read();
|
|
271
|
+
if (streamDone) break;
|
|
272
|
+
ws.send(value);
|
|
273
|
+
}
|
|
274
|
+
ws.send(JSON.stringify({ type: "done" }));
|
|
275
|
+
} catch (err) {
|
|
276
|
+
reject(err);
|
|
277
|
+
ws.close();
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
ws.addEventListener("open", () => {
|
|
281
|
+
const initFrame = {
|
|
282
|
+
type: "init",
|
|
283
|
+
metadata: { ...meta, ...size !== void 0 ? { size } : {}, projectRef: project },
|
|
284
|
+
token
|
|
285
|
+
};
|
|
286
|
+
ws.send(JSON.stringify(initFrame));
|
|
287
|
+
});
|
|
288
|
+
ws.addEventListener("message", (event) => {
|
|
289
|
+
const message = JSON.parse(String(event.data));
|
|
290
|
+
if (message.type === "ack") {
|
|
291
|
+
if (isUint8Array(data)) {
|
|
292
|
+
sendBuffer(data);
|
|
293
|
+
} else {
|
|
294
|
+
sendStream(data);
|
|
295
|
+
}
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (message.type === "done") {
|
|
299
|
+
done = true;
|
|
300
|
+
cleanup();
|
|
301
|
+
ws.close();
|
|
302
|
+
resolve(message.id);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
ws.addEventListener("error", () => {
|
|
306
|
+
cleanup();
|
|
307
|
+
reject(new Error("upload websocket error"));
|
|
308
|
+
});
|
|
309
|
+
ws.addEventListener("close", () => {
|
|
310
|
+
cleanup();
|
|
311
|
+
if (!done) {
|
|
312
|
+
reject(new Error("connection closed before upload completed"));
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// src/utils.ts
|
|
319
|
+
var MAX_DELAY_MS = 3e4;
|
|
320
|
+
var JITTER_MIN_MS = 300;
|
|
321
|
+
var JITTER_MAX_MS = 3e3;
|
|
322
|
+
function exponentialBackoff(retries) {
|
|
323
|
+
const delay = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
|
|
324
|
+
return new Promise((resolve) => setTimeout(resolve, delay));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// src/client.ts
|
|
328
|
+
var ContelloClient = class {
|
|
329
|
+
_pool;
|
|
330
|
+
_rpc;
|
|
331
|
+
_url;
|
|
332
|
+
_project;
|
|
333
|
+
_token;
|
|
334
|
+
constructor(options) {
|
|
335
|
+
const { url, project, token, operations, connections = 1, connectionEvents } = options;
|
|
336
|
+
this._url = url;
|
|
337
|
+
this._project = project;
|
|
338
|
+
this._token = token;
|
|
339
|
+
const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
|
|
340
|
+
let state = "disconnected";
|
|
341
|
+
let connectedCount = 0;
|
|
342
|
+
const onConnectionUp = () => {
|
|
343
|
+
connectedCount++;
|
|
344
|
+
if (connectedCount === connections && state !== "connected") {
|
|
345
|
+
state = "connected";
|
|
346
|
+
options.onConnected?.();
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
const onConnectionDown = () => {
|
|
350
|
+
if (connectedCount > 0) {
|
|
351
|
+
connectedCount--;
|
|
352
|
+
}
|
|
353
|
+
if (state === "connected") {
|
|
354
|
+
state = "reconnecting";
|
|
355
|
+
options.onReconnecting?.();
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
this._pool = new ConnectionPool((id) => {
|
|
359
|
+
const context = Object.freeze({ connectionId: id, websocketUrl });
|
|
360
|
+
return createClient({
|
|
361
|
+
url: websocketUrl,
|
|
362
|
+
connectionParams: { token },
|
|
363
|
+
lazy: false,
|
|
364
|
+
keepAlive: 3e4,
|
|
365
|
+
retryAttempts: Infinity,
|
|
366
|
+
retryWait: exponentialBackoff,
|
|
367
|
+
shouldRetry: () => true,
|
|
368
|
+
jsonMessageReplacer: (key, value) => {
|
|
369
|
+
if (!key) {
|
|
370
|
+
return decorateMessage(value);
|
|
371
|
+
}
|
|
372
|
+
return value;
|
|
373
|
+
},
|
|
374
|
+
...options.onError ? { onNonLazyError: (e) => options.onError(e) } : {},
|
|
375
|
+
on: {
|
|
376
|
+
connected: () => {
|
|
377
|
+
onConnectionUp();
|
|
378
|
+
connectionEvents?.onConnected?.(context);
|
|
379
|
+
},
|
|
380
|
+
connecting: () => {
|
|
381
|
+
connectionEvents?.onConnecting?.(context);
|
|
382
|
+
},
|
|
383
|
+
closed: () => {
|
|
384
|
+
onConnectionDown();
|
|
385
|
+
connectionEvents?.onClosed?.(context);
|
|
386
|
+
},
|
|
387
|
+
...options.onError || connectionEvents?.onError ? {
|
|
388
|
+
error: (e) => {
|
|
389
|
+
options.onError?.(e);
|
|
390
|
+
connectionEvents?.onError?.(context, e);
|
|
391
|
+
}
|
|
392
|
+
} : {}
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
}, connections);
|
|
396
|
+
this._rpc = operations ? buildRpc(operations, this) : void 0;
|
|
397
|
+
}
|
|
398
|
+
get rpc() {
|
|
399
|
+
if (!this._rpc) {
|
|
400
|
+
throw new Error("@contello/client: .rpc accessed without operations");
|
|
401
|
+
}
|
|
402
|
+
return this._rpc;
|
|
403
|
+
}
|
|
404
|
+
async init() {
|
|
405
|
+
await this._pool.connect();
|
|
406
|
+
}
|
|
407
|
+
async destroy() {
|
|
408
|
+
await this._pool.disconnect();
|
|
409
|
+
}
|
|
410
|
+
async ping() {
|
|
411
|
+
return ping((query) => firstValueFrom2(this.subscribe(query)));
|
|
412
|
+
}
|
|
413
|
+
subscribe(query, variables) {
|
|
414
|
+
const wsClient = this._pool.get();
|
|
415
|
+
return new Observable((obs) => wsClient.subscribe({ query, variables }, obs)).pipe(
|
|
416
|
+
map2((r) => r.data)
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
download(fileId) {
|
|
420
|
+
return wrap("@contello/client:download", () => downloadFile(this._url, this._token, fileId));
|
|
421
|
+
}
|
|
422
|
+
upload(data, meta, options) {
|
|
423
|
+
return wrap(
|
|
424
|
+
"@contello/client:upload",
|
|
425
|
+
() => upload(this._url, this._project, this._token, data, meta, options)
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
execute(query, variables) {
|
|
429
|
+
return wrap("@contello/client:execute", () => firstValueFrom2(this.subscribe(query, variables)));
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
function createContelloClient(options) {
|
|
433
|
+
return new ContelloClient(options);
|
|
434
|
+
}
|
|
435
|
+
export {
|
|
436
|
+
ContelloClient,
|
|
437
|
+
createContelloClient
|
|
438
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@contello/client",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "GraphQL client for Contello CMS with WebSocket transport, connection pooling, and built-in codegen",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "admin@entwico.com",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/entwico/contello-js",
|
|
11
|
+
"directory": "packages/client"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "tsup",
|
|
15
|
+
"lint": "eslint .",
|
|
16
|
+
"lint:fix": "eslint . --fix",
|
|
17
|
+
"typecheck": "tsc --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"graphql": "^16.13.1",
|
|
21
|
+
"graphql-ws": "^6.0.7"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"rxjs": "^7.0.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"rxjs": "^7.8.2"
|
|
28
|
+
},
|
|
29
|
+
"bin": {
|
|
30
|
+
"contello-client": "./dist/cli.js"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"exports": {
|
|
37
|
+
".": {
|
|
38
|
+
"import": "./dist/index.js",
|
|
39
|
+
"require": "./dist/index.cjs"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"registry": "https://registry.npmjs.org"
|
|
45
|
+
}
|
|
46
|
+
}
|