@contello/client 3.4.1 → 3.5.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/index.cjs CHANGED
@@ -1,10 +1,137 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
2
23
  let _contello_opentelemetry = require("@contello/opentelemetry");
3
24
  let _entwico_dash_async = require("@entwico/dash/async");
4
25
  let graphql_ws = require("graphql-ws");
26
+ let ws = require("ws");
27
+ ws = __toESM(ws, 1);
5
28
  let undici = require("undici");
6
29
  let node_crypto = require("node:crypto");
7
- //#region src/http.ts
30
+ // src/reply-watchdog.ts
31
+ const REPLY_TIMEOUT = 1e4;
32
+ /**
33
+ * Gives up a connection whose server stopped answering: a new one that is not acknowledged, or an
34
+ * established one that sends no pong to a ping. A connection that died without a close frame looks
35
+ * open forever, and every operation on it waits.
36
+ *
37
+ * `terminate` has to drop the connection without waiting for it (graphql-ws `client.terminate()`):
38
+ * closing a socket whose peer is gone waits for that same peer.
39
+ */
40
+ function createReplyWatchdog(terminate, timeout = REPLY_TIMEOUT) {
41
+ let timer;
42
+ function disarm() {
43
+ clearTimeout(timer);
44
+ timer = void 0;
45
+ }
46
+ function arm() {
47
+ disarm();
48
+ timer = setTimeout(terminate, timeout);
49
+ timer.unref?.();
50
+ }
51
+ return {
52
+ connecting: arm,
53
+ connected: disarm,
54
+ ping(received) {
55
+ if (!received) arm();
56
+ },
57
+ pong(received) {
58
+ if (received) disarm();
59
+ },
60
+ closed: disarm
61
+ };
62
+ }
63
+ // src/websocket.ts
64
+ const CLOSE_CODE_TERMINATED = 4499;
65
+ /**
66
+ * The socket class graphql-ws connects with. Node's own WebSocket cannot be forced shut: closed
67
+ * against a peer that stopped answering it stays in `CLOSING` and keeps its file descriptor for as
68
+ * long as the peer stays silent, one more with every reconnect. This one is destroyed when it was
69
+ * given up, and after `replyTimeout` when a handshake, opening or closing, gets no answer.
70
+ */
71
+ function createWebSocketClass(replyTimeout) {
72
+ const options = {
73
+ handshakeTimeout: replyTimeout,
74
+ closeTimeout: replyTimeout
75
+ };
76
+ return class ContelloWebSocket extends ws.default {
77
+ constructor(address, protocols) {
78
+ super(address, protocols, options);
79
+ }
80
+ close(code, data) {
81
+ if (code !== CLOSE_CODE_TERMINATED) {
82
+ super.close(code, data);
83
+ return;
84
+ }
85
+ this.on("error", () => {});
86
+ this.terminate();
87
+ }
88
+ };
89
+ }
90
+ // src/connection.ts
91
+ const KEEP_ALIVE_INTERVAL = 3e4;
92
+ /**
93
+ * One websocket to Contello that stays up: it connects right away, reconnects forever, and gives up
94
+ * a socket whose server stopped answering, so operations move to a new one.
95
+ */
96
+ function createConnection(options) {
97
+ const { onError, onFatalError } = options;
98
+ const replyTimeout = options.replyTimeout ?? 1e4;
99
+ const watchdog = createReplyWatchdog(() => client.terminate(), replyTimeout);
100
+ const client = (0, graphql_ws.createClient)({
101
+ url: options.url,
102
+ webSocketImpl: createWebSocketClass(replyTimeout),
103
+ connectionParams: { token: options.token },
104
+ lazy: false,
105
+ keepAlive: options.keepAlive ?? KEEP_ALIVE_INTERVAL,
106
+ retryAttempts: Infinity,
107
+ retryWait: options.retryWait ?? _entwico_dash_async.exponentialBackoff,
108
+ shouldRetry: () => true,
109
+ jsonMessageReplacer: (key, value) => {
110
+ if (!key) return (0, _contello_opentelemetry.injectTraceContext)(value);
111
+ return value;
112
+ },
113
+ ...onFatalError && { onNonLazyError: onFatalError },
114
+ on: {
115
+ connecting: () => {
116
+ watchdog.connecting();
117
+ options.onConnecting?.();
118
+ },
119
+ connected: () => {
120
+ watchdog.connected();
121
+ options.onConnected?.();
122
+ },
123
+ ping: (received) => watchdog.ping(received),
124
+ pong: (received) => watchdog.pong(received),
125
+ closed: () => {
126
+ watchdog.closed();
127
+ options.onClosed?.();
128
+ },
129
+ ...onError && { error: onError }
130
+ }
131
+ });
132
+ return client;
133
+ }
134
+ // src/http.ts
8
135
  const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
