@contello/client 2.2.0 → 2.2.2

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/index.js CHANGED
@@ -89,11 +89,11 @@ async function* asyncKeepalive(factory, signal) {
89
89
  attempt = 0;
90
90
  }
91
91
  attempt = 0;
92
- } catch (err) {
92
+ } catch (error) {
93
93
  if (signal?.aborted) {
94
94
  return;
95
95
  }
96
- void err;
96
+ void error;
97
97
  await exponentialBackoffWithSignal(attempt, signal);
98
98
  attempt++;
99
99
  }
@@ -155,6 +155,32 @@ function decorateMessage(message) {
155
155
 
156
156
  // src/http.ts
157
157
  import { Agent, request as undiciRequest } from "undici";
158
+ var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
159
+ var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
160
+ "content-type",
161
+ "content-length",
162
+ "content-range",
163
+ "content-encoding",
164
+ "accept-ranges",
165
+ "cache-control",
166
+ "etag",
167
+ "last-modified",
168
+ "expires",
169
+ "age"
170
+ ]);
171
+ function assertSafeSegment(segment, kind) {
172
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
173
+ throw new Error(`invalid ${kind}`);
174
+ }
175
+ }
176
+ function assertSafeAssetPath(path, kind) {
177
+ if (path === "") {
178
+ throw new Error(`invalid ${kind}`);
179
+ }
180
+ for (const segment of path.split("/")) {
181
+ assertSafeSegment(segment, kind);
182
+ }
183
+ }
158
184
  function createHttpAgent(options) {
159
185
  return new Agent({
160
186
  pipelining: options?.pipelining ?? 10,
@@ -166,6 +192,7 @@ function createHttpAgent(options) {
166
192
  });
167
193
  }
168
194
  async function downloadFile(agent, url, token, fileId) {
195
+ assertSafeSegment(fileId, "file id");
169
196
  const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {
170
197
  headers: { token },
171
198
  dispatcher: agent
@@ -184,6 +211,7 @@ async function downloadFile(agent, url, token, fileId) {
184
211
  };
185
212
  }
186
213
  async function proxyHls(agent, url, token, path, signal) {
214
+ assertSafeAssetPath(path, "hls path");
187
215
  const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {
188
216
  headers: { token },
189
217
  dispatcher: agent,
@@ -194,9 +222,12 @@ async function proxyHls(agent, url, token, path, signal) {
194
222
  function buildProxyResult(response, signal) {
195
223
  const headers = new Headers();
196
224
  for (const [key, value] of Object.entries(response.headers)) {
225
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
226
+ continue;
227
+ }
197
228
  if (Array.isArray(value)) {
198
229
  for (const v of value) headers.append(key, v);
199
- } else if (value != null) {
230
+ } else if (value !== null && value !== void 0) {
200
231
  headers.set(key, String(value));
201
232
  }
202
233
  }
@@ -280,42 +311,66 @@ async function ping(execute) {
280
311
  }
281
312
 
282
313
  // src/pool.ts
314
+ var DEFAULT_CONNECT_TIMEOUT = 1e4;
283
315
  var ConnectionPool = class {
284
- constructor(createClient2, poolSize) {
285
- this.createClient = createClient2;
286
- this.poolSize = poolSize;
316
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
317
+ this._createClient = _createClient;
318
+ this._poolSize = _poolSize;
319
+ this._connectTimeout = _connectTimeout;
287
320
  }
288
- clients = [];
289
- currentIndex = 0;
321
+ _clients = [];
322
+ _connected = [];
323
+ _currentIndex = 0;
290
324
  async connect() {
291
- const connected = [];
292
- for (let i = 0; i < this.poolSize; i++) {
293
- const client = this.createClient(`${i + 1}`);
294
- this.clients.push(client);
295
- connected.push(
325
+ const ready = [];
326
+ for (let i = 0; i < this._poolSize; i++) {
327
+ const index = i;
328
+ const client = this._createClient(`${i + 1}`);
329
+ this._clients.push(client);
330
+ this._connected.push(false);
331
+ client.on("connected", () => {
332
+ this._connected[index] = true;
333
+ });
334
+ client.on("closed", () => {
335
+ this._connected[index] = false;
336
+ });
337
+ ready.push(
296
338
  new Promise((resolve) => {
297
- const unsubscribe = client.on("connected", () => {
298
- unsubscribe();
339
+ let settled = false;
340
+ const done = () => {
341
+ if (settled) {
342
+ return;
343
+ }
344
+ settled = true;
345
+ offConnected();
346
+ clearTimeout(timer);
299
347
  resolve();
300
- });
348
+ };
349
+ const offConnected = client.on("connected", done);
350
+ const timer = setTimeout(done, this._connectTimeout);
351
+ timer.unref?.();
301
352
  })
302
353
  );
303
354
  }
304
- await Promise.all(connected);
355
+ await Promise.all(ready);
305
356
  }
306
357
  get() {
307
- if (this.clients.length === 0) {
358
+ if (this._clients.length === 0) {
308
359
  throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
309
360
  }
310
- const client = this.clients[this.currentIndex];
311
- this.currentIndex = (this.currentIndex + 1) % this.poolSize;
312
- if (!client) {
313
- throw new Error("No available WebSocket client");
361
+ for (let i = 0; i < this._clients.length; i++) {
362
+ const index = (this._currentIndex + i) % this._clients.length;
363
+ if (this._connected[index]) {
364
+ this._currentIndex = (index + 1) % this._clients.length;
365
+ return this._clients[index];
366
+ }
314
367
  }
368
+ const client = this._clients[this._currentIndex];
369
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
315
370
  return client;
316
371
  }
317
372
  async disconnect() {
318
- const closed = this.clients.map(
373
+ const closed = this._clients.map(
319
374
  (client) => new Promise((resolve) => {
320
375
  const unsubscribe = client.on("closed", () => {
321
376
  unsubscribe();
@@ -324,7 +379,9 @@ var ConnectionPool = class {
324
379
  client.dispose();
325
380
  })
326
381
  );
327
- this.clients = [];
382
+ this._clients = [];
383
+ this._connected = [];
384
+ this._currentIndex = 0;
328
385
  await Promise.all(closed);
329
386
  }
330
387
  };
@@ -398,123 +455,6 @@ function encodeLocalDate(value) {
398
455
  return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
399
456
  }
400
457
 
401
- // src/transform-response.ts
402
- var FLAT_PREFIX = "_flat_";
403
- var LDT_PREFIX = "_ldt_";
404
- var LD_PREFIX = "_ld_";
405
- var MODEL_SUFFIXES = ["Entity", "Component"];
406
- function decodeValue(value, decoder) {
407
- if (value === null || value === void 0) {
408
- return value;
409
- }
410
- if (Array.isArray(value)) {
411
- return value.map((item) => decodeValue(item, decoder));
412
- }
413
- if (typeof value === "string") {
414
- return decoder(value);
415
- }
416
- return value;
417
- }
418
- function deriveModel(typename) {
419
- for (const suffix of MODEL_SUFFIXES) {
420
- if (typename.endsWith(suffix)) {
421
- const stripped = typename.slice(0, -suffix.length);
422
- return stripped.charAt(0).toLowerCase() + stripped.slice(1);
423
- }
424
- }
425
- return void 0;
426
- }
427
- function transformResponse(data) {
428
- if (data === null || data === void 0 || typeof data !== "object") {
429
- return data;
430
- }
431
- if (Array.isArray(data)) {
432
- for (const item of data) {
433
- transformResponse(item);
434
- }
435
- return data;
436
- }
437
- const obj = data;
438
- const typename = obj["__typename"];
439
- if (typeof typename === "string") {
440
- const model = deriveModel(typename);
441
- if (model) {
442
- obj["__model"] = model;
443
- }
444
- }
445
- const flatKeys = Object.keys(obj).filter((k) => k.startsWith(FLAT_PREFIX));
446
- for (const flatKey of flatKeys) {
447
- const fieldKey = flatKey.slice(FLAT_PREFIX.length);
448
- const flatArray = obj[flatKey];
449
- const refArray = obj[fieldKey];
450
- if (!flatArray || !refArray) {
451
- continue;
452
- }
453
- const flatMap = /* @__PURE__ */ new Map();
454
- for (const component of flatArray) {
455
- if (component._flatId) {
456
- flatMap.set(component._flatId, component);
457
- }
458
- }
459
- obj[fieldKey] = resolveRefs(refArray, flatMap);
460
- delete obj[flatKey];
461
- }
462
- for (const key of Object.keys(obj)) {
463
- if (key.startsWith(LDT_PREFIX)) {
464
- const original = key.slice(LDT_PREFIX.length);
465
- obj[original] = decodeValue(obj[key], decodeLocalDateTime);
466
- delete obj[key];
467
- } else if (key.startsWith(LD_PREFIX)) {
468
- const original = key.slice(LD_PREFIX.length);
469
- obj[original] = decodeValue(obj[key], decodeLocalDate);
470
- delete obj[key];
471
- }
472
- }
473
- for (const key of Object.keys(obj)) {
474
- const value = obj[key];
475
- if (value && typeof value === "object") {
476
- if (Array.isArray(value)) {
477
- for (const item of value) {
478
- if (item && typeof item === "object") {
479
- transformResponse(item);
480
- }
481
- }
482
- } else {
483
- transformResponse(value);
484
- }
485
- }
486
- }
487
- return data;
488
- }
489
- function resolveRefs(refs, flatMap) {
490
- return refs.flatMap((ref) => {
491
- if (!ref._flatId) return [];
492
- const component = flatMap.get(ref._flatId);
493
- if (!component) return [];
494
- resolveNestedRefs(component, flatMap);
495
- transformResponse(component);
496
- return [component];
497
- });
498
- }
499
- function resolveNestedRefs(value, flatMap) {
500
- if (!value || typeof value !== "object") return;
501
- if (Array.isArray(value)) {
502
- for (const item of value) {
503
- resolveNestedRefs(item, flatMap);
504
- }
505
- return;
506
- }
507
- const obj = value;
508
- for (const key of Object.keys(obj)) {
509
- const inner = obj[key];
510
- if (Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
511
- obj[key] = resolveRefs(inner, flatMap);
512
- } else if (inner && typeof inner === "object") {
513
- resolveNestedRefs(inner, flatMap);
514
- }
515
- }
516
- }
517
-
518
458
  // src/transform-variables.ts
519
459
  function transformVariables(value) {
520
460
  if (value === null || value === void 0) {
@@ -544,14 +484,7 @@ function transformVariables(value) {
544
484
  function buildRpc(operations, subscribe) {
545
485
  const rpc = {};
546
486
  for (const [name, def] of Object.entries(operations)) {
547
- if (def.kind === "subscription") {
548
- rpc[name] = (variables) => mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse);
549
- } else {
550
- rpc[name] = (variables) => wrap(
551
- `rpc:${name}`,
552
- () => firstAsync(mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse))
553
- );
554
- }
487
+ rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
555
488
  }
556
489
  return rpc;
557
490
  }
@@ -561,16 +494,21 @@ var cache = /* @__PURE__ */ new WeakMap();
561
494
  function createSelection(source) {
562
495
  const spread = `{ ...${source.fragment} }`;
563
496
  switch (source.__cardinality) {
564
- case "singleton":
497
+ case "singleton": {
565
498
  return `subscription { source: ${source.subscription} ${spread} }`;
566
- case "entity":
499
+ }
500
+ case "entity": {
567
501
  return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
568
- case "route":
502
+ }
503
+ case "route": {
569
504
  return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
570
- case "asset":
505
+ }
506
+ case "asset": {
571
507
  return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
572
- case "i18nMessage":
508
+ }
509
+ case "i18nMessage": {
573
510
  return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
511
+ }
574
512
  }
575
513
  }
576
514
  function createSourceSubscription(source) {
@@ -591,54 +529,55 @@ function createSources(sources, subscribe) {
591
529
  const def = source;
592
530
  const doc = createSourceSubscription(def);
593
531
  switch (def.__cardinality) {
594
- case "singleton":
532
+ case "singleton": {
595
533
  out[name] = {
596
- fetch: () => wrap(
597
- `source:${name}`,
598
- () => firstAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
599
- )
534
+ fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
600
535
  };
601
536
  break;
602
- case "entity":
537
+ }
538
+ case "entity": {
603
539
  out[name] = {
604
540
  fetch: (vars) => wrap(
605
541
  `source:${name}`,
606
542
  () => collectAsync(
607
543
  mapAsync(
608
544
  subscribe(doc, transformVariables({ ids: vars?.ids })),
609
- (r) => transformResponse(r).source
545
+ (r) => r.source
610
546
  )
611
547
  )
612
548
  )
613
549
  };
614
550
  break;
615
- case "route":
551
+ }
552
+ case "route": {
616
553
  out[name] = {
617
554
  fetch: (vars) => wrap(
618
555
  `source:${name}`,
619
556
  () => collectAsync(
620
557
  mapAsync(
621
558
  subscribe(doc, transformVariables({ ids: vars?.ids, paths: vars?.paths })),
622
- (r) => transformResponse(r).source
559
+ (r) => r.source
623
560
  )
624
561
  )
625
562
  )
626
563
  };
627
564
  break;
628
- case "asset":
565
+ }
566
+ case "asset": {
629
567
  out[name] = {
630
568
  fetch: (vars) => wrap(
631
569
  `source:${name}`,
632
570
  () => collectAsync(
633
571
  mapAsync(
634
572
  subscribe(doc, transformVariables({ ids: vars?.ids })),
635
- (r) => transformResponse(r).source
573
+ (r) => r.source
636
574
  )
637
575
  )
638
576
  )
639
577
  };
640
578
  break;
641
- case "i18nMessage":
579
+ }
580
+ case "i18nMessage": {
642
581
  out[name] = {
643
582
  fetch: (vars) => wrap(
644
583
  `source:${name}`,
@@ -648,17 +587,122 @@ function createSources(sources, subscribe) {
648
587
  doc,
649
588
  transformVariables({ collection: vars.collection, ids: vars.ids })
650
589
  ),
651
- (r) => transformResponse(r).source
590
+ (r) => r.source
652
591
  )
653
592
  )
654
593
  )
655
594
  };
656
595
  break;
596
+ }
657
597
  }
658
598
  }
659
599
  return out;
660
600
  }
661
601
 
602
+ // src/transform-response.ts
603
+ var FLAT_PREFIX = "_flat_";
604
+ var LDT_PREFIX = "_ldt_";
605
+ var LD_PREFIX = "_ld_";
606
+ var MODEL_SUFFIXES = ["Entity", "Component"];
607
+ function decodeValue(value, decoder) {
608
+ if (value === null || value === void 0) {
609
+ return value;
610
+ }
611
+ if (Array.isArray(value)) {
612
+ return value.map((item) => decodeValue(item, decoder));
613
+ }
614
+ if (typeof value === "string") {
615
+ return decoder(value);
616
+ }
617
+ return value;
618
+ }
619
+ function deriveModel(typename) {
620
+ for (const suffix of MODEL_SUFFIXES) {
621
+ if (typename.endsWith(suffix)) {
622
+ const stripped = typename.slice(0, -suffix.length);
623
+ return stripped.charAt(0).toLowerCase() + stripped.slice(1);
624
+ }
625
+ }
626
+ return void 0;
627
+ }
628
+ function transformResponse(data) {
629
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
630
+ return data;
631
+ }
632
+ function transformNode(value, flatMap, seen) {
633
+ if (!value || typeof value !== "object") {
634
+ return;
635
+ }
636
+ if (seen.has(value)) {
637
+ return;
638
+ }
639
+ seen.add(value);
640
+ if (Array.isArray(value)) {
641
+ for (const item of value) {
642
+ transformNode(item, flatMap, seen);
643
+ }
644
+ return;
645
+ }
646
+ const obj = value;
647
+ const typename = obj["__typename"];
648
+ if (typeof typename === "string") {
649
+ const model = deriveModel(typename);
650
+ if (model) {
651
+ obj["__model"] = model;
652
+ }
653
+ }
654
+ let ownMap;
655
+ for (const key of Object.keys(obj)) {
656
+ if (!key.startsWith(FLAT_PREFIX)) {
657
+ continue;
658
+ }
659
+ const flatArray = obj[key];
660
+ delete obj[key];
661
+ if (!flatArray) {
662
+ continue;
663
+ }
664
+ if (!ownMap) {
665
+ ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
666
+ }
667
+ for (const component of flatArray) {
668
+ if (component._flatId) {
669
+ ownMap.set(component._flatId, component);
670
+ }
671
+ }
672
+ }
673
+ const resolveMap = ownMap ?? flatMap;
674
+ for (const key of Object.keys(obj)) {
675
+ if (key.startsWith(LDT_PREFIX)) {
676
+ obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
677
+ delete obj[key];
678
+ continue;
679
+ }
680
+ if (key.startsWith(LD_PREFIX)) {
681
+ obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
682
+ delete obj[key];
683
+ continue;
684
+ }
685
+ const inner = obj[key];
686
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
687
+ obj[key] = resolveRefs(inner, resolveMap);
688
+ }
689
+ transformNode(obj[key], resolveMap, seen);
690
+ }
691
+ }
692
+ function resolveRefs(refs, flatMap) {
693
+ const resolved = [];
694
+ for (const ref of refs) {
695
+ if (!ref._flatId) {
696
+ continue;
697
+ }
698
+ const component = flatMap.get(ref._flatId);
699
+ if (component) {
700
+ resolved.push(component);
701
+ }
702
+ }
703
+ return resolved;
704
+ }
705
+
662
706
  // src/upload.ts
663
707
  var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
664
708
  function isUint8Array(data) {
@@ -690,24 +734,42 @@ function upload(url, project, token, data, meta, options) {
690
734
  }
691
735
  ws.send(JSON.stringify({ type: "done" }));
692
736
  }
737
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
738
+ function waitForBufferedDrain() {
739
+ return new Promise((resolveDrain, rejectDrain) => {
740
+ const check = () => {
741
+ if (options?.abort?.aborted) {
742
+ rejectDrain(new Error("upload aborted"));
743
+ return;
744
+ }
745
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
746
+ resolveDrain();
747
+ return;
748
+ }
749
+ setTimeout(check, 50);
750
+ };
751
+ check();
752
+ });
753
+ }
693
754
  async function sendStream(stream) {
694
755
  const reader = stream.getReader();
695
756
  try {
696
757
  while (true) {
697
758
  const { done: streamDone, value } = await reader.read();
698
759
  if (streamDone) break;
760
+ await waitForBufferedDrain();
699
761
  ws.send(value);
700
762
  }
701
763
  ws.send(JSON.stringify({ type: "done" }));
702
- } catch (err) {
703
- reject(err);
764
+ } catch (error) {
765
+ reject(error);
704
766
  ws.close();
705
767
  }
706
768
  }
707
769
  ws.addEventListener("open", () => {
708
770
  const initFrame = {
709
771
  type: "init",
710
- metadata: { ...meta, ...size !== void 0 ? { size } : {}, projectRef: project },
772
+ metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
711
773
  token
712
774
  };
713
775
  ws.send(JSON.stringify(initFrame));
@@ -866,7 +928,7 @@ var ContelloClient = class {
866
928
  { query, variables },
867
929
  {
868
930
  next(msg) {
869
- const value = msg.data;
931
+ const value = transformResponse(msg.data);
870
932
  if (value === void 0 || value === null) {
871
933
  return;
872
934
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/client",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
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",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "scripts": {
36
36
  "build": "tsup",
37
- "lint": "eslint .",
37
+ "lint": "eslint . --cache",
38
38
  "lint:fix": "eslint . --fix",
39
39
  "typecheck": "tsc --noEmit"
40
40
  }