@alxia/graphql 0.13.3 → 0.15.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.js CHANGED
@@ -105,26 +105,8 @@ function boundedStream(source, options) {
105
105
  };
106
106
  return stream;
107
107
  }
108
- // src/graphql.ts
109
- import {
110
- isDev
111
- } from "@alxia/core";
112
-
113
- // src/endpoint.ts
114
- var DEFAULT_BODY_LIMIT = 1048576;
115
- function declareEndpoint(app, path, handler, bodyLimit, socket) {
116
- const route = app;
117
- route.get(path, handler);
118
- const inherited = app.routes.at(-1)?.bodyLimit;
119
- const own = bodyLimit ?? (inherited === undefined ? DEFAULT_BODY_LIMIT : undefined);
120
- if (own === undefined)
121
- route.post(path, handler);
122
- else
123
- route.post(path, { bodyLimit: own }, handler);
124
- if (socket !== undefined) {
125
- route.ws(socket.path, socket.middleware, socket.handlers);
126
- }
127
- }
108
+ // src/yoga.ts
109
+ import { isDev } from "@alxia/core";
128
110
 
129
111
  // src/handler.ts
130
112
  import {
@@ -628,9 +610,350 @@ function parseCaches(parseCache) {
628
610
  return { documentCache, errorCache };
629
611
  }
630
612
 
613
+ // src/yoga.ts
614
+ function yogaFor(yogaOptions, page) {
615
+ const { maxTokens, maxNesting, parseCache, ...rest } = yogaOptions;
616
+ const { cors, ide, graphiql } = page;
617
+ const limits = resolveLimits(maxTokens, maxNesting, parseCache, rest);
618
+ const shown = graphiql ?? true;
619
+ return yogaServers({
620
+ ...rest,
621
+ ...rest["logging"] === undefined ? { logging: "warn" } : {},
622
+ ...untrustedRequestId(rest),
623
+ plugins: [
624
+ limitsParsing(limits.tokens, limits.depth),
625
+ ...rest["plugins"] ?? [],
626
+ reportsOperations()
627
+ ],
628
+ cors,
629
+ graphiql: ide === undefined ? (_request, context) => isDev(context) && shown : ide === "graphiql" ? shown : false
630
+ }, rest["parserAndValidationCache"] === undefined ? () => parseCaches(parseCache) : undefined);
631
+ }
632
+ function untrustedRequestId(options) {
633
+ const { requestId } = options;
634
+ if (requestId === undefined)
635
+ return { requestId: false };
636
+ if (requestId === true)
637
+ return { requestId: { trustHeader: false } };
638
+ if (typeof requestId === "object" && requestId !== null) {
639
+ return { requestId: { trustHeader: false, ...requestId } };
640
+ }
641
+ return {};
642
+ }
643
+
644
+ // src/executor.ts
645
+ var SUBSCRIPTION_REFUSED = {
646
+ errors: [
647
+ {
648
+ message: "graphqlExecutor runs queries and mutations, not a subscription.",
649
+ extensions: { code: "SUBSCRIPTION_NOT_SUPPORTED" }
650
+ }
651
+ ]
652
+ };
653
+ function graphqlExecutor(options) {
654
+ const yoga = yogaFor(options, { cors: false, ide: false })("/graphql");
655
+ return async (request, context, call) => {
656
+ const response = await yoga.fetch(new Request("http://in-process/graphql", {
657
+ method: "POST",
658
+ headers: {
659
+ "content-type": "application/json",
660
+ accept: "application/json, text/event-stream"
661
+ },
662
+ body: JSON.stringify({
663
+ query: request.query,
664
+ ...request.operationName !== undefined && {
665
+ operationName: request.operationName
666
+ },
667
+ ...request.variables !== undefined && {
668
+ variables: request.variables
669
+ }
670
+ }),
671
+ ...call?.signal !== undefined && { signal: call.signal }
672
+ }), context);
673
+ if (/text\/event-stream|multipart\/mixed/.test(response.headers.get("content-type") ?? "")) {
674
+ response.body?.cancel();
675
+ return SUBSCRIPTION_REFUSED;
676
+ }
677
+ const body = await response.json();
678
+ return {
679
+ ...body.data !== undefined && { data: body.data },
680
+ ...body.errors !== undefined && { errors: body.errors }
681
+ };
682
+ };
683
+ }
684
+ // src/field-rate-limit/count.ts
685
+ import {
686
+ print
687
+ } from "graphql";
688
+ function countSelections(document, selections, names, singles = new Set) {
689
+ const fragments = new Map;
690
+ for (const definition of document.definitions) {
691
+ if (definition.kind === "FragmentDefinition") {
692
+ fragments.set(definition.name.value, definition);
693
+ }
694
+ }
695
+ const done = new Map;
696
+ const active = new Set;
697
+ const walk = (set) => {
698
+ const counts = new Map;
699
+ const add = (from, under = "") => {
700
+ for (const [name, selected] of from) {
701
+ const own = counts.get(name) ?? { count: 0, distinct: new Set };
702
+ own.count += selected.count;
703
+ for (const one of selected.distinct) {
704
+ if (own.distinct.size >= 2)
705
+ break;
706
+ own.distinct.add(under + one);
707
+ }
708
+ counts.set(name, own);
709
+ }
710
+ };
711
+ for (const selection of set.selections) {
712
+ if (selection.kind === "Field") {
713
+ const name = selection.name.value;
714
+ const written = `${selection.alias?.value ?? name}(${(selection.arguments ?? []).map((argument) => print(argument)).sort().join(",")})`;
715
+ if (names.has(name)) {
716
+ const own = counts.get(name) ?? { count: 0, distinct: new Set };
717
+ own.count += 1;
718
+ if (singles.has(name) && own.distinct.size < 2)
719
+ own.distinct.add(written);
720
+ counts.set(name, own);
721
+ }
722
+ if (selection.selectionSet) {
723
+ add(walk(selection.selectionSet), `${written}/`);
724
+ }
725
+ } else if (selection.kind === "InlineFragment") {
726
+ add(walk(selection.selectionSet));
727
+ } else {
728
+ const name = selection.name.value;
729
+ const fragment = fragments.get(name);
730
+ if (fragment === undefined || active.has(name))
731
+ continue;
732
+ let own = done.get(name);
733
+ if (own === undefined) {
734
+ active.add(name);
735
+ own = walk(fragment.selectionSet);
736
+ active.delete(name);
737
+ done.set(name, own);
738
+ }
739
+ add(own);
740
+ }
741
+ }
742
+ return counts;
743
+ };
744
+ return walk(selections);
745
+ }
746
+ // src/field-rate-limit/from-store.ts
747
+ function limitFromStore(store, policy) {
748
+ const own = store.policy;
749
+ const resolved = {
750
+ limit: policy?.limit ?? own?.limit ?? Number.NaN,
751
+ windowMs: policy?.windowMs ?? own?.windowMs ?? Number.NaN
752
+ };
753
+ for (const name of ["limit", "windowMs"]) {
754
+ const value = resolved[name];
755
+ if (!Number.isSafeInteger(value) || value < 1) {
756
+ throw new TypeError(`limitFromStore: ${name} must be a whole number of 1 or more, not ${String(policy?.[name] ?? own?.[name])}`);
757
+ }
758
+ if (own !== undefined && value !== own[name]) {
759
+ throw new TypeError(`limitFromStore: ${name} ${value} differs from the store's policy of ${own.limit} per ${own.windowMs}ms. Leave the policy out to use the store's, or give the same numbers.`);
760
+ }
761
+ }
762
+ return {
763
+ async consume(key, cost) {
764
+ for (let i = 0;i < cost; i++) {
765
+ const decision = await store.consume(key, resolved);
766
+ if (!decision.allowed) {
767
+ return { allowed: false, retryAfter: decision.retryAfter };
768
+ }
769
+ }
770
+ return { allowed: true, retryAfter: 0 };
771
+ }
772
+ };
773
+ }
774
+ // src/field-rate-limit/plugin.ts
775
+ import { GraphQLError as GraphQLError2, getOperationAST as getOperationAST2 } from "graphql";
776
+
777
+ // src/field-rate-limit/ipv6-network.ts
778
+ function groupsOf(text) {
779
+ const zone = text.indexOf("%");
780
+ const address = zone === -1 ? text : text.slice(0, zone);
781
+ const halves = address.split("::");
782
+ if (halves.length > 2 || !address.includes(":"))
783
+ return;
784
+ const read = (half) => half === undefined || half === "" ? [] : half.split(":");
785
+ const head = read(halves[0]) ?? [];
786
+ const tail = read(halves[1]) ?? [];
787
+ const written = [...head, ...tail];
788
+ const last = written[written.length - 1];
789
+ if (last?.includes(".")) {
790
+ if (!address.endsWith(last))
791
+ return;
792
+ const octets = last.split(".");
793
+ const bytes = octets.map((octet) => /^\d{1,3}$/.test(octet) ? Number(octet) : Number.NaN);
794
+ if (bytes.length !== 4 || bytes.some((byte) => !(byte <= 255)))
795
+ return;
796
+ const [a = 0, b = 0, c = 0, d = 0] = bytes;
797
+ written.splice(-1, 1, (a << 8 | b).toString(16), (c << 8 | d).toString(16));
798
+ if (tail.length > 0)
799
+ tail.splice(-1, 1, "x", "x");
800
+ else
801
+ head.splice(-1, 1, "x", "x");
802
+ }
803
+ const compressed = halves.length === 2;
804
+ const missing = 8 - written.length;
805
+ if (compressed ? missing < 1 : missing !== 0)
806
+ return;
807
+ const all = compressed ? [
808
+ ...written.slice(0, head.length),
809
+ ...new Array(missing).fill("0"),
810
+ ...written.slice(head.length)
811
+ ] : written;
812
+ const groups = all.map((group) => /^[0-9a-f]{1,4}$/i.test(group) ? Number.parseInt(group, 16) : Number.NaN);
813
+ return groups.some(Number.isNaN) ? undefined : groups;
814
+ }
815
+ function written(groups) {
816
+ let start = -1;
817
+ let length = 0;
818
+ for (let i = 0;i < 8; ) {
819
+ if (groups[i] !== 0) {
820
+ i++;
821
+ continue;
822
+ }
823
+ let end = i;
824
+ while (end < 8 && groups[end] === 0)
825
+ end++;
826
+ if (end - i > length) {
827
+ start = i;
828
+ length = end - i;
829
+ }
830
+ i = end;
831
+ }
832
+ const hex = (list) => list.map((group) => group.toString(16)).join(":");
833
+ if (length < 2)
834
+ return hex(groups);
835
+ return `${hex(groups.slice(0, start))}::${hex(groups.slice(start + length))}`;
836
+ }
837
+ function ipv6Network(address, prefix) {
838
+ const groups = groupsOf(address);
839
+ if (groups === undefined)
840
+ return address;
841
+ if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535) {
842
+ const [a = 0, b = 0] = groups.slice(6);
843
+ return `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`;
844
+ }
845
+ const masked = groups.map((group, index) => {
846
+ const kept = Math.min(16, Math.max(0, prefix - index * 16));
847
+ return group >> 16 - kept << 16 - kept;
848
+ });
849
+ return `${written(masked.map((group) => group & 65535))}/${prefix}`;
850
+ }
851
+
852
+ // src/field-rate-limit/plugin.ts
853
+ var DEFAULT_LIMIT_CODE = "RATE_LIMITED";
854
+ function rulesOf(fields) {
855
+ if (typeof fields !== "object" || fields === null || Object.keys(fields).length === 0) {
856
+ throw new TypeError("fieldRateLimit({ fields }): fields maps each field name to count to its limit, and holds at least one");
857
+ }
858
+ const rules = new Map;
859
+ for (const [name, rule] of Object.entries(fields)) {
860
+ const wrapped = typeof rule === "object" && rule !== null && "limit" in rule && typeof rule.limit === "object";
861
+ const limit = wrapped ? rule.limit : rule;
862
+ if (typeof limit?.consume !== "function") {
863
+ throw new TypeError(`fieldRateLimit({ fields: { ${name} } }): a limit has a consume(key, cost) method, or is { limit, single? }`);
864
+ }
865
+ rules.set(name, {
866
+ limit,
867
+ single: wrapped && rule.single === true
868
+ });
869
+ }
870
+ return rules;
871
+ }
872
+ function checked(options) {
873
+ const { ipv6Prefix } = options;
874
+ if (ipv6Prefix !== undefined) {
875
+ if (!Number.isInteger(ipv6Prefix) || ipv6Prefix < 0 || ipv6Prefix > 128) {
876
+ throw new TypeError(`fieldRateLimit: ipv6Prefix must be a whole number from 0 to 128, not ${String(ipv6Prefix)}`);
877
+ }
878
+ if (options.key !== undefined) {
879
+ throw new TypeError("fieldRateLimit: ipv6Prefix applies to the default key, and a key of your own was given. Drop one, or group the address in your key.");
880
+ }
881
+ }
882
+ const { code } = options;
883
+ if (code !== undefined && (typeof code !== "string" || code === "")) {
884
+ throw new TypeError("fieldRateLimit: code is a non-empty string");
885
+ }
886
+ }
887
+ function refusal(message, code, status, extensions = {}, headers) {
888
+ return {
889
+ errors: [
890
+ new GraphQLError2(message, {
891
+ extensions: {
892
+ code,
893
+ ...extensions,
894
+ http: headers === undefined ? { status } : { status, headers }
895
+ }
896
+ })
897
+ ]
898
+ };
899
+ }
900
+ function fieldRateLimit(options) {
901
+ const rules = rulesOf(options.fields);
902
+ checked(options);
903
+ const names = new Set(rules.keys());
904
+ const singles = new Set([...rules].filter(([, r]) => r.single).map(([n]) => n));
905
+ const code = options.code ?? DEFAULT_LIMIT_CODE;
906
+ const prefix = options.ipv6Prefix;
907
+ const keyOf = options.key ?? ((ctx) => {
908
+ const { ip } = ctx;
909
+ return prefix === undefined || ip === undefined ? ip : ipv6Network(ip, prefix);
910
+ });
911
+ return {
912
+ async onExecute({ args, setResultAndStopExecution }) {
913
+ const operation = getOperationAST2(args.document, args.operationName);
914
+ if (!operation)
915
+ return;
916
+ const counts = countSelections(args.document, operation.selectionSet, names, singles);
917
+ if (counts.size === 0)
918
+ return;
919
+ for (const [name, selected] of counts) {
920
+ if (rules.get(name)?.single && selected.distinct.size > 1) {
921
+ return setResultAndStopExecution(refusal(`${name} may be selected once per operation`, "FIELD_SELECTED_ONCE", 400));
922
+ }
923
+ }
924
+ const who = await keyOf(args.contextValue);
925
+ if (who === undefined)
926
+ return;
927
+ for (const [name, selected] of counts) {
928
+ const decision = await rules.get(name).limit.consume(`${name}:${who}`, selected.count);
929
+ if (!decision.allowed) {
930
+ const wait = Math.ceil(decision.retryAfter / 1000);
931
+ const retryAfter = Number.isFinite(wait) ? Math.max(1, wait) : 1;
932
+ return setResultAndStopExecution(refusal("Too many attempts, try again later", code, 429, { retryAfter }, { "retry-after": String(retryAfter) }));
933
+ }
934
+ }
935
+ }
936
+ };
937
+ }
938
+ // src/endpoint.ts
939
+ var DEFAULT_BODY_LIMIT = 1048576;
940
+ function declareEndpoint(app, path, handler, bodyLimit, socket) {
941
+ const route = app;
942
+ route.get(path, handler);
943
+ const inherited = app.routes.at(-1)?.bodyLimit;
944
+ const own = bodyLimit ?? (inherited === undefined ? DEFAULT_BODY_LIMIT : undefined);
945
+ if (own === undefined)
946
+ route.post(path, handler);
947
+ else
948
+ route.post(path, { bodyLimit: own }, handler);
949
+ if (socket !== undefined) {
950
+ route.ws(socket.path, socket.middleware, socket.handlers);
951
+ }
952
+ }
953
+
631
954
  // src/ws-operations.ts
