@sortlist/cli 0.63.0 → 0.65.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.
@@ -126,9 +126,16 @@ function createRouterClient(options) {
126
126
  graphqlErrors: errors
127
127
  });
128
128
  }
129
- async function execute(query, variables) {
130
- const res = await post(query, variables, headersFor());
131
- const json = await res.json();
129
+ async function respond(query, variables, signal) {
130
+ try {
131
+ const res = await post(query, variables, headersFor(), signal);
132
+ return await res.json();
133
+ } catch (err) {
134
+ throw signal?.aborted ? signal.reason : err;
135
+ }
136
+ }
137
+ async function execute(query, variables, signal) {
138
+ const json = await respond(query, variables, signal);
132
139
  if (json.errors?.length) {
133
140
  if (!hasResolvedField(json.data)) failWith(json.errors);
134
141
  options.onPartialErrors?.(json.errors);
@@ -174,6 +181,15 @@ function unwrap(type) {
174
181
  if (isListType(type)) return unwrap(type.ofType);
175
182
  return type;
176
183
  }
184
+ function operationArg(field) {
185
+ return {
186
+ name: field.name,
187
+ type: field.type,
188
+ required: isNonNullType(field.type),
189
+ description: field.description,
190
+ ...field.defaultValue === void 0 ? {} : { defaultValue: field.defaultValue }
191
+ };
192
+ }
177
193
  function isRecord(value) {
178
194
  return typeof value === "object" && value !== null;
179
195
  }
@@ -183,13 +199,7 @@ function getInputFields(field) {
183
199
  if (arg.name !== "input") return null;
184
200
  const argType = isNonNullType(arg.type) ? arg.type.ofType : arg.type;
185
201
  if (!isInputObjectType(argType)) return null;
186
- const fields = argType.getFields();
187
- return Object.entries(fields).map(([name, f]) => ({
188
- name,
189
- type: f.type,
190
- required: isNonNullType(f.type),
191
- description: f.description
192
- }));
202
+ return Object.values(argType.getFields()).map(operationArg);
193
203
  }
194
204
  function supersededBy(field, siblings) {
195
205
  const replacement = field.deprecationReason?.match(/`(\w+)`/)?.[1];
@@ -260,12 +270,7 @@ function listOperations(introspected) {
260
270
  if (!type || !services) continue;
261
271
  for (const { fieldName, field, service } of exposedFields(type, services)) {
262
272
  const inputFields = getInputFields(field);
263
- const args = inputFields ?? field.args.map((a) => ({
264
- name: a.name,
265
- type: a.type,
266
- required: isNonNullType(a.type),
267
- description: a.description
268
- }));
273
+ const args = inputFields ?? field.args.map(operationArg);
269
274
  const resultSubscription = kind === "mutation" ? pairs.get(fieldName) : void 0;
270
275
  const scopes = fieldScopes.get(type.name)?.get(fieldName);
271
276
  operations.push({
@@ -668,6 +673,8 @@ function abstractFieldsFromList(type, schema, subPaths, totalCount) {
668
673
 
669
674
  // src/core/run-operation.ts
670
675
  import { randomUUID } from "crypto";
676
+ import { setTimeout as delay } from "timers/promises";
677
+ import { isDeepStrictEqual } from "util";
671
678
  var ResultNotDeliveredError = class extends Error {
672
679
  subscription;
673
680
  constructor(subscription) {
@@ -692,7 +699,7 @@ function nextPageCursor(result) {
692
699
  }
693
700
  return null;
694
701
  }
695
- async function listen(client, query, variables, seconds, signal, options = {}) {
702
+ function deadlineAfter(seconds, signal) {
696
703
  const controller = new AbortController();
697
704
  let expired = false;
698
705
  const timer = setTimeout(() => {
@@ -702,33 +709,80 @@ async function listen(client, query, variables, seconds, signal, options = {}) {
702
709
  const forward = () => controller.abort(signal?.reason);
703
710
  if (signal?.aborted) forward();
704
711
  signal?.addEventListener("abort", forward, { once: true });
705
- const stop = () => {
706
- clearTimeout(timer);
707
- signal?.removeEventListener("abort", forward);
708
- controller.abort();
712
+ return {
713
+ signal: controller.signal,
714
+ timedOut: () => expired,
715
+ stop: () => {
716
+ clearTimeout(timer);
717
+ signal?.removeEventListener("abort", forward);
718
+ controller.abort();
719
+ }
720
+ };
721
+ }
722
+ function abortReasonOr(err, signal) {
723
+ return signal?.aborted ? signal.reason : err;
724
+ }
725
+ var RECONNECT_DELAYS_MS = [500, 1e3, 2e3];
726
+ function reconnectDelay(attempts) {
727
+ return RECONNECT_DELAYS_MS[Math.min(attempts, RECONNECT_DELAYS_MS.length - 1)];
728
+ }
729
+ var GATEWAY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
730
+ function reconnectable(err) {
731
+ if (isDroppedStream(err)) return true;
732
+ if (!(err instanceof RouterError)) return false;
733
+ return err.kind === "unreachable" || err.kind === "http" && GATEWAY_STATUSES.has(err.httpStatus ?? 0);
734
+ }
735
+ async function subscribeWithin(deadline, client, query, variables, signal, options) {
736
+ const open = () => client.openSubscription(query, variables, deadline.signal);
737
+ const giveUpUnlessReconnectable = (err) => {
738
+ if (signal?.aborted) throw signal.reason;
739
+ if (deadline.timedOut() || !reconnectable(err)) throw err;
709
740
  };
710
- const open = () => client.openSubscription(query, variables, controller.signal);
711
741
  let first;
712
742
  try {
713
743
  first = await open();
714
744
  } catch (err) {
715
- stop();
716
- throw err;
745
+ throw abortReasonOr(err, signal);
746
+ }
747
+ let attempts = 0;
748
+ async function reopen() {
749
+ for (; ; ) {
750
+ try {
751
+ await delay(reconnectDelay(attempts), void 0, { signal: deadline.signal });
752
+ attempts += 1;
753
+ return await open();
754
+ } catch (err) {
755
+ giveUpUnlessReconnectable(err);
756
+ }
757
+ }
717
758
  }
718
759
  async function* events() {
719
760
  let current = first;
720
761
  for (; ; ) {
721
762
  try {
722
- yield* current;
763
+ for await (const event of current) {
764
+ attempts = 0;
765
+ yield event;
766
+ }
723
767
  return;
724
768
  } catch (err) {
725
- if (expired || !isDroppedStream(err)) throw err;
726
- current = await open();
727
- options.onReopen?.();
769
+ giveUpUnlessReconnectable(err);
728
770
  }
771
+ current = await reopen();
772
+ options.onReopen?.();
729
773
  }
730
774
  }
731
- return { events: events(), stop, timedOut: () => expired, signal: controller.signal };
775
+ return events();
776
+ }
777
+ async function listen(client, query, variables, seconds, signal, options = {}) {
778
+ const deadline = deadlineAfter(seconds, signal);
779
+ try {
780
+ const events = await subscribeWithin(deadline, client, query, variables, signal, options);
781
+ return { events, stop: deadline.stop, timedOut: deadline.timedOut, signal: deadline.signal };
782
+ } catch (err) {
783
+ deadline.stop();
784
+ throw err;
785
+ }
732
786
  }
733
787
  function wrap(spec, args) {
734
788
  return spec.inputWrapper ? { input: args } : args;
@@ -738,9 +792,35 @@ function withPageStatus(schema, subscription, selection) {
738
792
  if (!deliversFillingPages(schema, subscription)) return selection;
739
793
  return { ...selection, fields: [...selection.fields, PAGE_STATUS_FIELD] };
740
794
  }
741
- function timedOutBy(err, listener) {
795
+ function timedOutBy(err, deadline) {
742
796
  const cause = err instanceof Error ? err.cause : void 0;
743
- return listener.timedOut() && (isAbort(err) || isAbort(cause));
797
+ return deadline.timedOut() && (isAbort(err) || isAbort(cause));
798
+ }
799
+ function edgeCount(data) {
800
+ if (!isRecord(data)) return 0;
801
+ let count = 0;
802
+ for (const value of Object.values(data)) {
803
+ const edges = isRecord(value) ? value.edges ?? value.nodes : void 0;
804
+ if (Array.isArray(edges)) count += edges.length;
805
+ }
806
+ return count;
807
+ }
808
+ function supersedes(page, current, byArrival) {
809
+ if (!current) return true;
810
+ if (page.filling !== current.filling) return !page.filling;
811
+ if (byArrival) return true;
812
+ const more = page.filling ? edgeCount(page.data) - edgeCount(current.data) : 0;
813
+ return more > 0 || more === 0 && page.streamed;
814
+ }
815
+ function offer(wait, page) {
816
+ if (wait.ended || !supersedes(page, wait.latest, wait.byArrival)) return;
817
+ wait.latest = page;
818
+ if (!wait.onPage || wait.delivered.some((seen) => isDeepStrictEqual(seen, page.data))) return;
819
+ wait.delivered.push(page.data);
820
+ wait.onPage(page.data);
821
+ }
822
+ function completed(wait) {
823
+ return wait.latest?.filling === false;
744
824
  }
745
825
  function whenAborted(signal) {
746
826
  return new Promise((_, reject) => {
@@ -749,11 +829,10 @@ function whenAborted(signal) {
749
829
  });
750
830
  }
751
831
  var StoredReads = class {
752
- constructor(wait, read, signal, onPage) {
832
+ constructor(wait, read, signal) {
753
833
  this.wait = wait;
754
834
  this.read = read;
755
835
  this.signal = signal;
756
- this.onPage = onPage;
757
836
  this.completed = new Promise((resolve) => {
758
837
  this.finish = resolve;
759
838
  });
@@ -765,56 +844,61 @@ var StoredReads = class {
765
844
  wait;
766
845
  read;
767
846
  signal;
768
- onPage;
769
847
  completed;
770
848
  failed;
771
849
  finish = () => void 0;
772
850
  fail = () => void 0;
773
851
  inflight = /* @__PURE__ */ new Set();
852
+ started = 0;
853
+ newestSettled = 0;
774
854
  start() {
775
- const reading = this.take(this.wait.pages).catch((err) => this.fail(err)).finally(() => this.inflight.delete(reading));
855
+ this.started += 1;
856
+ const reading = this.take(this.started).catch((err) => this.fail(err)).finally(() => this.inflight.delete(reading));
776
857
  this.inflight.add(reading);
777
858
  }
778
859
  settled() {
779
860
  return Promise.race([Promise.allSettled([...this.inflight]), this.failed, whenAborted(this.signal)]);
780
861
  }
781
- async take(pagesBefore) {
862
+ async take(order) {
782
863
  let result;
783
864
  try {
784
865
  result = await this.read(this.signal);
785
866
  } catch (err) {
786
- if (!this.signal.aborted) this.wait.readFailure = err;
867
+ if (!this.signal.aborted) this.settle(order, err);
787
868
  return;
788
869
  }
789
870
  if (this.signal.aborted) return;
790
- if (result?.state === "complete") {
791
- this.wait.stored = result;
792
- this.deliver(result.data);
793
- this.finish();
794
- } else if (result?.state === "filling" && this.wait.pages === pagesBefore) {
795
- this.wait.latest = { page: { data: result.data, nextCursor: result.nextCursor }, filling: true };
796
- this.deliver(result.data);
797
- }
798
- }
799
- deliver(page) {
871
+ this.settle(order, void 0);
872
+ if (result?.state !== "complete" && result?.state !== "filling") return;
800
873
  try {
801
- this.onPage?.(page);
874
+ offer(this.wait, {
875
+ data: result.data,
876
+ nextCursor: result.nextCursor,
877
+ filling: result.state === "filling",
878
+ streamed: false
879
+ });
802
880
  } catch (err) {
803
881
  this.fail(err);
804
882
  }
883
+ if (completed(this.wait)) this.finish();
884
+ }
885
+ settle(order, failure) {
886
+ if (order < this.newestSettled) return;
887
+ this.newestSettled = order;
888
+ this.wait.readFailure = failure;
805
889
  }
806
890
  };
807
- async function follow(listener, wait, fieldName, onPage) {
808
- for await (const data of listener.events) {
891
+ async function follow(events, wait, fieldName) {
892
+ for await (const data of events) {
809
893
  if (!(fieldName in data)) continue;
810
894
  const delivered = data[fieldName];
811
- wait.pages += 1;
812
- wait.latest = {
813
- page: { data: delivered, nextCursor: nextPageCursor(delivered) },
814
- filling: isStillFilling(delivered)
815
- };
816
- onPage?.(delivered);
817
- if (!wait.latest.filling) return;
895
+ offer(wait, {
896
+ data: delivered,
897
+ nextCursor: nextPageCursor(delivered),
898
+ filling: isStillFilling(delivered),
899
+ streamed: true
900
+ });
901
+ if (completed(wait)) return;
818
902
  }
819
903
  }
820
904
  function withExternalId(input, subscription) {
@@ -827,12 +911,19 @@ function withExternalId(input, subscription) {
827
911
  async function runWithoutWaiting(input, variables, externalId) {
828
912
  const { schema, spec, client } = input;
829
913
  const built = buildQuery(schema, spec.kind, spec.fieldName, variables, input.selection);
830
- const data = await client.execute(built.query, built.variables);
914
+ const data = await client.execute(built.query, built.variables, input.signal);
831
915
  const done = { state: "done", data: data[built.fieldName] };
832
916
  return externalId === void 0 ? done : { ...done, externalId };
833
917
  }
834
918
  async function runOperation(input) {
835
- const { schema, spec, client, waitSeconds } = input;
919
+ try {
920
+ return await runUntilSettled(input);
921
+ } catch (err) {
922
+ throw abortReasonOr(err, input.signal);
923
+ }
924
+ }
925
+ async function runUntilSettled(input) {
926
+ const { spec, waitSeconds } = input;
836
927
  if (spec.kind === "subscription") {
837
928
  throw new Error(`${spec.fieldName} is a subscription: listen to it rather than run it.`);
838
929
  }
@@ -840,9 +931,13 @@ async function runOperation(input) {
840
931
  const args = withExternalId(input, subscription);
841
932
  const variables = wrap(spec, args);
842
933
  if (subscription === void 0 || waitSeconds === void 0) {
843
- const externalId2 = subscription === void 0 ? void 0 : args.externalId;
844
- return runWithoutWaiting(input, variables, externalId2);
934
+ const externalId = subscription === void 0 ? void 0 : args.externalId;
935
+ return runWithoutWaiting(input, variables, externalId);
845
936
  }
937
+ return runWaiting(input, subscription, args, variables, waitSeconds);
938
+ }
939
+ async function runWaiting(input, subscription, args, variables, waitSeconds) {
940
+ const { schema, spec, client } = input;
846
941
  const externalId = args.externalId;
847
942
  const subscriptionVariables = subscriptionVariablesFor(schema, subscription, args, externalId);
848
943
  const listened = buildQuery(
@@ -854,28 +949,32 @@ async function runOperation(input) {
854
949
  );
855
950
  const reveal = input.selection.reveal;
856
951
  const mutation = buildQuery(schema, spec.kind, spec.fieldName, variables, reveal === void 0 ? {} : { reveal });
857
- const wait = { pages: 0 };
858
- let reads;
859
- const listener = await listen(
860
- client,
861
- listened.query,
862
- listened.variables,
863
- waitSeconds,
864
- input.signal,
865
- input.readStored ? { onReopen: () => reads?.start() } : {}
866
- );
867
- if (input.readStored) reads = new StoredReads(wait, input.readStored, listener.signal, input.onPage);
952
+ const wait = { ended: false, byArrival: !input.readStored, delivered: [], onPage: input.onPage };
953
+ const deadline = deadlineAfter(waitSeconds, input.signal);
954
+ const reads = input.readStored ? new StoredReads(wait, input.readStored, deadline.signal) : void 0;
955
+ let opened = false;
868
956
  try {
869
- await client.execute(mutation.query, mutation.variables);
870
- const following = follow(listener, wait, listened.fieldName, input.onPage);
957
+ const events = await subscribeWithin(
958
+ deadline,
959
+ client,
960
+ listened.query,
961
+ listened.variables,
962
+ input.signal,
963
+ reads ? { onReopen: () => reads.start() } : {}
964
+ );
965
+ opened = true;
966
+ await client.execute(mutation.query, mutation.variables, input.signal);
967
+ const following = follow(events, wait, listened.fieldName);
871
968
  if (reads) await followWithReads(following, reads, wait);
872
969
  else await following;
873
970
  } catch (err) {
874
- if (!timedOutBy(err, listener)) throw err;
971
+ if (input.signal?.aborted || !timedOutBy(err, deadline)) throw err;
972
+ if (!opened) throw notSent(err, spec.fieldName, subscription, waitSeconds);
875
973
  if (!wait.latest) return { state: "pending", ended: "timeout", externalId };
876
- return { state: "filling", ended: "timeout", externalId, ...wait.latest.page };
974
+ return resultOf(wait.latest, externalId, "timeout");
877
975
  } finally {
878
- listener.stop();
976
+ wait.ended = true;
977
+ deadline.stop();
879
978
  }
880
979
  return closedOn(wait, externalId, subscription);
881
980
  }
@@ -883,15 +982,35 @@ async function followWithReads(following, reads, wait) {
883
982
  following.catch(() => void 0);
884
983
  reads.start();
885
984
  await Promise.race([following, reads.completed, reads.failed]);
886
- if (!wait.stored && wait.latest?.filling !== false) await reads.settled();
985
+ if (!completed(wait)) await reads.settled();
986
+ }
987
+ function notSent(cause, mutation, subscription, waitSeconds) {
988
+ return new RouterError(`${subscription} did not open within ${waitSeconds}s, so ${mutation} was not sent.`, {
989
+ kind: "unreachable",
990
+ code: "UNREACHABLE",
991
+ cause
992
+ });
993
+ }
994
+ function resultOf(latest, externalId, ended) {
995
+ const { data, nextCursor } = latest;
996
+ if (latest.filling) return { state: "filling", ended, externalId, data, nextCursor };
997
+ return { state: "complete", externalId, data, nextCursor };
887
998
  }
888
999
  function closedOn(wait, externalId, subscription) {
889
- if (wait.stored) return wait.stored;
890
1000
  if (!wait.latest) throw wait.readFailure ?? new ResultNotDeliveredError(subscription);
891
- if (wait.latest.filling) return { state: "filling", ended: "closed", externalId, ...wait.latest.page };
892
- return { state: "complete", externalId, ...wait.latest.page };
1001
+ return resultOf(wait.latest, externalId, "closed");
893
1002
  }
894
1003
 
1004
+ // src/core/scopes.ts
1005
+ var USER_API_SCOPES = [
1006
+ "atlas/organization:read",
1007
+ "atlas/reveal:read",
1008
+ "outreach/channel_account:read",
1009
+ "outreach/channel_account:write",
1010
+ "signals/watcher:read",
1011
+ "signals/watcher:write"
1012
+ ];
1013
+
895
1014
  // src/core/introspect.ts
896
1015
  import { buildClientSchema, getIntrospectionQuery } from "graphql";
897
1016
  async function fetchIntrospection(endpoint, token, fetchImpl = fetch, baseHeaders = {}) {
@@ -900,7 +1019,7 @@ async function fetchIntrospection(endpoint, token, fetchImpl = fetch, baseHeader
900
1019
  const res = await fetchImpl(endpoint, {
901
1020
  method: "POST",
902
1021
  headers,
903
- body: JSON.stringify({ query: getIntrospectionQuery() })
1022
+ body: JSON.stringify({ query: getIntrospectionQuery({ oneOf: true }) })
904
1023
  });
905
1024
  if (!res.ok) {
906
1025
  throw new Error(`Introspection failed: HTTP ${res.status} ${res.statusText}`);
@@ -986,11 +1105,15 @@ export {
986
1105
  ResultNotDeliveredError,
987
1106
  isAbort,
988
1107
  nextPageCursor,
1108
+ reconnectable,
989
1109
  listen,
1110
+ withPageStatus,
1111
+ supersedes,
990
1112
  runOperation,
1113
+ USER_API_SCOPES,
991
1114
  fetchIntrospection,
992
1115
  requiredScopes,
993
1116
  buildIntrospected,
994
1117
  introspect
995
1118
  };
996
- //# sourceMappingURL=chunk-MOYY5PLS.js.map
1119
+ //# sourceMappingURL=chunk-R7GAJC42.js.map