@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.cjs CHANGED
@@ -135,11 +135,11 @@ async function* asyncKeepalive(factory, signal) {
135
135
  attempt = 0;
136
136
  }
137
137
  attempt = 0;
138
- } catch (err) {
138
+ } catch (error) {
139
139
  if (signal?.aborted) {
140
140
  return;
141
141
  }
142
- void err;
142
+ void error;
143
143
  await exponentialBackoffWithSignal(attempt, signal);
144
144
  attempt++;
145
145
  }
@@ -201,6 +201,32 @@ function decorateMessage(message) {
201
201
 
202
202
  // src/http.ts
203
203
  var import_undici = require("undici");
204
+ var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
205
+ var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
206
+ "content-type",
207
+ "content-length",
208
+ "content-range",
209
+ "content-encoding",
210
+ "accept-ranges",
211
+ "cache-control",
212
+ "etag",
213
+ "last-modified",
214
+ "expires",
215
+ "age"
216
+ ]);
217
+ function assertSafeSegment(segment, kind) {
218
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
219
+ throw new Error(`invalid ${kind}`);
220
+ }
221
+ }
222
+ function assertSafeAssetPath(path, kind) {
223
+ if (path === "") {
224
+ throw new Error(`invalid ${kind}`);
225
+ }
226
+ for (const segment of path.split("/")) {
227
+ assertSafeSegment(segment, kind);
228
+ }
229
+ }
204
230
  function createHttpAgent(options) {
205
231
  return new import_undici.Agent({
206
232
  pipelining: options?.pipelining ?? 10,
@@ -212,6 +238,7 @@ function createHttpAgent(options) {
212
238
  });
213
239
  }
214
240
  async function downloadFile(agent, url, token, fileId) {
241
+ assertSafeSegment(fileId, "file id");
215
242
  const response = await (0, import_undici.request)(`${url}/api/v1/assets/files/${fileId}`, {
216
243
  headers: { token },
217
244
  dispatcher: agent
@@ -230,6 +257,7 @@ async function downloadFile(agent, url, token, fileId) {
230
257
  };
231
258
  }
232
259
  async function proxyHls(agent, url, token, path, signal) {
260
+ assertSafeAssetPath(path, "hls path");
233
261
  const response = await (0, import_undici.request)(`${url}/api/v1/assets/video/hls/${path}`, {
234
262
  headers: { token },
235
263
  dispatcher: agent,
@@ -240,9 +268,12 @@ async function proxyHls(agent, url, token, path, signal) {
240
268
  function buildProxyResult(response, signal) {
241
269
  const headers = new Headers();
242
270
  for (const [key, value] of Object.entries(response.headers)) {
271
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
272
+ continue;
273
+ }
243
274
  if (Array.isArray(value)) {
244
275
  for (const v of value) headers.append(key, v);
245
- } else if (value != null) {
276
+ } else if (value !== null && value !== void 0) {
246
277
  headers.set(key, String(value));
247
278
  }
248
279
  }
@@ -326,42 +357,66 @@ async function ping(execute) {
326
357
  }
327
358
 
328
359
  // src/pool.ts
360
+ var DEFAULT_CONNECT_TIMEOUT = 1e4;
329
361
  var ConnectionPool = class {
330
- constructor(createClient2, poolSize) {
331
- this.createClient = createClient2;
332
- this.poolSize = poolSize;
362
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
363
+ this._createClient = _createClient;
364
+ this._poolSize = _poolSize;
365
+ this._connectTimeout = _connectTimeout;
333
366
  }
334
- clients = [];
335
- currentIndex = 0;
367
+ _clients = [];
368
+ _connected = [];
369
+ _currentIndex = 0;
336
370
  async connect() {
337
- const connected = [];
338
- for (let i = 0; i < this.poolSize; i++) {
339
- const client = this.createClient(`${i + 1}`);
340
- this.clients.push(client);
341
- connected.push(
371
+ const ready = [];
372
+ for (let i = 0; i < this._poolSize; i++) {
373
+ const index = i;
374
+ const client = this._createClient(`${i + 1}`);
375
+ this._clients.push(client);
376
+ this._connected.push(false);
377
+ client.on("connected", () => {
378
+ this._connected[index] = true;
379
+ });
380
+ client.on("closed", () => {
381
+ this._connected[index] = false;
382
+ });
383
+ ready.push(
342
384
  new Promise((resolve) => {
343
- const unsubscribe = client.on("connected", () => {
344
- unsubscribe();
385
+ let settled = false;
386
+ const done = () => {
387
+ if (settled) {
388
+ return;
389
+ }
390
+ settled = true;
391
+ offConnected();
392
+ clearTimeout(timer);
345
393
  resolve();
346
- });
394
+ };
395
+ const offConnected = client.on("connected", done);
396
+ const timer = setTimeout(done, this._connectTimeout);
397
+ timer.unref?.();
347
398
  })
348
399
  );
349
400
  }
350
- await Promise.all(connected);
401
+ await Promise.all(ready);
351
402
  }
352
403
  get() {
353
- if (this.clients.length === 0) {
404
+ if (this._clients.length === 0) {
354
405
  throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
355
406
  }
356
- const client = this.clients[this.currentIndex];
357
- this.currentIndex = (this.currentIndex + 1) % this.poolSize;
358
- if (!client) {
359
- throw new Error("No available WebSocket client");
407
+ for (let i = 0; i < this._clients.length; i++) {
408
+ const index = (this._currentIndex + i) % this._clients.length;
409
+ if (this._connected[index]) {
410
+ this._currentIndex = (index + 1) % this._clients.length;
411
+ return this._clients[index];
412
+ }
360
413
  }
414
+ const client = this._clients[this._currentIndex];
415
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
361
416
  return client;
362
417
  }
363
418
  async disconnect() {
364
- const closed = this.clients.map(
419
+ const closed = this._clients.map(
365
420
  (client) => new Promise((resolve) => {
366
421
  const unsubscribe = client.on("closed", () => {
367
422
  unsubscribe();
@@ -370,7 +425,9 @@ var ConnectionPool = class {
370
425
  client.dispose();
371
426
  })
372
427
  );
373
- this.clients = [];
428
+ this._clients = [];
429
+ this._connected = [];
430
+ this._currentIndex = 0;
374
431
  await Promise.all(closed);
375
432
  }
376
433
  };
@@ -444,123 +501,6 @@ function encodeLocalDate(value) {
444
501
  return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
445
502
  }
446
503
 
447
- // src/transform-response.ts
448
- var FLAT_PREFIX = "_flat_";
449
- var LDT_PREFIX = "_ldt_";
450
- var LD_PREFIX = "_ld_";
451
- var MODEL_SUFFIXES = ["Entity", "Component"];
452
- function decodeValue(value, decoder) {
453
- if (value === null || value === void 0) {
454
- return value;
455
- }
456
- if (Array.isArray(value)) {
457
- return value.map((item) => decodeValue(item, decoder));
458
- }
459
- if (typeof value === "string") {
460
- return decoder(value);
461
- }
462
- return value;
463
- }
464
- function deriveModel(typename) {
465
- for (const suffix of MODEL_SUFFIXES) {
466
- if (typename.endsWith(suffix)) {
467
- const stripped = typename.slice(0, -suffix.length);
468
- return stripped.charAt(0).toLowerCase() + stripped.slice(1);
469
- }
470
- }
471
- return void 0;
472
- }
473
- function transformResponse(data) {
474
- if (data === null || data === void 0 || typeof data !== "object") {
475
- return data;
476
- }
477
- if (Array.isArray(data)) {
478
- for (const item of data) {
479
- transformResponse(item);
480
- }
481
- return data;
482
- }
483
- const obj = data;
484
- const typename = obj["__typename"];
485
- if (typeof typename === "string") {
486
- const model = deriveModel(typename);
487
- if (model) {
488
- obj["__model"] = model;
489
- }
490
- }
491
- const flatKeys = Object.keys(obj).filter((k) => k.startsWith(FLAT_PREFIX));
492
- for (const flatKey of flatKeys) {
493
- const fieldKey = flatKey.slice(FLAT_PREFIX.length);
494
- const flatArray = obj[flatKey];
495
- const refArray = obj[fieldKey];
496
- if (!flatArray || !refArray) {
497
- continue;
498
- }
499
- const flatMap = /* @__PURE__ */ new Map();
500
- for (const component of flatArray) {
501
- if (component._flatId) {
502
- flatMap.set(component._flatId, component);
503
- }
504
- }
505
- obj[fieldKey] = resolveRefs(refArray, flatMap);
506
- delete obj[flatKey];
507
- }
508
- for (const key of Object.keys(obj)) {
509
- if (key.startsWith(LDT_PREFIX)) {
510
- const original = key.slice(LDT_PREFIX.length);
511
- obj[original] = decodeValue(obj[key], decodeLocalDateTime);
512
- delete obj[key];
513
- } else if (key.startsWith(LD_PREFIX)) {
514
- const original = key.slice(LD_PREFIX.length);
515
- obj[original] = decodeValue(obj[key], decodeLocalDate);
516
- delete obj[key];
517
- }
518
- }
519
- for (const key of Object.keys(obj)) {
520
- const value = obj[key];
521
- if (value && typeof value === "object") {
522
- if (Array.isArray(value)) {
523
- for (const item of value) {
524
- if (item && typeof item === "object") {
525
- transformResponse(item);
526
- }
527
- }
528
- } else {
529
- transformResponse(value);
530
- }
531
- }
532
- }
533
- return data;
534
- }
535
- function resolveRefs(refs, flatMap) {
536
- return refs.flatMap((ref) => {
537
- if (!ref._flatId) return [];
538
- const component = flatMap.get(ref._flatId);
539
- if (!component) return [];
540
- resolveNestedRefs(component, flatMap);
541
- transformResponse(component);
542
- return [component];
543
- });
544
- }
545
- function resolveNestedRefs(value, flatMap) {
546
- if (!value || typeof value !== "object") return;
547
- if (Array.isArray(value)) {
548
- for (const item of value) {
549
- resolveNestedRefs(item, flatMap);
550
- }
551
- return;
552
- }
553
- const obj = value;
554
- for (const key of Object.keys(obj)) {
555
- const inner = obj[key];
556
- if (Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
557
- obj[key] = resolveRefs(inner, flatMap);
558
- } else if (inner && typeof inner === "object") {
559
- resolveNestedRefs(inner, flatMap);
560
- }
561
- }
562
- }
563
-
564
504
  // src/transform-variables.ts
565
505
  function transformVariables(value) {
566
506
  if (value === null || value === void 0) {
@@ -590,14 +530,7 @@ function transformVariables(value) {
590
530
  function buildRpc(operations, subscribe) {
591
531
  const rpc = {};
592
532
  for (const [name, def] of Object.entries(operations)) {
593
- if (def.kind === "subscription") {
594
- rpc[name] = (variables) => mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse);
595
- } else {
596
- rpc[name] = (variables) => wrap(
597
- `rpc:${name}`,
598
- () => firstAsync(mapAsync(subscribe(def.document, transformVariables(variables)), transformResponse))
599
- );
600
- }
533
+ rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
601
534
  }
602
535
  return rpc;
603
536
  }
@@ -607,16 +540,21 @@ var cache = /* @__PURE__ */ new WeakMap();
607
540
  function createSelection(source) {
608
541
  const spread = `{ ...${source.fragment} }`;
609
542
  switch (source.__cardinality) {
610
- case "singleton":
543
+ case "singleton": {
611
544
  return `subscription { source: ${source.subscription} ${spread} }`;
612
- case "entity":
545
+ }
546
+ case "entity": {
613
547
  return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
614
- case "route":
548
+ }
549
+ case "route": {
615
550
  return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
616
- case "asset":
551
+ }
552
+ case "asset": {
617
553
  return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
618
- case "i18nMessage":
554
+ }
555
+ case "i18nMessage": {
619
556
  return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
557
+ }
620
558
  }
621
559
  }
622
560
  function createSourceSubscription(source) {
@@ -637,54 +575,55 @@ function createSources(sources, subscribe) {
637
575
  const def = source;
638
576
  const doc = createSourceSubscription(def);
639
577
  switch (def.__cardinality) {
640
- case "singleton":
578
+ case "singleton": {
641
579
  out[name] = {
642
- fetch: () => wrap(
643
- `source:${name}`,
644
- () => firstAsync(mapAsync(subscribe(doc), (r) => transformResponse(r).source))
645
- )
580
+ fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
646
581
  };
647
582
  break;
648
- case "entity":
583
+ }
584
+ case "entity": {
649
585
  out[name] = {
650
586
  fetch: (vars) => wrap(
651
587
  `source:${name}`,
652
588
  () => collectAsync(
653
589
  mapAsync(
654
590
  subscribe(doc, transformVariables({ ids: vars?.ids })),
655
- (r) => transformResponse(r).source
591
+ (r) => r.source
656
592
  )
657
593
  )
658
594
  )
659
595
  };
660
596
  break;
661
- case "route":
597
+ }
598
+ case "route": {
662
599
  out[name] = {
663
600
  fetch: (vars) => wrap(
664
601
  `source:${name}`,
665
602
  () => collectAsync(
666
603
  mapAsync(
667
604
  subscribe(doc, transformVariables({ ids: vars?.ids, paths: vars?.paths })),
668
- (r) => transformResponse(r).source
605
+ (r) => r.source
669
606
  )
670
607
  )
671
608
  )
672
609
  };
673
610
  break;
674
- case "asset":
611
+ }
612
+ case "asset": {
675
613
  out[name] = {
676
614
  fetch: (vars) => wrap(
677
615
  `source:${name}`,
678
616
  () => collectAsync(
679
617
  mapAsync(
680
618
  subscribe(doc, transformVariables({ ids: vars?.ids })),
681
- (r) => transformResponse(r).source
619
+ (r) => r.source
682
620
  )
683
621
  )
684
622
  )
685
623
  };
686
624
  break;
687
- case "i18nMessage":
625
+ }
626
+ case "i18nMessage": {
688
627
  out[name] = {
689
628
  fetch: (vars) => wrap(
690
629
  `source:${name}`,
@@ -694,17 +633,122 @@ function createSources(sources, subscribe) {
694
633
  doc,
695
634
  transformVariables({ collection: vars.collection, ids: vars.ids })
696
635
  ),
697
- (r) => transformResponse(r).source
636
+ (r) => r.source
698
637
  )
699
638
  )
700
639
  )
701
640
  };
702
641
  break;
642
+ }
703
643
  }
704
644
  }
705
645
  return out;
706
646
  }
707
647
 
648
+ // src/transform-response.ts
649
+ var FLAT_PREFIX = "_flat_";
650
+ var LDT_PREFIX = "_ldt_";
651
+ var LD_PREFIX = "_ld_";
652
+ var MODEL_SUFFIXES = ["Entity", "Component"];
653
+ function decodeValue(value, decoder) {
654
+ if (value === null || value === void 0) {
655
+ return value;
656
+ }
657
+ if (Array.isArray(value)) {
658
+ return value.map((item) => decodeValue(item, decoder));
659
+ }
660
+ if (typeof value === "string") {
661
+ return decoder(value);
662
+ }
663
+ return value;
664
+ }
665
+ function deriveModel(typename) {
666
+ for (const suffix of MODEL_SUFFIXES) {
667
+ if (typename.endsWith(suffix)) {
668
+ const stripped = typename.slice(0, -suffix.length);
669
+ return stripped.charAt(0).toLowerCase() + stripped.slice(1);
670
+ }
671
+ }
672
+ return void 0;
673
+ }
674
+ function transformResponse(data) {
675
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
676
+ return data;
677
+ }
678
+ function transformNode(value, flatMap, seen) {
679
+ if (!value || typeof value !== "object") {
680
+ return;
681
+ }
682
+ if (seen.has(value)) {
683
+ return;
684
+ }
685
+ seen.add(value);
686
+ if (Array.isArray(value)) {
687
+ for (const item of value) {
688
+ transformNode(item, flatMap, seen);
689
+ }
690
+ return;
691
+ }
692
+ const obj = value;
693
+ const typename = obj["__typename"];
694
+ if (typeof typename === "string") {
695
+ const model = deriveModel(typename);
696
+ if (model) {
697
+ obj["__model"] = model;
698
+ }
699
+ }
700
+ let ownMap;
701
+ for (const key of Object.keys(obj)) {
702
+ if (!key.startsWith(FLAT_PREFIX)) {
703
+ continue;
704
+ }
705
+ const flatArray = obj[key];
706
+ delete obj[key];
707
+ if (!flatArray) {
708
+ continue;
709
+ }
710
+ if (!ownMap) {
711
+ ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
712
+ }
713
+ for (const component of flatArray) {
714
+ if (component._flatId) {
715
+ ownMap.set(component._flatId, component);
716
+ }
717
+ }
718
+ }
719
+ const resolveMap = ownMap ?? flatMap;
720
+ for (const key of Object.keys(obj)) {
721
+ if (key.startsWith(LDT_PREFIX)) {
722
+ obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
723
+ delete obj[key];
724
+ continue;
725
+ }
726
+ if (key.startsWith(LD_PREFIX)) {
727
+ obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
728
+ delete obj[key];
729
+ continue;
730
+ }
731
+ const inner = obj[key];
732
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
733
+ obj[key] = resolveRefs(inner, resolveMap);
734
+ }
735
+ transformNode(obj[key], resolveMap, seen);
736
+ }
737
+ }
738
+ function resolveRefs(refs, flatMap) {
739
+ const resolved = [];
740
+ for (const ref of refs) {
741
+ if (!ref._flatId) {
742
+ continue;
743
+ }
744
+ const component = flatMap.get(ref._flatId);
745
+ if (component) {
746
+ resolved.push(component);
747
+ }
748
+ }
749
+ return resolved;
750
+ }
751
+
708
752
  // src/upload.ts
709
753
  var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
710
754
  function isUint8Array(data) {
@@ -736,24 +780,42 @@ function upload(url, project, token, data, meta, options) {
736
780
  }
737
781
  ws.send(JSON.stringify({ type: "done" }));
738
782
  }
783
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
784
+ function waitForBufferedDrain() {
785
+ return new Promise((resolveDrain, rejectDrain) => {
786
+ const check = () => {
787
+ if (options?.abort?.aborted) {
788
+ rejectDrain(new Error("upload aborted"));
789
+ return;
790
+ }
791
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
792
+ resolveDrain();
793
+ return;
794
+ }
795
+ setTimeout(check, 50);
796
+ };
797
+ check();
798
+ });
799
+ }
739
800
  async function sendStream(stream) {
740
801
  const reader = stream.getReader();
741
802
  try {
742
803
  while (true) {
743
804
  const { done: streamDone, value } = await reader.read();
744
805
  if (streamDone) break;
806
+ await waitForBufferedDrain();
745
807
  ws.send(value);
746
808
  }
747
809
  ws.send(JSON.stringify({ type: "done" }));
748
- } catch (err) {
749
- reject(err);
810
+ } catch (error) {
811
+ reject(error);
750
812
  ws.close();
751
813
  }
752
814
  }
753
815
  ws.addEventListener("open", () => {
754
816
  const initFrame = {
755
817
  type: "init",
756
- metadata: { ...meta, ...size !== void 0 ? { size } : {}, projectRef: project },
818
+ metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
757
819
  token
758
820
  };
759
821
  ws.send(JSON.stringify(initFrame));
@@ -912,7 +974,7 @@ var ContelloClient = class {
912
974
  { query, variables },
913
975
  {
914
976
  next(msg) {
915
- const value = msg.data;
977
+ const value = transformResponse(msg.data);
916
978
  if (value === void 0 || value === null) {
917
979
  return;
918
980
  }