@constructive-io/graphql-codegen 2.17.11
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/LICENSE +23 -0
- package/README.md +161 -0
- package/codegen.d.ts +13 -0
- package/codegen.js +267 -0
- package/esm/codegen.js +227 -0
- package/esm/gql.js +721 -0
- package/esm/index.js +3 -0
- package/esm/options.js +21 -0
- package/gql.d.ts +163 -0
- package/gql.js +774 -0
- package/index.d.ts +3 -0
- package/index.js +19 -0
- package/options.d.ts +37 -0
- package/options.js +25 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# @constructive-io/graphql-codegen
|
|
2
|
+
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/@constructive-io/graphql-codegen"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphql%2Fcodegen%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
Generate GraphQL mutations/queries
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @constructive-io/graphql-codegen
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## introspecting via GraphQL
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import {
|
|
25
|
+
generate
|
|
26
|
+
} from '@constructive-io/graphql-codegen';
|
|
27
|
+
import { print } from 'graphql/language';
|
|
28
|
+
|
|
29
|
+
const gen = generate(resultOfIntrospectionQuery);
|
|
30
|
+
const output = Object.keys(gen).reduce((m, key) => {
|
|
31
|
+
m[key] = print(gen[key].ast);
|
|
32
|
+
return m;
|
|
33
|
+
}, {});
|
|
34
|
+
|
|
35
|
+
console.log(output);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
# output
|
|
39
|
+
|
|
40
|
+
which will output the entire API as an object with the mutations and queries as values
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"createApiTokenMutation": "mutation createApiTokenMutation($id: UUID, $userId: UUID!, $accessToken: String, $accessTokenExpiresAt: Datetime) {
|
|
45
|
+
createApiToken(input: {apiToken: {id: $id, userId: $userId, accessToken: $accessToken, accessTokenExpiresAt: $accessTokenExpiresAt}}) {
|
|
46
|
+
apiToken {
|
|
47
|
+
id
|
|
48
|
+
userId
|
|
49
|
+
accessToken
|
|
50
|
+
accessTokenExpiresAt
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Codegen (types, operations, SDK, React Query)
|
|
57
|
+
|
|
58
|
+
Programmatic codegen generates files to disk from a schema SDL file or from a live endpoint via introspection.
|
|
59
|
+
|
|
60
|
+
```js
|
|
61
|
+
import { runCodegen, defaultGraphQLCodegenOptions } from '@constructive-io/graphql-codegen'
|
|
62
|
+
|
|
63
|
+
await runCodegen({
|
|
64
|
+
input: { schema: './schema.graphql' }, // or: { endpoint: 'http://localhost:3000/graphql', headers: { Host: 'meta8.localhost' } }
|
|
65
|
+
output: defaultGraphQLCodegenOptions.output, // root/typesFile/operationsDir/sdkFile/reactQueryFile
|
|
66
|
+
documents: defaultGraphQLCodegenOptions.documents, // format: 'gql'|'ts', naming convention
|
|
67
|
+
features: { emitTypes: true, emitOperations: true, emitSdk: true, emitReactQuery: true },
|
|
68
|
+
reactQuery: { fetcher: 'graphql-request' }
|
|
69
|
+
}, process.cwd())
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Outputs under `output.root`:
|
|
73
|
+
- `types/generated.ts` (schema types)
|
|
74
|
+
- `operations/*` (queries/mutations/Fragments)
|
|
75
|
+
- `sdk.ts` (typed GraphQL Request client)
|
|
76
|
+
- `react-query.ts` (typed React Query hooks; generated when `emitReactQuery: true`)
|
|
77
|
+
|
|
78
|
+
Documents options:
|
|
79
|
+
- `format`: `'gql' | 'ts'`
|
|
80
|
+
- `convention`: `'dashed' | 'underscore' | 'camelcase' | 'camelUpper'`
|
|
81
|
+
- `allowQueries`, `excludeQueries`, `excludePatterns` to control which root fields become operations
|
|
82
|
+
|
|
83
|
+
Endpoint introspection:
|
|
84
|
+
- Set `input.endpoint` and optional `input.headers`
|
|
85
|
+
- If your dev server routes by hostname, add `headers: { Host: 'meta8.localhost' }`
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Education and Tutorials
|
|
90
|
+
|
|
91
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
92
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
93
|
+
|
|
94
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
95
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
96
|
+
|
|
97
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
98
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
99
|
+
|
|
100
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
101
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
102
|
+
|
|
103
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
104
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
105
|
+
|
|
106
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
107
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
108
|
+
|
|
109
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
110
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
111
|
+
|
|
112
|
+
## Related Constructive Tooling
|
|
113
|
+
|
|
114
|
+
### 🧪 Testing
|
|
115
|
+
|
|
116
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
117
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
118
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
119
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
|
|
120
|
+
|
|
121
|
+
### 🧠 Parsing & AST
|
|
122
|
+
|
|
123
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
124
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
125
|
+
* [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
126
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
127
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
128
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
129
|
+
* [pg-ast](https://www.npmjs.com/package/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
|
|
130
|
+
|
|
131
|
+
### 🚀 API & Dev Tools
|
|
132
|
+
|
|
133
|
+
* [@constructive-io/graphql-server](https://github.com/constructive-io/constructive/tree/main/graphql/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
|
|
134
|
+
* [@constructive-io/graphql-explorer](https://github.com/constructive-io/constructive/tree/main/graphql/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
|
|
135
|
+
|
|
136
|
+
### 🔁 Streaming & Uploads
|
|
137
|
+
|
|
138
|
+
* [etag-hash](https://github.com/constructive-io/constructive/tree/main/streaming/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
|
|
139
|
+
* [etag-stream](https://github.com/constructive-io/constructive/tree/main/streaming/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
|
|
140
|
+
* [uuid-hash](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
|
|
141
|
+
* [uuid-stream](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
|
|
142
|
+
* [@constructive-io/s3-streamer](https://github.com/constructive-io/constructive/tree/main/streaming/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
|
|
143
|
+
* [@constructive-io/upload-names](https://github.com/constructive-io/constructive/tree/main/streaming/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
|
|
144
|
+
|
|
145
|
+
### 🧰 CLI & Codegen
|
|
146
|
+
|
|
147
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
148
|
+
* [@constructive-io/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
|
|
149
|
+
* [@constructive-io/graphql-codegen](https://github.com/constructive-io/constructive/tree/main/graphql/codegen): **✨ GraphQL code generation** (types, operations, SDK) from schema/endpoint introspection.
|
|
150
|
+
* [@constructive-io/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
|
|
151
|
+
* [@constructive-io/graphql-query](https://github.com/constructive-io/constructive/tree/main/graphql/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
|
|
152
|
+
|
|
153
|
+
## Credits
|
|
154
|
+
|
|
155
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
156
|
+
|
|
157
|
+
## Disclaimer
|
|
158
|
+
|
|
159
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
160
|
+
|
|
161
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/codegen.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { GraphQLCodegenOptions } from './options';
|
|
2
|
+
export declare function runCodegen(opts: GraphQLCodegenOptions, cwd: string): Promise<{
|
|
3
|
+
root: string;
|
|
4
|
+
typesFile: string;
|
|
5
|
+
operationsDir: string;
|
|
6
|
+
sdkFile: string;
|
|
7
|
+
}>;
|
|
8
|
+
export declare function runCodegenFromJSONConfig(configPath: string, cwd: string): Promise<{
|
|
9
|
+
root: string;
|
|
10
|
+
typesFile: string;
|
|
11
|
+
operationsDir: string;
|
|
12
|
+
sdkFile: string;
|
|
13
|
+
}>;
|
package/codegen.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.runCodegen = runCodegen;
|
|
40
|
+
exports.runCodegenFromJSONConfig = runCodegenFromJSONConfig;
|
|
41
|
+
const fs_1 = require("fs");
|
|
42
|
+
const path_1 = require("path");
|
|
43
|
+
const graphql_1 = require("graphql");
|
|
44
|
+
const inflection = require('inflection');
|
|
45
|
+
const gql_1 = require("./gql");
|
|
46
|
+
const introspectron_1 = require("introspectron");
|
|
47
|
+
const options_1 = require("./options");
|
|
48
|
+
const core_1 = require("@graphql-codegen/core");
|
|
49
|
+
const typescriptPlugin = __importStar(require("@graphql-codegen/typescript"));
|
|
50
|
+
const typescriptOperationsPlugin = __importStar(require("@graphql-codegen/typescript-operations"));
|
|
51
|
+
const typescriptGraphqlRequestPlugin = __importStar(require("@graphql-codegen/typescript-graphql-request"));
|
|
52
|
+
const typescriptReactQueryPlugin = __importStar(require("@graphql-codegen/typescript-react-query"));
|
|
53
|
+
const graphql_request_1 = require("graphql-request");
|
|
54
|
+
const parser_1 = require("@babel/parser");
|
|
55
|
+
const generator_1 = __importDefault(require("@babel/generator"));
|
|
56
|
+
const t = __importStar(require("@babel/types"));
|
|
57
|
+
function addDocumentNodeImport(code) {
|
|
58
|
+
const ast = (0, parser_1.parse)(code, {
|
|
59
|
+
sourceType: 'module',
|
|
60
|
+
plugins: ['typescript']
|
|
61
|
+
});
|
|
62
|
+
const importDecl = t.importDeclaration([t.importSpecifier(t.identifier('DocumentNode'), t.identifier('DocumentNode'))], t.stringLiteral('graphql'));
|
|
63
|
+
importDecl.importKind = 'type';
|
|
64
|
+
ast.program.body.unshift(importDecl);
|
|
65
|
+
const output = (0, generator_1.default)(ast, {}, code);
|
|
66
|
+
return output.code;
|
|
67
|
+
}
|
|
68
|
+
function getFilename(key, convention) {
|
|
69
|
+
if (convention === 'underscore')
|
|
70
|
+
return inflection.underscore(key);
|
|
71
|
+
if (convention === 'dashed')
|
|
72
|
+
return inflection.underscore(key).replace(/_/g, '-');
|
|
73
|
+
if (convention === 'camelUpper')
|
|
74
|
+
return inflection.camelize(key, false);
|
|
75
|
+
return key;
|
|
76
|
+
}
|
|
77
|
+
async function ensureDir(p) {
|
|
78
|
+
await fs_1.promises.mkdir(p, { recursive: true });
|
|
79
|
+
}
|
|
80
|
+
async function readFileUTF8(p) {
|
|
81
|
+
return fs_1.promises.readFile(p, 'utf8');
|
|
82
|
+
}
|
|
83
|
+
async function writeFileUTF8(p, content) {
|
|
84
|
+
await ensureDir((0, path_1.dirname)(p));
|
|
85
|
+
await fs_1.promises.writeFile(p, content, 'utf8');
|
|
86
|
+
}
|
|
87
|
+
async function getIntrospectionFromSDL(schemaPath) {
|
|
88
|
+
const sdl = await readFileUTF8(schemaPath);
|
|
89
|
+
const schema = (0, graphql_1.buildSchema)(sdl);
|
|
90
|
+
const q = (0, graphql_1.getIntrospectionQuery)();
|
|
91
|
+
const res = await (0, graphql_1.graphql)({ schema, source: q });
|
|
92
|
+
return res.data;
|
|
93
|
+
}
|
|
94
|
+
async function getIntrospectionFromEndpoint(endpoint, headers) {
|
|
95
|
+
const client = new graphql_request_1.GraphQLClient(endpoint, { headers });
|
|
96
|
+
const q = (0, graphql_1.getIntrospectionQuery)();
|
|
97
|
+
const res = await client.request(q);
|
|
98
|
+
return res;
|
|
99
|
+
}
|
|
100
|
+
function generateKeyedObjFromGqlMap(gqlMap) {
|
|
101
|
+
const gen = (0, gql_1.generate)(gqlMap);
|
|
102
|
+
return Object.entries(gen).reduce((acc, [key, val]) => {
|
|
103
|
+
if (val?.ast)
|
|
104
|
+
acc[key] = (0, graphql_1.print)(val.ast);
|
|
105
|
+
return acc;
|
|
106
|
+
}, {});
|
|
107
|
+
}
|
|
108
|
+
function applyQueryFilters(map, docs) {
|
|
109
|
+
const allow = (docs.allowQueries || []).filter(Boolean);
|
|
110
|
+
const exclude = (docs.excludeQueries || []).filter(Boolean);
|
|
111
|
+
const patterns = (docs.excludePatterns || []).filter(Boolean);
|
|
112
|
+
let keys = Object.keys(map);
|
|
113
|
+
if (allow.length > 0)
|
|
114
|
+
keys = keys.filter((k) => allow.includes(k));
|
|
115
|
+
if (exclude.length > 0)
|
|
116
|
+
keys = keys.filter((k) => !exclude.includes(k));
|
|
117
|
+
if (patterns.length > 0) {
|
|
118
|
+
const regs = patterns.map((p) => {
|
|
119
|
+
try {
|
|
120
|
+
return new RegExp(p);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}).filter((r) => !!r);
|
|
126
|
+
keys = keys.filter((k) => !regs.some((r) => r.test(k)));
|
|
127
|
+
}
|
|
128
|
+
return keys.reduce((acc, k) => {
|
|
129
|
+
acc[k] = map[k];
|
|
130
|
+
return acc;
|
|
131
|
+
}, {});
|
|
132
|
+
}
|
|
133
|
+
async function writeOperationsDocuments(docs, dir, format, convention) {
|
|
134
|
+
await ensureDir(dir);
|
|
135
|
+
const index = [];
|
|
136
|
+
for (const key of Object.keys(docs)) {
|
|
137
|
+
const filename = getFilename(key, convention) + (format === 'ts' ? '.ts' : '.gql');
|
|
138
|
+
if (format === 'ts') {
|
|
139
|
+
const code = `import gql from 'graphql-tag'\nexport const ${key} = gql\`\n${docs[key]}\n\``;
|
|
140
|
+
await writeFileUTF8((0, path_1.join)(dir, filename), code);
|
|
141
|
+
index.push(`export * from './${filename}'`);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
await writeFileUTF8((0, path_1.join)(dir, filename), docs[key]);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (format === 'ts')
|
|
148
|
+
await writeFileUTF8((0, path_1.join)(dir, 'index.ts'), index.sort().join('\n'));
|
|
149
|
+
}
|
|
150
|
+
async function runCodegen(opts, cwd) {
|
|
151
|
+
const options = {
|
|
152
|
+
input: { ...(options_1.defaultGraphQLCodegenOptions.input), ...(opts.input || {}) },
|
|
153
|
+
output: { ...(options_1.defaultGraphQLCodegenOptions.output), ...(opts.output || {}) },
|
|
154
|
+
documents: { ...(options_1.defaultGraphQLCodegenOptions.documents), ...(opts.documents || {}) },
|
|
155
|
+
features: { ...(options_1.defaultGraphQLCodegenOptions.features), ...(opts.features || {}) }
|
|
156
|
+
};
|
|
157
|
+
const root = (0, path_1.join)(cwd, options.output.root);
|
|
158
|
+
const typesFile = (0, path_1.join)(root, options.output.typesFile);
|
|
159
|
+
const operationsDir = (0, path_1.join)(root, options.output.operationsDir);
|
|
160
|
+
const sdkFile = (0, path_1.join)(root, options.output.sdkFile);
|
|
161
|
+
const reactQueryFile = (0, path_1.join)(root, options.output.reactQueryFile || 'react-query.ts');
|
|
162
|
+
const hasSchemaPath = !!options.input.schema && options.input.schema.trim() !== '';
|
|
163
|
+
const hasEndpoint = !!options.input.endpoint && options.input.endpoint.trim() !== '';
|
|
164
|
+
const schemaPath = hasSchemaPath ? ((0, path_1.isAbsolute)(options.input.schema) ? options.input.schema : (0, path_1.resolve)(cwd, options.input.schema)) : '';
|
|
165
|
+
const introspection = hasEndpoint
|
|
166
|
+
? await getIntrospectionFromEndpoint(options.input.endpoint, options.input.headers || {})
|
|
167
|
+
: await getIntrospectionFromSDL(schemaPath);
|
|
168
|
+
const { queries, mutations } = (0, introspectron_1.parseGraphQuery)(introspection);
|
|
169
|
+
const gqlMap = applyQueryFilters({ ...queries, ...mutations }, options.documents);
|
|
170
|
+
let docs = {};
|
|
171
|
+
const schema = hasEndpoint
|
|
172
|
+
? (0, graphql_1.buildClientSchema)(introspection)
|
|
173
|
+
: (0, graphql_1.buildSchema)(await readFileUTF8(schemaPath));
|
|
174
|
+
if (options.features.emitOperations || options.features.emitSdk || options.features.emitReactQuery) {
|
|
175
|
+
docs = generateKeyedObjFromGqlMap(gqlMap);
|
|
176
|
+
}
|
|
177
|
+
if (options.features.emitOperations) {
|
|
178
|
+
await writeOperationsDocuments(docs, operationsDir, options.documents.format, options.documents.convention);
|
|
179
|
+
}
|
|
180
|
+
if (options.features.emitTypes) {
|
|
181
|
+
const typesContent = await (0, core_1.codegen)({
|
|
182
|
+
filename: typesFile,
|
|
183
|
+
schema: schema,
|
|
184
|
+
documents: [],
|
|
185
|
+
config: {},
|
|
186
|
+
plugins: [{ typescript: {} }],
|
|
187
|
+
pluginMap: { typescript: typescriptPlugin }
|
|
188
|
+
});
|
|
189
|
+
await writeFileUTF8(typesFile, typesContent);
|
|
190
|
+
}
|
|
191
|
+
if (options.features.emitSdk) {
|
|
192
|
+
const documents = [];
|
|
193
|
+
for (const [name, content] of Object.entries(docs)) {
|
|
194
|
+
try {
|
|
195
|
+
const doc = require('graphql').parse(content);
|
|
196
|
+
documents.push({ location: name, document: doc });
|
|
197
|
+
}
|
|
198
|
+
catch (e) { }
|
|
199
|
+
}
|
|
200
|
+
const sdkContent = await (0, core_1.codegen)({
|
|
201
|
+
filename: sdkFile,
|
|
202
|
+
schema: schema,
|
|
203
|
+
documents,
|
|
204
|
+
config: {},
|
|
205
|
+
plugins: [
|
|
206
|
+
{ typescript: {} },
|
|
207
|
+
{ 'typescript-operations': {} },
|
|
208
|
+
{ 'typescript-graphql-request': {} }
|
|
209
|
+
],
|
|
210
|
+
pluginMap: {
|
|
211
|
+
typescript: typescriptPlugin,
|
|
212
|
+
'typescript-operations': typescriptOperationsPlugin,
|
|
213
|
+
'typescript-graphql-request': typescriptGraphqlRequestPlugin
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
// Fix TS2742: Add missing DocumentNode import using Babel AST
|
|
217
|
+
const sdkContentWithImport = addDocumentNodeImport(sdkContent);
|
|
218
|
+
await writeFileUTF8(sdkFile, sdkContentWithImport);
|
|
219
|
+
}
|
|
220
|
+
if (options.features.emitReactQuery) {
|
|
221
|
+
const documents = [];
|
|
222
|
+
for (const [name, content] of Object.entries(docs)) {
|
|
223
|
+
try {
|
|
224
|
+
const doc = require('graphql').parse(content);
|
|
225
|
+
documents.push({ location: name, document: doc });
|
|
226
|
+
}
|
|
227
|
+
catch (e) { }
|
|
228
|
+
}
|
|
229
|
+
const rqConfig = {
|
|
230
|
+
fetcher: options.reactQuery?.fetcher || 'graphql-request',
|
|
231
|
+
legacyMode: options.reactQuery?.legacyMode || false,
|
|
232
|
+
exposeDocument: options.reactQuery?.exposeDocument || false,
|
|
233
|
+
addInfiniteQuery: options.reactQuery?.addInfiniteQuery || false
|
|
234
|
+
};
|
|
235
|
+
const rqContent = await (0, core_1.codegen)({
|
|
236
|
+
filename: reactQueryFile,
|
|
237
|
+
schema: schema,
|
|
238
|
+
documents,
|
|
239
|
+
config: rqConfig,
|
|
240
|
+
plugins: [
|
|
241
|
+
{ typescript: {} },
|
|
242
|
+
{ 'typescript-operations': {} },
|
|
243
|
+
{ 'typescript-react-query': rqConfig }
|
|
244
|
+
],
|
|
245
|
+
pluginMap: {
|
|
246
|
+
typescript: typescriptPlugin,
|
|
247
|
+
'typescript-operations': typescriptOperationsPlugin,
|
|
248
|
+
'typescript-react-query': typescriptReactQueryPlugin
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
await writeFileUTF8(reactQueryFile, rqContent);
|
|
252
|
+
}
|
|
253
|
+
return { root, typesFile, operationsDir, sdkFile };
|
|
254
|
+
}
|
|
255
|
+
async function runCodegenFromJSONConfig(configPath, cwd) {
|
|
256
|
+
const path = (0, path_1.isAbsolute)(configPath) ? configPath : (0, path_1.resolve)(cwd, configPath);
|
|
257
|
+
const content = await readFileUTF8(path);
|
|
258
|
+
let overrides = {};
|
|
259
|
+
try {
|
|
260
|
+
overrides = JSON.parse(content);
|
|
261
|
+
}
|
|
262
|
+
catch (e) {
|
|
263
|
+
throw new Error('Invalid JSON config: ' + e);
|
|
264
|
+
}
|
|
265
|
+
const merged = (0, options_1.mergeGraphQLCodegenOptions)(options_1.defaultGraphQLCodegenOptions, overrides);
|
|
266
|
+
return runCodegen(merged, cwd);
|
|
267
|
+
}
|