632
955
  import { startOperation } from "@alxia/core";
633
- import { getOperationAST as getOperationAST2 } from "graphql";
956
+ import { getOperationAST as getOperationAST3 } from "graphql";
634
957
 
635
958
  class SocketOperations {
636
959
  #ctx;
@@ -640,7 +963,7 @@ class SocketOperations {
640
963
  }
641
964
  begin(id, document, operationName) {
642
965
  this.end(id);
643
- const operation = getOperationAST2(document, operationName);
966
+ const operation = getOperationAST3(document, operationName);
644
967
  if (operation === undefined || operation === null)
645
968
  return;
646
969
  const end = startOperation(this.#ctx, {
@@ -831,41 +1154,14 @@ function graphql(app, options) {
831
1154
  graphiql,
832
1155
  sandbox,
833
1156
  ws = false,
834
- maxTokens,
835
- maxNesting,
836
- parseCache,
837
1157
  bodyLimit,
838
1158
  ...yogaOptions
839
1159
  } = options;
840
- const limits = resolveLimits(maxTokens, maxNesting, parseCache, yogaOptions);
841
- const page = graphiql ?? true;
842
- const yogaAt = yogaServers({
843
- ...yogaOptions,
844
- ...yogaOptions.logging === undefined ? { logging: "warn" } : {},
845
- ...untrustedRequestId(yogaOptions),
846
- plugins: [
847
- limitsParsing(limits.tokens, limits.depth),
848
- ...yogaOptions.plugins ?? [],
849
- reportsOperations()
850
- ],
851
- cors,
852
- graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
853
- }, yogaOptions.parserAndValidationCache === undefined ? () => parseCaches(parseCache) : undefined);
1160
+ const yogaAt = yogaFor(yogaOptions, { cors, ide, graphiql });
854
1161
  const handler = graphqlHandler(yogaAt, ide === "apollo-sandbox" ? sandbox ?? {} : false);
855
1162
  declareEndpoint(app, path, handler, bodyLimit, ws === false ? undefined : graphqlSocket(yogaAt, path, ws === true ? {} : ws));
856
1163
  return app;
857
1164
  }
858
- function untrustedRequestId(options) {
859
- const { requestId } = options;
860
- if (requestId === undefined)
861
- return { requestId: false };
862
- if (requestId === true)
863
- return { requestId: { trustHeader: false } };
864
- if (typeof requestId === "object" && requestId !== null) {
865
- return { requestId: { trustHeader: false, ...requestId } };
866
- }
867
- return {};
868
- }
869
1165
  // src/once-per-request.ts
870
1166
  var caches = new WeakMap;
871
1167
  function oncePerRequest(request, key, load) {
@@ -913,11 +1209,14 @@ export {
913
1209
  SANDBOX_POLICY,
914
1210
  boundedStream,
915
1211
  clearRequestCache,
1212
+ fieldRateLimit,
916
1213
  freshPerMutation,
917
1214
  graphql,
1215
+ graphqlExecutor,
1216
+ limitFromStore,
918
1217
  oncePerRequest,
919
1218
  renderSandbox
920
1219
  };
921
1220
 
922
- //# debugId=B869BB3633C5D98964756E2164756E21
1221
+ //# debugId=21672915486E17F964756E2164756E21
923
1222
  //# sourceMappingURL=index.js.map