graphql-query-merger 1.1.1 → 2.0.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/README.md CHANGED
@@ -1,231 +1,252 @@
1
- # GraphQL Query Merger
2
-
3
- **GraphQL Query Merger** is a utility library designed to merge multiple GraphQL queries into a single, cohesive query. This helps developers streamline their GraphQL requests by combining related operations efficiently, avoiding redundancy and improving maintainability.
4
-
5
- ---
6
-
7
- ## Table of Contents
8
-
9
- - [GraphQL Query Merger](#graphql-query-merger)
10
- - [Table of Contents](#table-of-contents)
11
- - [Features](#features)
12
- - [Installation](#installation)
13
- - [Usage](#usage)
14
- - [Importing the Library](#importing-the-library)
15
- - [Combining Queries](#combining-queries)
16
- - [Basic Query Combination](#basic-query-combination)
17
- - [Combining Queries with Variables](#combining-queries-with-variables)
18
- - [Conditional Query Combination](#conditional-query-combination)
19
- - [Notes](#notes)
20
-
21
- ---
22
-
23
- ## Features
24
-
25
- - **Merge GraphQL Queries**: Seamlessly combine multiple queries into one.
26
- - **Variable Deduplication**: Automatically handles conflicts by renaming variables.
27
- - **Supports Conditional Queries**: Add queries dynamically based on runtime logic.
28
- - **Customizable Query Names**: Optionally name the resulting query.
29
-
30
- ---
31
-
32
- ## Installation
33
-
34
- To install the library, use npm or yarn:
35
-
36
- ```bash
37
- npm install graphql-query-merger graphql
38
- ```
39
-
40
- > **Note**: `graphql-query-merger` has a peer dependency on `graphql`. Ensure that the `graphql` package is installed alongside it.
41
-
42
- ---
43
-
44
- ## Usage
45
-
46
- ### Importing the Library
47
-
48
- To use the library, import the necessary functions:
49
-
50
- ```javascript
51
- const { mergeQueries } = require('graphql-query-merger');
52
- const { print } = require('graphql');
53
- const { gql } = require('graphql-tag');
54
- ```
55
-
56
- - **`mergeQueries()`**: Initializes a new query merger instance.
57
- - **`push(query, variables?)`**: Adds a query to the merger. Optionally accepts a variables object.
58
- - **`print()`**: Converts the resulting query to a printable string format.
59
-
60
- ### Combining Queries
61
-
62
- #### Basic Query Combination
63
-
64
- You can combine queries written as strings or `gql`-tagged templates.
65
-
66
- ```javascript
67
- const query_1 = /* GraphQL */ `
68
- {
69
- user {
70
- id
71
- name
72
- }
73
- }
74
- `;
75
-
76
- const query_2 = /* GraphQL */ gql`
77
- {
78
- post {
79
- id
80
- title
81
- }
82
- }
83
- `;
84
-
85
- const combined = mergeQueries().push(query_1).push(query_2);
86
-
87
- console.log(print(combined.query));
88
- ```
89
-
90
- **Output**:
91
-
92
- ```graphql
93
- {
94
- user {
95
- id
96
- name
97
- }
98
- post {
99
- id
100
- title
101
- }
102
- }
103
- ```
104
-
105
- #### Combining Queries with Variables
106
-
107
- When combining queries that include variables, the library automatically renames conflicting variable names to maintain uniqueness.
108
-
109
- ```javascript
110
- const query_1 = /* GraphQL */ gql`
111
- query ($id: ID!) {
112
- user(id: $id) {
113
- id
114
- name
115
- }
116
- }
117
- `;
118
-
119
- const query_2 = /* GraphQL */ `
120
- query ($id: ID!) {
121
- post(id: $id) {
122
- id
123
- title
124
- }
125
- }
126
- `;
127
-
128
- const combined = mergeQueries().push(query_1, { id: 1 }).push(query_2, { id: 2 });
129
-
130
- console.log(print(combined.query));
131
- console.log(combined.variables);
132
- ```
133
-
134
- **Output**:
135
-
136
- ```graphql
137
- query ($id_1: ID!, $id_2: ID!) {
138
- user(id: $id_1) {
139
- id
140
- name
141
- }
142
- post(id: $id_2) {
143
- id
144
- title
145
- }
146
- }
147
- ```
148
-
149
- **Variables**:
150
-
151
- ```json
152
- {
153
- "id_1": 1,
154
- "id_2": 2
155
- }
156
- ```
157
-
158
- - **Automatic Variable Renaming**: Conflicting variable names (`id`) are renamed (`id_1`, `id_2`).
159
-
160
- #### Conditional Query Combination
161
-
162
- You can dynamically add queries based on runtime conditions.
163
-
164
- ```javascript
165
- const combined = mergeQueries('optionalQueryName');
166
-
167
- combined.push(
168
- /* GraphQL */ `
169
- query ($email: String!) {
170
- user(email: $email) {
171
- id
172
- name
173
- }
174
- }
175
- `,
176
- { email: 'example@test.com' },
177
- );
178
-
179
- if (true) {
180
- combined.push(
181
- /* GraphQL */ `
182
- query ($id: ID!) {
183
- post(id: $id) {
184
- id
185
- title
186
- date
187
- }
188
- }
189
- `,
190
- { id: 10 },
191
- );
192
- }
193
-
194
- console.log(print(combined.query));
195
- console.log(combined.variables);
196
- ```
197
-
198
- **Output**:
199
-
200
- ```graphql
201
- query optionalQueryName($email_1: String!, $id_2: ID!) {
202
- user(email: $email_1) {
203
- id
204
- name
205
- }
206
- post(id: $id_2) {
207
- id
208
- title
209
- date
210
- }
211
- }
212
- ```
213
-
214
- **Variables**:
215
-
216
- ```json
217
- {
218
- "email_1": "example@test.com",
219
- "id_2": 10
220
- }
221
- ```
222
-
223
- ---
224
-
225
- ## Notes
226
-
227
- 1. **Variable Scope**: The library renames variables in the combined query to ensure no conflicts occur between different queries.
228
- 2. **Query Formats**: Queries can be provided as:
229
- - String literals
230
- - `gql`-tagged templates (recommended for syntax highlighting and validation).
231
- 3. **Error Handling**: Ensure all variables required by the queries are provided when invoking `push()`. Missing variables will lead to runtime errors.
1
+ # GraphQL Query Merger
2
+
3
+ **GraphQL Query Merger** is a utility library designed to merge multiple GraphQL queries into a single, cohesive query. This helps developers streamline their GraphQL requests by combining related operations efficiently, avoiding redundancy and improving maintainability.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [GraphQL Query Merger](#graphql-query-merger)
10
+ - [Table of Contents](#table-of-contents)
11
+ - [Features](#features)
12
+ - [Installation](#installation)
13
+ - [Usage](#usage)
14
+ - [Importing the Library](#importing-the-library)
15
+ - [Using `getQueryString()` Instead of `print`](#using-getquerystring-instead-of-print)
16
+ - [Combining Queries](#combining-queries)
17
+ - [Basic Query Combination](#basic-query-combination)
18
+ - [Combining Queries with Variables](#combining-queries-with-variables)
19
+ - [Conditional Query Combination](#conditional-query-combination)
20
+ - [Notes](#notes)
21
+ - [Development](#development)
22
+
23
+ ---
24
+
25
+ ## Features
26
+
27
+ - **Merge GraphQL Queries**: Seamlessly combine multiple queries into one.
28
+ - **Variable and Fragment Renaming**: Gives each input's definitions unique names.
29
+ - **Supports Conditional Queries**: Add queries dynamically based on runtime logic.
30
+ - **Customizable Query Names**: Optionally name the resulting query.
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ To install the library, use npm or yarn:
37
+
38
+ ```bash
39
+ npm install graphql-query-merger graphql
40
+ ```
41
+
42
+ > **Note**: `graphql-query-merger` has a peer dependency on `graphql`. Ensure that the `graphql` package is installed alongside it.
43
+
44
+ ---
45
+
46
+ ## Usage
47
+
48
+ ### Importing the Library
49
+
50
+ To use the library, import the necessary functions:
51
+
52
+ ```javascript
53
+ const { mergeQueries } = require('graphql-query-merger');
54
+ const { gql } = require('graphql-tag');
55
+ ```
56
+
57
+ - **`mergeQueries()`**: Initializes a new query merger instance.
58
+ - **`push(query, variables?)`**: Adds a query to the merger. Optionally accepts a variables object.
59
+ - **`getQueryString()`**: Merger method that returns the combined query string. This is a direct replacement for `print(merger.query)` and you do not need to import `print` from `graphql` if you use this method.
60
+ - **`query`** and **`variables`**: The merged GraphQL `DocumentNode` and variables object. TypeScript declarations are included.
61
+
62
+ ### Using `getQueryString()` Instead of `print`
63
+
64
+ You can get the combined query string using the merger's `getQueryString()` method, instead of using `print` from `graphql`:
65
+
66
+ ```javascript
67
+ const combined = mergeQueries().push(query_1).push(query_2);
68
+
69
+ console.log(combined.getQueryString()); // Equivalent to print(combined.query)
70
+ ```
71
+
72
+ This simplifies your code and avoids the need to import `print` separately.
73
+
74
+ ### Combining Queries
75
+
76
+ #### Basic Query Combination
77
+
78
+ You can combine queries written as strings or `gql`-tagged templates.
79
+
80
+ ```javascript
81
+ const query_1 = /* GraphQL */ `
82
+ {
83
+ user {
84
+ id
85
+ name
86
+ }
87
+ }
88
+ `;
89
+
90
+ const query_2 = /* GraphQL */ gql`
91
+ {
92
+ post {
93
+ id
94
+ title
95
+ }
96
+ }
97
+ `;
98
+
99
+ const combined = mergeQueries().push(query_1).push(query_2);
100
+
101
+ console.log(combined.getQueryString());
102
+ ```
103
+
104
+ **Output**:
105
+
106
+ ```graphql
107
+ {
108
+ user {
109
+ id
110
+ name
111
+ }
112
+ post {
113
+ id
114
+ title
115
+ }
116
+ }
117
+ ```
118
+
119
+ #### Combining Queries with Variables
120
+
121
+ When combining queries that include variables, the library renames each declared variable to maintain uniqueness.
122
+
123
+ ```javascript
124
+ const query_1 = /* GraphQL */ gql`
125
+ query ($id: ID!) {
126
+ user(id: $id) {
127
+ id
128
+ name
129
+ }
130
+ }
131
+ `;
132
+
133
+ const query_2 = /* GraphQL */ `
134
+ query ($id: ID!) {
135
+ post(id: $id) {
136
+ id
137
+ title
138
+ }
139
+ }
140
+ `;
141
+
142
+ const combined = mergeQueries().push(query_1, { id: 1 }).push(query_2, { id: 2 });
143
+
144
+ console.log(combined.getQueryString());
145
+ console.log(combined.variables);
146
+ ```
147
+
148
+ **Output**:
149
+
150
+ ```graphql
151
+ query ($id_1: ID!, $id_2: ID!) {
152
+ user(id: $id_1) {
153
+ id
154
+ name
155
+ }
156
+ post(id: $id_2) {
157
+ id
158
+ title
159
+ }
160
+ }
161
+ ```
162
+
163
+ **Variables**:
164
+
165
+ ```json
166
+ {
167
+ "id_1": 1,
168
+ "id_2": 2
169
+ }
170
+ ```
171
+
172
+ - **Automatic Variable Renaming**: Variable names (`id`) are renamed (`id_1`, `id_2`).
173
+
174
+ #### Conditional Query Combination
175
+
176
+ You can dynamically add queries based on runtime conditions.
177
+
178
+ ```javascript
179
+ const combined = mergeQueries('optionalQueryName');
180
+
181
+ combined.push(
182
+ /* GraphQL */ `
183
+ query ($email: String!) {
184
+ user(email: $email) {
185
+ id
186
+ name
187
+ }
188
+ }
189
+ `,
190
+ { email: 'example@test.com' },
191
+ );
192
+
193
+ if (true) {
194
+ combined.push(
195
+ /* GraphQL */ `
196
+ query ($id: ID!) {
197
+ post(id: $id) {
198
+ id
199
+ title
200
+ date
201
+ }
202
+ }
203
+ `,
204
+ { id: 10 },
205
+ );
206
+ }
207
+
208
+ console.log(combined.getQueryString());
209
+ console.log(combined.variables);
210
+ ```
211
+
212
+ **Output**:
213
+
214
+ ```graphql
215
+ query optionalQueryName($email_1: String!, $id_2: ID!) {
216
+ user(email: $email_1) {
217
+ id
218
+ name
219
+ }
220
+ post(id: $id_2) {
221
+ id
222
+ title
223
+ date
224
+ }
225
+ }
226
+ ```
227
+
228
+ **Variables**:
229
+
230
+ ```json
231
+ {
232
+ "email_1": "example@test.com",
233
+ "id_2": 10
234
+ }
235
+ ```
236
+
237
+ ---
238
+
239
+ ## Notes
240
+
241
+ 1. **Inputs**: Each `push()` accepts a GraphQL string or `DocumentNode` containing exactly one operation. Referenced variables and fragments must be defined in that document; fragments may appear before or after their references. Duplicate definitions are rejected.
242
+ 2. **Operation types**: Queries and mutations can only be combined with operations of the same type. A subscription can be added alone, but not combined with another operation.
243
+ 3. **Operation directives**: Operations with directives are rejected because moving or dropping them could change their meaning. Directives on fields and fragments are preserved.
244
+ 4. **Field conflicts**: Selections are combined as written; the library does not automatically alias conflicting fields or validate the result against a schema. Use aliases where necessary. GraphQL can coalesce identical fields, so repeated mutation fields may execute only once unless given distinct aliases.
245
+ 5. **Variables**: Declared variables and fragment names receive a suffix for each successfully added document. Extra variable values are retained, but `push()` rejects name collisions rather than overwriting values. Required variables are not checked; GraphQL execution validates them.
246
+ 6. **Errors**: Accessing `query` or calling `getQueryString()` before adding an operation throws. A failed `push()` does not alter the merger.
247
+
248
+ ## Development
249
+
250
+ The development tools require Node.js 22.12 or later within Node 22, Node 24, or Node 26 and later. This requirement does not apply to consumers of the built package.
251
+
252
+ Run `npm test`, `npm run typecheck`, and `npm run build` to validate changes.
@@ -0,0 +1,15 @@
1
+ import { type DocumentNode } from 'graphql';
2
+ type Variables = Record<string, unknown>;
3
+ declare class GraphQLQueryMerger {
4
+ private readonly operationName;
5
+ private readonly documents;
6
+ private readonly variableNames;
7
+ private operationType;
8
+ constructor(operationName: string);
9
+ push(document: string | DocumentNode, variables?: Variables): this;
10
+ get query(): DocumentNode;
11
+ getQueryString(): string;
12
+ get variables(): Variables;
13
+ }
14
+ declare const mergeQueries: (operationName?: string) => GraphQLQueryMerger;
15
+ export { mergeQueries };
package/dist/index.es.js CHANGED
@@ -1,96 +1,107 @@
1
- import { parse as p, Kind as t, print as d, visit as m } from "graphql";
2
- const E = (c, a, s) => {
3
- const o = {}, l = {}, r = m(c, {
4
- [t.VARIABLE_DEFINITION](e) {
5
- const n = e.variable.name.value, i = `${n}_${s}`;
6
- return o[n] = i, {
7
- ...e,
8
- variable: {
9
- ...e.variable,
10
- name: { kind: t.NAME, value: i }
11
- }
12
- };
1
+ import { assertName as f, parse as u, Kind as o, print as d, visit as v } from "graphql";
2
+ function w(p, n, m, s) {
3
+ const r = new Map(
4
+ (n.variableDefinitions ?? []).map(({ variable: e }) => [
5
+ e.name.value,
6
+ `${e.name.value}_${s}`
7
+ ])
8
+ ), t = p.definitions.filter(
9
+ (e) => e.kind === o.FRAGMENT_DEFINITION
10
+ ), l = new Map(
11
+ t.map(({ name: e }) => [e.value, `${e.value}_${s}`])
12
+ );
13
+ if (r.size !== (n.variableDefinitions ?? []).length)
14
+ throw new Error("Duplicate variable definition in the provided operation.");
15
+ if (l.size !== t.length)
16
+ throw new Error("Duplicate fragment definition in the provided document.");
17
+ const h = new Set(r.values()), c = v(p, {
18
+ [o.VARIABLE](e) {
19
+ const a = r.get(e.name.value);
20
+ if (!a)
21
+ throw new Error(`Variable "$${e.name.value}" is not defined in the operation.`);
22
+ return { ...e, name: { ...e.name, value: a } };
13
23
  },
14
- [t.VARIABLE](e) {
15
- const n = e.name.value, i = o[n] || n;
16
- return {
17
- ...e,
18
- name: { kind: t.NAME, value: i }
19
- };
24
+ [o.FRAGMENT_DEFINITION](e) {
25
+ const a = l.get(e.name.value);
26
+ return a ? { ...e, name: { ...e.name, value: a } } : void 0;
20
27
  },
21
- [t.FRAGMENT_DEFINITION](e) {
22
- const n = e.name.value, i = `${n}_${s}`;
23
- return l[n] = i, {
24
- ...e,
25
- name: { kind: t.NAME, value: i }
26
- };
27
- },
28
- [t.FRAGMENT_SPREAD](e) {
29
- const n = e.name.value, i = l[n] || n;
30
- return {
31
- ...e,
32
- name: { kind: t.NAME, value: i }
33
- };
34
- },
35
- [t.DIRECTIVE](e) {
36
- return m(e, {
37
- [t.VARIABLE](n) {
38
- const i = n.name.value, N = o[i] || i;
39
- return {
40
- ...n,
41
- name: { kind: t.NAME, value: N }
42
- };
43
- }
44
- });
28
+ [o.FRAGMENT_SPREAD](e) {
29
+ const a = l.get(e.name.value);
30
+ if (!a)
31
+ throw new Error(`Fragment "${e.name.value}" is not defined in the document.`);
32
+ return { ...e, name: { ...e.name, value: a } };
45
33
  }
46
- }), u = {};
47
- for (const [e, n] of Object.entries(a)) {
48
- const i = o[e] || e;
49
- u[i] = n;
50
- }
51
- return { document: r, variables: u };
52
- };
53
- class h {
54
- constructor(a) {
55
- this.operationName = a, this.documents = [], this.internalVariables = [], this.uniqueIdCounter = 1, this.operationType = null;
34
+ }), i = Object.entries(m).map(([e, a]) => [
35
+ r.get(e) ?? e,
36
+ a
37
+ ]);
38
+ if (new Set(i.map(([e]) => e)).size !== i.length || Object.keys(m).some(
39
+ (e) => !r.has(e) && h.has(e)
40
+ ))
41
+ throw new Error("Variable names collide after renaming.");
42
+ return { document: c, variables: Object.fromEntries(i) };
43
+ }
44
+ class E {
45
+ constructor(n) {
46
+ this.documents = [], this.variableNames = /* @__PURE__ */ new Set(), this.operationType = null, n && f(n), this.operationName = n;
56
47
  }
57
- push(a, s = {}) {
58
- typeof a == "string" && (a = p(a));
59
- const o = this.uniqueIdCounter++, { document: l, variables: r } = E(a, s, o), u = l.definitions.filter(
60
- (n) => n.kind === t.OPERATION_DEFINITION
48
+ push(n, m = {}) {
49
+ var c;
50
+ const s = typeof n == "string" ? u(n) : n, r = s.definitions.filter(
51
+ (i) => i.kind === o.OPERATION_DEFINITION
61
52
  );
62
- if (u.length === 0)
63
- throw new Error(
64
- "No operation definition found in the provided document."
65
- );
66
- const e = u[0].operation;
67
- if (this.operationType && this.operationType !== e)
53
+ if (r.length === 0)
54
+ throw new Error("No operation definition found in the provided document.");
55
+ if (r.length > 1)
56
+ throw new Error("Cannot merge a document containing multiple operations.");
57
+ const t = r[0];
58
+ if ((c = t.directives) != null && c.length)
59
+ throw new Error("Cannot merge an operation with directives.");
60
+ if (this.operationType && this.operationType !== t.operation)
68
61
  throw new Error(
69
- `Cannot merge different operation types: ${this.operationType} and ${e}.`
62
+ `Cannot merge different operation types: ${this.operationType} and ${t.operation}.`
70
63
  );
71
- return this.operationType = e, this.documents.push(l), this.internalVariables.push(r), this;
64
+ if (this.operationType === "subscription")
65
+ throw new Error("Cannot merge multiple subscription operations.");
66
+ const l = w(
67
+ s,
68
+ t,
69
+ m,
70
+ this.documents.length + 1
71
+ ), h = /* @__PURE__ */ new Set([
72
+ ...Object.keys(l.variables),
73
+ ...(t.variableDefinitions ?? []).map(
74
+ ({ variable: i }) => `${i.name.value}_${this.documents.length + 1}`
75
+ )
76
+ ]);
77
+ for (const i of h)
78
+ if (this.variableNames.has(i))
79
+ throw new Error(`Variable name "${i}" collides with an existing variable.`);
80
+ this.operationType = t.operation, this.documents.push(l);
81
+ for (const i of h)
82
+ this.variableNames.add(i);
83
+ return this;
72
84
  }
73
85
  get query() {
74
- const a = [], s = [], o = [];
75
- for (const l of this.documents)
76
- for (const r of l.definitions)
77
- r.kind === t.OPERATION_DEFINITION ? (a.push(
78
- ...r.variableDefinitions || []
79
- ), s.push(...r.selectionSet.selections)) : r.kind === t.FRAGMENT_DEFINITION && o.push(r);
86
+ if (!this.operationType)
87
+ throw new Error("Cannot create a query without an operation.");
88
+ const n = [], m = [], s = [];
89
+ for (const { document: r } of this.documents)
90
+ for (const t of r.definitions)
91
+ t.kind === o.OPERATION_DEFINITION ? (n.push(...t.variableDefinitions ?? []), m.push(...t.selectionSet.selections)) : t.kind === o.FRAGMENT_DEFINITION && s.push(t);
80
92
  return {
81
- kind: t.DOCUMENT,
93
+ kind: o.DOCUMENT,
82
94
  definitions: [
83
95
  {
84
- kind: t.OPERATION_DEFINITION,
96
+ kind: o.OPERATION_DEFINITION,
85
97
  operation: this.operationType,
86
- name: { kind: t.NAME, value: this.operationName || "" },
87
- variableDefinitions: a,
88
- selectionSet: {
89
- kind: t.SELECTION_SET,
90
- selections: s
91
- }
98
+ ...this.operationName && {
99
+ name: { kind: o.NAME, value: this.operationName }
100
+ },
101
+ variableDefinitions: n,
102
+ selectionSet: { kind: o.SELECTION_SET, selections: m }
92
103
  },
93
- ...o
104
+ ...s
94
105
  ]
95
106
  };
96
107
  }
@@ -98,10 +109,12 @@ class h {
98
109
  return d(this.query);
99
110
  }
100
111
  get variables() {
101
- return Object.assign({}, ...this.internalVariables);
112
+ return Object.fromEntries(
113
+ this.documents.flatMap(({ variables: n }) => Object.entries(n))
114
+ );
102
115
  }
103
116
  }
104
- const f = (c = "") => new h(c);
117
+ const N = (p = "") => new E(p);
105
118
  export {
106
- f as mergeQueries
119
+ N as mergeQueries
107
120
  };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(a,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],e):(a=typeof globalThis<"u"?globalThis:a||self,e(a["graphql-query-merger"]={},a.graphql))})(this,function(a,e){"use strict";const N=(m,o,u)=>{const s={},d={},r=e.visit(m,{[e.Kind.VARIABLE_DEFINITION](n){const i=n.variable.name.value,t=`${i}_${u}`;return s[i]=t,{...n,variable:{...n.variable,name:{kind:e.Kind.NAME,value:t}}}},[e.Kind.VARIABLE](n){const i=n.name.value,t=s[i]||i;return{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.FRAGMENT_DEFINITION](n){const i=n.name.value,t=`${i}_${u}`;return d[i]=t,{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.FRAGMENT_SPREAD](n){const i=n.name.value,t=d[i]||i;return{...n,name:{kind:e.Kind.NAME,value:t}}},[e.Kind.DIRECTIVE](n){return e.visit(n,{[e.Kind.VARIABLE](i){const t=i.name.value,E=s[t]||t;return{...i,name:{kind:e.Kind.NAME,value:E}}}})}}),c={};for(const[n,i]of Object.entries(o)){const t=s[n]||n;c[t]=i}return{document:r,variables:c}};class f{constructor(o){this.operationName=o,this.documents=[],this.internalVariables=[],this.uniqueIdCounter=1,this.operationType=null}push(o,u={}){typeof o=="string"&&(o=e.parse(o));const s=this.uniqueIdCounter++,{document:d,variables:r}=N(o,u,s),c=d.definitions.filter(i=>i.kind===e.Kind.OPERATION_DEFINITION);if(c.length===0)throw new Error("No operation definition found in the provided document.");const n=c[0].operation;if(this.operationType&&this.operationType!==n)throw new Error(`Cannot merge different operation types: ${this.operationType} and ${n}.`);return this.operationType=n,this.documents.push(d),this.internalVariables.push(r),this}get query(){const o=[],u=[],s=[];for(const d of this.documents)for(const r of d.definitions)r.kind===e.Kind.OPERATION_DEFINITION?(o.push(...r.variableDefinitions||[]),u.push(...r.selectionSet.selections)):r.kind===e.Kind.FRAGMENT_DEFINITION&&s.push(r);return{kind:e.Kind.DOCUMENT,definitions:[{kind:e.Kind.OPERATION_DEFINITION,operation:this.operationType,name:{kind:e.Kind.NAME,value:this.operationName||""},variableDefinitions:o,selectionSet:{kind:e.Kind.SELECTION_SET,selections:u}},...s]}}getQueryString(){return e.print(this.query)}get variables(){return Object.assign({},...this.internalVariables)}}const l=(m="")=>new f(m);a.mergeQueries=l,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
1
+ (function(m,n){typeof exports=="object"&&typeof module<"u"?n(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],n):(m=typeof globalThis<"u"?globalThis:m||self,n(m["graphql-query-merger"]={},m.graphql))})(this,(function(m,n){"use strict";function l(d,t,f,a){const o=new Map((t.variableDefinitions??[]).map(({variable:e})=>[e.name.value,`${e.name.value}_${a}`])),i=d.definitions.filter(e=>e.kind===n.Kind.FRAGMENT_DEFINITION),u=new Map(i.map(({name:e})=>[e.value,`${e.value}_${a}`]));if(o.size!==(t.variableDefinitions??[]).length)throw new Error("Duplicate variable definition in the provided operation.");if(u.size!==i.length)throw new Error("Duplicate fragment definition in the provided document.");const c=new Set(o.values()),p=n.visit(d,{[n.Kind.VARIABLE](e){const s=o.get(e.name.value);if(!s)throw new Error(`Variable "$${e.name.value}" is not defined in the operation.`);return{...e,name:{...e.name,value:s}}},[n.Kind.FRAGMENT_DEFINITION](e){const s=u.get(e.name.value);return s?{...e,name:{...e.name,value:s}}:void 0},[n.Kind.FRAGMENT_SPREAD](e){const s=u.get(e.name.value);if(!s)throw new Error(`Fragment "${e.name.value}" is not defined in the document.`);return{...e,name:{...e.name,value:s}}}}),r=Object.entries(f).map(([e,s])=>[o.get(e)??e,s]);if(new Set(r.map(([e])=>e)).size!==r.length||Object.keys(f).some(e=>!o.has(e)&&c.has(e)))throw new Error("Variable names collide after renaming.");return{document:p,variables:Object.fromEntries(r)}}class h{constructor(t){this.documents=[],this.variableNames=new Set,this.operationType=null,t&&n.assertName(t),this.operationName=t}push(t,f={}){var p;const a=typeof t=="string"?n.parse(t):t,o=a.definitions.filter(r=>r.kind===n.Kind.OPERATION_DEFINITION);if(o.length===0)throw new Error("No operation definition found in the provided document.");if(o.length>1)throw new Error("Cannot merge a document containing multiple operations.");const i=o[0];if((p=i.directives)!=null&&p.length)throw new Error("Cannot merge an operation with directives.");if(this.operationType&&this.operationType!==i.operation)throw new Error(`Cannot merge different operation types: ${this.operationType} and ${i.operation}.`);if(this.operationType==="subscription")throw new Error("Cannot merge multiple subscription operations.");const u=l(a,i,f,this.documents.length+1),c=new Set([...Object.keys(u.variables),...(i.variableDefinitions??[]).map(({variable:r})=>`${r.name.value}_${this.documents.length+1}`)]);for(const r of c)if(this.variableNames.has(r))throw new Error(`Variable name "${r}" collides with an existing variable.`);this.operationType=i.operation,this.documents.push(u);for(const r of c)this.variableNames.add(r);return this}get query(){if(!this.operationType)throw new Error("Cannot create a query without an operation.");const t=[],f=[],a=[];for(const{document:o}of this.documents)for(const i of o.definitions)i.kind===n.Kind.OPERATION_DEFINITION?(t.push(...i.variableDefinitions??[]),f.push(...i.selectionSet.selections)):i.kind===n.Kind.FRAGMENT_DEFINITION&&a.push(i);return{kind:n.Kind.DOCUMENT,definitions:[{kind:n.Kind.OPERATION_DEFINITION,operation:this.operationType,...this.operationName&&{name:{kind:n.Kind.NAME,value:this.operationName}},variableDefinitions:t,selectionSet:{kind:n.Kind.SELECTION_SET,selections:f}},...a]}}getQueryString(){return n.print(this.query)}get variables(){return Object.fromEntries(this.documents.flatMap(({variables:t})=>Object.entries(t)))}}const v=(d="")=>new h(d);m.mergeQueries=v,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,30 +1,33 @@
1
- {
2
- "name": "graphql-query-merger",
3
- "version": "1.1.1",
4
- "description": "Merge and unify multiple GraphQL queries into a single operation with field and variable conflict resolution.",
5
- "main": "dist/index.umd.js",
6
- "module": "dist/index.es.js",
7
- "types": "dist/index.d.ts",
8
- "files": [
9
- "dist"
10
- ],
11
- "scripts": {
12
- "build": "vite build",
13
- "test": "jest"
14
- },
15
- "keywords": [
16
- "graphql",
17
- "query",
18
- "merge"
19
- ],
20
- "author": "A. Juárez",
21
- "license": "ISC",
22
- "devDependencies": {
23
- "@babel/preset-env": "^7.26.0",
24
- "babel-jest": "^29.7.0",
25
- "graphql": "^16.9.0",
26
- "graphql-tag": "^2.12.6",
27
- "jest": "^29.7.0",
28
- "vite": "^5.4.11"
29
- }
30
- }
1
+ {
2
+ "name": "graphql-query-merger",
3
+ "version": "2.0.0",
4
+ "description": "Merge multiple GraphQL queries into one operation, preserving field selections and renaming variables and fragments; conflicting fields require aliases.",
5
+ "main": "dist/index.umd.js",
6
+ "module": "dist/index.es.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "vite build && tsc -p tsconfig.build.json",
13
+ "typecheck": "tsc --noEmit",
14
+ "test": "vitest run"
15
+ },
16
+ "keywords": [
17
+ "graphql",
18
+ "query",
19
+ "merge"
20
+ ],
21
+ "author": "A. Juárez",
22
+ "license": "ISC",
23
+ "peerDependencies": {
24
+ "graphql": "^16.9.0"
25
+ },
26
+ "devDependencies": {
27
+ "graphql": "^16.9.0",
28
+ "graphql-tag": "^2.12.6",
29
+ "typescript": "^5.7.2",
30
+ "vite": "^6.4.6",
31
+ "vitest": "^5.1.2"
32
+ }
33
+ }