9
136
  const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
10
137
  "content-type",
@@ -159,8 +286,7 @@ function toWebStream(body, signal) {
159
286
  }
160
287
  });
161
288
  }
162
- //#endregion
163
- //#region src/introspection.ts
289
+ // src/introspection.ts
164
290
  const INTROSPECT_QUERY = `query ContelloIntrospectToken($token: String!) {
165
291
  contelloIntrospectToken(token: $token) {
166
292
  active audience expiresAt user { id username firstName lastName email } permissions { resourceType scope actions }
@@ -220,15 +346,13 @@ function createTokenIntrospector(introspect, options) {
220
346
  return running;
221
347
  } };
222
348
  }
223
- //#endregion
224
- //#region src/ping.ts
349
+ // src/ping.ts
225
350
  const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
226
351
  async function ping(execute) {
227
352
  const data = await execute(PING_QUERY);
228
353
  if (data.contelloPing.response !== "pong") throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
229
354
  }
230
- //#endregion
231
- //#region src/pool.ts
355
+ // src/pool.ts
232
356
  const DEFAULT_CONNECT_TIMEOUT = 1e4;
233
357
  var ConnectionPool = class {
234
358
  _createClient;
@@ -285,12 +409,13 @@ var ConnectionPool = class {
285
409
  return client;
286
410
  }
287
411
  async disconnect() {
288
- const closed = this._clients.map((client) => new Promise((resolve) => {
412
+ const closed = this._clients.map((client, index) => new Promise((resolve) => {
289
413
  const unsubscribe = client.on("closed", () => {
290
414
  unsubscribe();
291
415
  resolve();
292
416
  });
293
- client.dispose();
417
+ Promise.resolve(client.dispose()).catch(() => {});
418
+ if (this._connected[index] !== true) client.terminate();
294
419
  }));
295
420
  this._clients = [];
296
421
  this._connected = [];
@@ -298,11 +423,9 @@ var ConnectionPool = class {
298
423
  await Promise.all(closed);
299
424
  }
300
425
  };
301
- //#endregion
302
- //#region src/telemetry.ts
426
+ // src/telemetry.ts
303
427
  const { wrap } = (0, _contello_opentelemetry.createOperationTelemetry)("@contello/client");
304
- //#endregion
305
- //#region src/scalars.ts
428
+ // src/scalars.ts
306
429
  const LOCAL_DATE_TIME_KEYS = [
307
430
  "year",
308
431
  "month",
@@ -366,8 +489,7 @@ function encodeLocalDateTime(value) {
366
489
  function encodeLocalDate(value) {
367
490
  return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
368
491
  }
369
- //#endregion
370
- //#region src/transform-variables.ts
492
+ // src/transform-variables.ts
371
493
  /**
372
494
  * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.
373
495
  * detection is by shape — generated input types use the struct types, so consumers
@@ -385,8 +507,7 @@ function transformVariables(value) {
385
507
  for (const [key, val] of Object.entries(obj)) out[key] = transformVariables(val);
386
508
  return out;
387
509
  }
388
- //#endregion
389
- //#region src/rpc.ts
510
+ // src/rpc.ts
390
511
  function buildRpc(operations, subscribe) {
391
512
  const rpc = {};
392
513
  for (const [name, def] of Object.entries(operations)) rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => {
@@ -395,8 +516,7 @@ function buildRpc(operations, subscribe) {
395
516
  };
396
517
  return rpc;
397
518
  }
398
- //#endregion
399
- //#region src/source-mutation.ts
519
+ // src/source-mutation.ts
400
520
  const cache$1 = /* @__PURE__ */ new WeakMap();
401
521
  /**
402
522
  * A create/update answers with the entity itself, so it selects the source's own fragment — the
@@ -444,8 +564,7 @@ function createSourceMutationVariables(binding, values) {
444
564
  function readSourceMutationId(binding, result) {
445
565
  return binding.result === "idScalar" ? result : result.id;
446
566
  }
447
- //#endregion
448
- //#region src/source-subscription.ts
567
+ // src/source-subscription.ts
449
568
  const cache = /* @__PURE__ */ new WeakMap();
450
569
  function createSelection(source) {
451
570
  const spread = `{ ...${source.fragment} }`;
@@ -464,8 +583,7 @@ function createSourceSubscription(source) {
464
583
  cache.set(source, doc);
465
584
  return doc;
466
585
  }
467
- //#endregion
468
- //#region src/sources.ts
586
+ // src/sources.ts
469
587
  const WRITE_KINDS = [
470
588
  "create",
471
589
  "update",
@@ -535,8 +653,7 @@ function createSourceAccessor(name, def, doc, subscribe) {
535
653
  } };
536
654
  }
537
655
  }
538
- //#endregion
539
- //#region src/transform-response.ts
656
+ // src/transform-response.ts
540
657
  const FLAT_PREFIX = "_flat_";
541
658
  const LDT_PREFIX = "_ldt_";
542
659
  const LD_PREFIX = "_ld_";
@@ -617,33 +734,79 @@ function resolveRefs(refs, flatMap) {
617
734
  }
618
735
  return resolved;
619
736
  }
620
- //#endregion
621
- //#region src/upload.ts
622
- const DEFAULT_CHUNK_SIZE = 4194304;
737
+ // src/upload.ts
738
+ function parseServerMessage(data) {
739
+ try {
740
+ return JSON.parse(String(data));
741
+ } catch {
742
+ return;
743
+ }
744
+ }
745
+ const DEFAULT_CHUNK_SIZE = 262144;
746
+ const DEFAULT_TIMINGS = {
747
+ replyTimeout: REPLY_TIMEOUT,
748
+ stallTimeout: 6e4,
749
+ heartbeatTimeout: 15e3
750
+ };
623
751
  function isUint8Array(data) {
624
752
  return data instanceof Uint8Array;
625
753
  }
626
- function upload(url, project, token, data, meta, options) {
754
+ /**
755
+ * Sends a file over the upload websocket and answers with the id of the asset.
756
+ *
757
+ * The server acknowledges the start and every chunk, so while it owes an answer its silence has a
758
+ * limit: `stallTimeout` without a message from it and without a byte leaving for it ends the upload.
759
+ *
760
+ * The server pings for as long as the upload is open, storing the file after the last chunk
761
+ * included, and is alive for as long as its pings come: `heartbeatTimeout` without a ping or a
762
+ * message ends the upload. That takes a Contello that pings its uploads.
763
+ */
764
+ function upload(url, project, token, data, meta, options, { replyTimeout, stallTimeout, heartbeatTimeout } = DEFAULT_TIMINGS) {
627
765
  const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
628
766
  const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
629
767
  const size = isUint8Array(data) ? data.length : meta.size;
630
768
  return new Promise((resolve, reject) => {
631
- const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
769
+ const ws = new (createWebSocketClass(replyTimeout))(wsUrl, "contello-file-upload-v1");
632
770
  let done = false;
771
+ let awaitingAck = false;
772
+ let bytesSent = 0;
773
+ let bytesAcknowledged = 0;
774
+ let lastProgress = Date.now();
775
+ let lastBuffered = 0;
776
+ let lastHeard;
777
+ let cancelSource;
778
+ const stallCheck = setInterval(() => {
779
+ const buffered = ws.bufferedAmount;
780
+ if (buffered < lastBuffered) lastProgress = Date.now();
781
+ lastBuffered = buffered;
782
+ const owed = awaitingAck || bytesAcknowledged < bytesSent;
783
+ if (lastHeard !== void 0 && Date.now() - lastHeard > heartbeatTimeout || owed && Date.now() - lastProgress > stallTimeout) fail(/* @__PURE__ */ new Error("upload stalled: the server stopped answering"));
784
+ }, Math.min(1e3, stallTimeout / 4, heartbeatTimeout / 4));
785
+ stallCheck.unref?.();
633
786
  const cleanup = () => {
787
+ clearInterval(stallCheck);
634
788
  options?.abort?.removeEventListener("abort", abortHandler);
635
789
  };
636
- const abortHandler = () => {
790
+ function fail(error) {
637
791
  if (done) return;
638
- ws.close();
639
- reject(/* @__PURE__ */ new Error("upload aborted"));
640
- };
792
+ done = true;
793
+ cleanup();
794
+ cancelSource?.();
795
+ ws.terminate();
796
+ reject(error);
797
+ }
798
+ const abortHandler = () => fail(/* @__PURE__ */ new Error("upload aborted"));
641
799
  options?.abort?.addEventListener("abort", abortHandler);
800
+ function send(chunk) {
801
+ if (bytesAcknowledged === bytesSent) lastProgress = Date.now();
802
+ bytesSent += chunk.length;
803
+ ws.send(chunk);
804
+ }
642
805
  function sendBuffer(buf) {
643
806
  let offset = 0;
644
807
  while (offset < buf.length) {
645
808
  const chunk = buf.subarray(offset, offset + chunkSize);
646
- ws.send(chunk);
809
+ send(chunk);
647
810
  offset += chunk.length;
648
811
  }
649
812
  ws.send(JSON.stringify({ type: "done" }));
@@ -652,8 +815,8 @@ function upload(url, project, token, data, meta, options) {
652
815
  function waitForBufferedDrain() {
653
816
  return new Promise((resolveDrain, rejectDrain) => {
654
817
  const check = () => {
655
- if (options?.abort?.aborted) {
656
- rejectDrain(/* @__PURE__ */ new Error("upload aborted"));
818
+ if (done) {
819
+ rejectDrain(/* @__PURE__ */ new Error("upload ended"));
657
820
  return;
658
821
  }
659
822
  if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
@@ -667,17 +830,19 @@ function upload(url, project, token, data, meta, options) {
667
830
  }
668
831
  async function sendStream(stream) {
669
832
  const reader = stream.getReader();
833
+ cancelSource = () => void reader.cancel().catch(() => {});
670
834
  try {
671
835
  while (true) {
672
836
  const { done: streamDone, value } = await reader.read();
673
837
  if (streamDone) break;
674
- await waitForBufferedDrain();
675
- ws.send(value);
838
+ for (let offset = 0; offset < value.length; offset += chunkSize) {
839
+ await waitForBufferedDrain();
840
+ send(value.subarray(offset, offset + chunkSize));
841
+ }
676
842
  }
677
843
  ws.send(JSON.stringify({ type: "done" }));
678
844
  } catch (error) {
679
- reject(error);
680
- ws.close();
845
+ fail(error instanceof Error ? error : new Error(String(error)));
681
846
  }
682
847
  }
683
848
  ws.addEventListener("open", () => {
@@ -690,11 +855,29 @@ function upload(url, project, token, data, meta, options) {
690
855
  },
691
856
  token
692
857
  };
858
+ awaitingAck = true;
859
+ lastProgress = Date.now();
860
+ lastHeard = Date.now();
693
861
  ws.send(JSON.stringify(initFrame));
694
862
  });
695
863
  ws.addEventListener("message", (event) => {
696
- const message = JSON.parse(String(event.data));
864
+ const message = parseServerMessage(event.data);
865
+ if (!message) {
866
+ fail(/* @__PURE__ */ new Error(`upload failed: ${String(event.data)}`));
867
+ return;
868
+ }
869
+ if (message.type === "error") {
870
+ fail(/* @__PURE__ */ new Error(`upload failed: ${message.error}`));
871
+ return;
872
+ }
873
+ lastProgress = Date.now();
874
+ lastHeard = Date.now();
875
+ if (message.type === "progress") {
876
+ bytesAcknowledged = Math.max(bytesAcknowledged, message.bytesReceived);
877
+ return;
878
+ }
697
879
  if (message.type === "ack") {
880
+ awaitingAck = false;
698
881
  if (isUint8Array(data)) sendBuffer(data);
699
882
  else sendStream(data);
700
883
  return;
@@ -705,18 +888,14 @@ function upload(url, project, token, data, meta, options) {
705
888
  ws.close();
706
889
  resolve(message.id);
707
890
  });
708
- ws.addEventListener("error", () => {
709
- cleanup();
710
- reject(/* @__PURE__ */ new Error("upload websocket error"));
711
- });
712
- ws.addEventListener("close", () => {
713
- cleanup();
714
- if (!done) reject(/* @__PURE__ */ new Error("connection closed before upload completed"));
891
+ ws.on("ping", () => {
892
+ lastHeard = Date.now();
715
893
  });
894
+ ws.addEventListener("error", () => fail(/* @__PURE__ */ new Error("upload websocket error")));
895
+ ws.addEventListener("close", () => fail(/* @__PURE__ */ new Error("connection closed before upload completed")));
716
896
  });
717
897
  }
718
- //#endregion
719
- //#region src/client.ts
898
+ // src/client.ts
720
899
  var ContelloClient = class {
721
900
  _pool;
722
901
  _rpc;
@@ -751,36 +930,23 @@ var ContelloClient = class {
751
930
  connectionId: id,
752
931
  websocketUrl
753
932
  });
754
- return (0, graphql_ws.createClient)({
933
+ return createConnection({
755
934
  url: websocketUrl,
756
- connectionParams: { token },
757
- lazy: false,
758
- keepAlive: 3e4,
759
- retryAttempts: Infinity,
760
- retryWait: _entwico_dash_async.exponentialBackoff,
761
- shouldRetry: () => true,
762
- jsonMessageReplacer: (key, value) => {
763
- if (!key) return (0, _contello_opentelemetry.injectTraceContext)(value);
764
- return value;
935
+ token,
936
+ onFatalError: options.onError,
937
+ onConnecting: () => connectionEvents?.onConnecting?.(context),
938
+ onConnected: () => {
939
+ onConnectionUp();
940
+ connectionEvents?.onConnected?.(context);
765
941
  },
766
- ...options.onError && { onNonLazyError: (e) => options.onError(e) },
767
- on: {
768
- connected: () => {
769
- onConnectionUp();
770
- connectionEvents?.onConnected?.(context);
771
- },
772
- connecting: () => {
773
- connectionEvents?.onConnecting?.(context);
774
- },
775
- closed: () => {
776
- onConnectionDown();
777
- connectionEvents?.onClosed?.(context);
778
- },
779
- ...(options.onError || connectionEvents?.onError) && { error: (e) => {
780
- options.onError?.(e);
781
- connectionEvents?.onError?.(context, e);
782
- } }
783
- }
942
+ onClosed: () => {
943
+ onConnectionDown();
944
+ connectionEvents?.onClosed?.(context);
945
+ },
946
+ ...(options.onError || connectionEvents?.onError) && { onError: (e) => {
947
+ options.onError?.(e);
948
+ connectionEvents?.onError?.(context, e);
949
+ } }
784
950
  });
785
951
  }, connections);
786
952
  this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
@@ -912,8 +1078,7 @@ var ContelloClient = class {
912
1078
  function createContelloClient(options) {
913
1079
  return new ContelloClient(options);
914
1080
  }
915
- //#endregion
916
- //#region src/built-in-mutations.ts
1081
+ // src/built-in-mutations.ts
917
1082
  /**
918
1083
  * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their
919
1084
  * field and argument names are fixed parts of every Contello schema — but the generator still
@@ -977,7 +1142,6 @@ const BUILT_IN_MUTATIONS = {
977
1142
  }
978
1143
  }
979
1144
  };
980
- //#endregion
981
1145
  exports.BUILT_IN_MUTATIONS = BUILT_IN_MUTATIONS;
982
1146
  exports.ContelloClient = ContelloClient;
983
1147
  exports.createContelloClient = createContelloClient;