pluggable-codegen 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,329 +1,10 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/codegen.ts
2
- var _promises = require('fs/promises');
3
- var _path = require('path');
4
- var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
5
- var _tinyglobby = require('tinyglobby');
6
-
7
- // src/cache.ts
8
- var _crypto = require('crypto');
9
-
10
-
11
-
12
- // src/utils.ts
13
-
14
-
15
- async function lookupPath(dir, candidates, check) {
16
- if (!Array.isArray(candidates)) {
17
- candidates = [candidates];
18
- }
19
- do {
20
- for (const candidate of candidates) {
21
- const path = _path.resolve.call(void 0, dir, candidate);
22
- try {
23
- return await check(path);
24
- } catch (e) {
25
- }
26
- }
27
- } while (cdup());
28
- return void 0;
29
- function cdup() {
30
- const orig = dir;
31
- dir = _path.dirname.call(void 0, dir);
32
- return dir !== orig;
33
- }
34
- }
35
- function hash(data) {
36
- const hash2 = _crypto.createHash.call(void 0, "sha256");
37
- hash2.update(data);
38
- return hash2.digest("hex");
39
- }
40
-
41
- // src/cache.ts
42
- var Cache = class {
43
- #rootDir;
44
- #cacheFile;
45
- #cacheData;
46
- #writeTmr;
47
- constructor(rootDir, cacheFile) {
48
- this.#rootDir = rootDir;
49
- this.#cacheFile = cacheFile;
50
- }
51
- async check(files, output, mode, generate) {
52
- if (!mode) {
53
- await generate();
54
- return;
55
- }
56
- const [cacheData, sourceHash, outputHash] = await Promise.all([
57
- this.#cacheData ??= this.#readCacheData(),
58
- this.#getSourceHash(files, mode),
59
- this.#getOutputHash(_path.resolve.call(void 0, this.#rootDir, output))
60
- ]);
61
- const entry = cacheData.get(output);
62
- if (entry && entry.source === sourceHash && entry.output === outputHash) {
63
- return;
64
- }
65
- const newHash = await generate();
66
- if (newHash === void 0) {
67
- return;
68
- }
69
- cacheData.set(output, {
70
- source: sourceHash,
71
- output: newHash
72
- });
73
- clearTimeout(this.#writeTmr);
74
- this.#writeTmr = setTimeout(() => this.#writeCacheData(cacheData), 250);
75
- }
76
- async #getSourceHash(files, mode) {
77
- const hash2 = _crypto.createHash.call(void 0, "sha256");
78
- for (const file of files) {
79
- hash2.update(mode === "files" ? file.localPath : await file.buffer());
80
- }
81
- return hash2.digest("hex");
82
- }
83
- async #getOutputHash(file) {
84
- try {
85
- return hash(await _promises.readFile.call(void 0, file));
86
- } catch (e2) {
87
- return void 0;
88
- }
89
- }
90
- async #readCacheData() {
91
- if (!this.#cacheFile) {
92
- return /* @__PURE__ */ new Map();
93
- }
94
- try {
95
- const rawData = JSON.parse(await _promises.readFile.call(void 0, this.#cacheFile, "utf-8"));
96
- const cacheData = /* @__PURE__ */ new Map();
97
- if (!isObject(rawData)) {
98
- return cacheData;
99
- }
100
- for (const [key, value] of Object.entries(rawData)) {
101
- if (!isObject(value) || !isValidEntry(value)) {
102
- continue;
103
- }
104
- cacheData.set(key, value);
105
- }
106
- return cacheData;
107
- } catch (e3) {
108
- return /* @__PURE__ */ new Map();
109
- }
110
- }
111
- async #writeCacheData(data) {
112
- if (this.#cacheFile) {
113
- await _promises.writeFile.call(void 0, this.#cacheFile, JSON.stringify(Object.fromEntries(data)));
114
- }
115
- }
116
- };
117
- function isObject(v) {
118
- return !!v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
119
- }
120
- function isValidEntry(v) {
121
- return Object.keys(v).length === 2 && "source" in v && typeof v.source === "string" && "output" in v && typeof v.output === "string";
122
- }
123
-
124
- // src/file.ts
125
-
126
-
127
- var File = class {
128
-
129
-
130
- #contents;
131
- constructor(path, rootDir) {
132
- this.fullPath = path;
133
- this.localPath = _path.relative.call(void 0, rootDir, path).replace(/^\.(?:\/|$)/, "");
134
- }
135
- async buffer() {
136
- return this.#contents ??= _promises.readFile.call(void 0, this.fullPath);
137
- }
138
- async text(encoding = "utf-8") {
139
- const contents = await this.buffer();
140
- return contents.toString(encoding);
141
- }
142
- async json() {
143
- return JSON.parse(await this.text());
144
- }
145
- };
146
-
147
- // src/options.ts
148
-
149
-
150
- async function normalizeOptions(options = {}) {
151
- let packageJson;
152
- const rootDir = _path.resolve.call(void 0, _nullishCoalesce(options.rootDir, () => ( process.cwd())));
153
- const cacheFile = await resolveCacheFile(rootDir, options.cacheFile);
154
- const prettier = await _asyncNullishCoalesce(options.prettier, async () => ( hasDevDep(await getPackageJson(), "prettier")));
155
- const eslint = await _asyncNullishCoalesce(options.eslint, async () => ( hasDevDep(await getPackageJson(), "eslint")));
156
- return { rootDir, cacheFile, prettier, eslint };
157
- async function getPackageJson() {
158
- return packageJson ??= readPackageJson(rootDir);
159
- }
160
- }
161
- async function normalizeJobs(rootDir, inputs) {
162
- const jobs = await Promise.all(
163
- inputs.map(async (input) => {
164
- return typeof input === "function" ? input(rootDir) : input;
165
- })
166
- );
167
- return jobs.flat();
168
- }
169
- async function resolveCacheFile(rootDir, cacheFile) {
170
- if (cacheFile === false) {
171
- return void 0;
172
- } else if (cacheFile !== void 0) {
173
- return _path.resolve.call(void 0, rootDir, cacheFile);
174
- }
175
- const codegenPath = typeof __dirname !== "undefined" ? __dirname : import.meta.dirname;
176
- if (!codegenPath.includes("/node_modules/")) {
177
- return void 0;
178
- }
179
- cacheFile = codegenPath.replace(/^(.+\/node_modules)\/.*$/, "$1/.cache/pluggable-codegen.json");
180
- try {
181
- await _promises.mkdir.call(void 0, _path.dirname.call(void 0, cacheFile), { recursive: true, mode: 488 });
182
- } catch (e4) {
183
- }
184
- return cacheFile;
185
- }
186
- function hasDevDep(packageJson, dep) {
187
- return typeof packageJson === "object" && packageJson !== null && "devDependencies" in packageJson && typeof packageJson.devDependencies === "object" && packageJson.devDependencies !== null && dep in packageJson.devDependencies;
188
- }
189
- async function readPackageJson(dir) {
190
- return lookupPath(dir, "package.json", async (path) => {
191
- const content = await _promises.readFile.call(void 0, path, "utf-8");
192
- return JSON.parse(content);
193
- });
194
- }
195
-
196
- // src/codegen.ts
197
- var Codegen = class _Codegen {
198
- #options;
199
- #cache;
200
- #jobs;
201
- #running = /* @__PURE__ */ new Map();
202
- #eslint;
203
- #prettier;
204
- static async init(jobOrOptions, ...moreJobs) {
205
- const [options, jobs] = typeof jobOrOptions === "function" || "input" in jobOrOptions ? [void 0, [jobOrOptions, ...moreJobs]] : [jobOrOptions, moreJobs];
206
- const normalizedOptions = await normalizeOptions(options);
207
- const normalizedJobs = await normalizeJobs(normalizedOptions.rootDir, jobs);
208
- return new _Codegen(normalizedOptions, normalizedJobs);
209
- }
210
- constructor(options, jobs) {
211
- this.#options = options;
212
- this.#cache = new Cache(options.rootDir, options.cacheFile);
213
- this.#jobs = this.#createJobMap(jobs);
214
- }
215
- async generateAll() {
216
- await Promise.allSettled([...this.#jobs.values()].map(async (job) => this.#generate(job)));
217
- }
218
- async generateMatching(path) {
219
- await Promise.allSettled(
220
- [...this.#jobs].map(async ([match, job]) => {
221
- if (match(path)) {
222
- await this.#generate(job);
223
- }
224
- })
225
- );
226
- }
227
- async #generate(job) {
228
- _optionalChain([this, 'access', _ => _.#running, 'access', _2 => _2.get, 'call', _3 => _3(job), 'optionalAccess', _4 => _4.abort, 'call', _5 => _5()]);
229
- const controller = new AbortController();
230
- this.#running.set(job, controller);
231
- const files = await this.#scanFiles(job);
232
- await this.#cache.check(files, job.output, job.cacheBy, async () => {
233
- const file = _path.resolve.call(void 0, this.#options.rootDir, job.output);
234
- let output = await job.generate(files, controller.signal);
235
- if (output === null) {
236
- return void 0;
237
- }
238
- if (controller.signal.aborted) {
239
- return void 0;
240
- }
241
- if (typeof output === "string" && (_nullishCoalesce(job.eslint, () => ( this.#options.eslint)))) {
242
- output = await this.#applyESLint(output, file);
243
- }
244
- if (controller.signal.aborted) {
245
- return void 0;
246
- }
247
- if (typeof output === "string" && (_nullishCoalesce(job.prettier, () => ( this.#options.prettier)))) {
248
- output = await this.#applyPrettier(output, file);
249
- }
250
- if (controller.signal.aborted) {
251
- return void 0;
252
- }
253
- try {
254
- await _promises.mkdir.call(void 0, _path.dirname.call(void 0, file), { mode: 488, recursive: true });
255
- } catch (e5) {
256
- }
257
- await _promises.writeFile.call(void 0, file, output);
258
- return hash(output);
259
- });
260
- }
261
- async #scanFiles(job) {
262
- const files = await _tinyglobby.glob.call(void 0, job.input, {
263
- cwd: this.#options.rootDir,
264
- absolute: true
265
- });
266
- return files.sort().map((path) => new File(path, this.#options.rootDir));
267
- }
268
- async #applyESLint(source, path) {
269
- const eslint = await this.#loadESLint();
270
- const [result] = await eslint.lintText(source, {
271
- filePath: path
272
- });
273
- return _nullishCoalesce(_optionalChain([result, 'optionalAccess', _6 => _6.output]), () => ( source));
274
- }
275
- async #applyPrettier(source, path) {
276
- const prettier = await this.#loadPrettier();
277
- const options = await prettier.resolveConfig(path);
278
- return prettier.format(source, {
279
- ..._nullishCoalesce(options, () => ( {})),
280
- filepath: path
281
- });
282
- }
283
- async #loadESLint() {
284
- return this.#eslint ??= Promise.resolve().then(() => _interopRequireWildcard(require("eslint"))).then(
285
- ({ ESLint }) => new ESLint({
286
- fix: true
287
- })
288
- );
289
- }
290
- async #loadPrettier() {
291
- return this.#prettier ??= Promise.resolve().then(() => _interopRequireWildcard(require("prettier")));
292
- }
293
- #createJobMap(jobs) {
294
- return new Map(jobs.map((job) => [this.#createMatcher(job), job]));
295
- }
296
- #createMatcher(job) {
297
- const root = _tinyglobby.escapePath.call(void 0, this.#options.rootDir);
298
- return _picomatch2.default.call(void 0,
299
- Array.isArray(job.input) ? job.input.map((pattern) => `${root}/${pattern.replace(/^\//, "")}`) : `${root}/${job.input.replace(/^\//, "")}`
300
- );
301
- }
302
- };
303
-
304
- // src/plugin.ts
305
- function codegen(jobOrOptions, ...moreJobs) {
306
- const init = Codegen.init(jobOrOptions, ...moreJobs);
307
- return {
308
- name: "pluggable-codegen",
309
- async buildStart() {
310
- const codegen2 = await init;
311
- await codegen2.generateAll();
312
- },
313
- async watchChange(id) {
314
- const codegen2 = await init;
315
- await codegen2.generateMatching(id);
316
- }
317
- };
318
- }
319
-
320
- // src/types.ts
321
- function defineCodegen(optionsOrJob, ...jobs) {
322
- return [optionsOrJob, ...jobs];
323
- }
324
-
325
-
326
-
327
-
328
-
329
- exports.Codegen = Codegen; exports.File = File; exports.codegen = codegen; exports.defineCodegen = defineCodegen;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_file = require('./file.cjs');
3
+ const require_codegen = require('./codegen.cjs');
4
+ const require_plugin = require('./plugin.cjs');
5
+ const require_types = require('./types.cjs');
6
+
7
+ exports.Codegen = require_codegen.Codegen;
8
+ exports.File = require_file.File;
9
+ exports.codegen = require_plugin.codegen;
10
+ exports.defineCodegen = require_types.defineCodegen;
@@ -0,0 +1,5 @@
1
+ import { File } from "./file.mjs";
2
+ import { CodegenInput, CodegenJob, CodegenJobGenerator, CodegenOptions, CodegenPresetOptions, NormalizedCodegenOptions, defineCodegen } from "./types.mjs";
3
+ import { Codegen } from "./codegen.mjs";
4
+ import { Plugin, codegen } from "./plugin.mjs";
5
+ export { Codegen, CodegenInput, CodegenJob, CodegenJobGenerator, CodegenOptions, CodegenPresetOptions, File, NormalizedCodegenOptions, Plugin, codegen, defineCodegen };
package/dist/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import { File } from "./file.mjs";
2
+ import { Codegen } from "./codegen.mjs";
3
+ import { codegen } from "./plugin.mjs";
4
+ import { defineCodegen } from "./types.mjs";
5
+
6
+ export { Codegen, File, codegen, defineCodegen };
@@ -0,0 +1,51 @@
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ const require_utils = require('./utils.cjs');
3
+ let node_fs_promises = require("node:fs/promises");
4
+ let node_path = require("node:path");
5
+
6
+ //#region src/options.ts
7
+ async function normalizeOptions(options = {}) {
8
+ let packageJson;
9
+ const rootDir = (0, node_path.resolve)(options.rootDir ?? process.cwd());
10
+ return {
11
+ rootDir,
12
+ cacheFile: await resolveCacheFile(rootDir, options.cacheFile),
13
+ prettier: options.prettier ?? hasDevDep(await getPackageJson(), "prettier"),
14
+ eslint: options.eslint ?? hasDevDep(await getPackageJson(), "eslint")
15
+ };
16
+ async function getPackageJson() {
17
+ return packageJson ??= readPackageJson(rootDir);
18
+ }
19
+ }
20
+ async function normalizeJobs(rootDir, inputs) {
21
+ return (await Promise.all(inputs.map(async (input) => {
22
+ return typeof input === "function" ? input(rootDir) : input;
23
+ }))).flat();
24
+ }
25
+ async function resolveCacheFile(rootDir, cacheFile) {
26
+ if (cacheFile === false) return;
27
+ else if (cacheFile !== void 0) return (0, node_path.resolve)(rootDir, cacheFile);
28
+ const codegenPath = typeof __dirname !== "undefined" ? __dirname : __dirname;
29
+ if (!codegenPath.includes("/node_modules/")) return;
30
+ cacheFile = codegenPath.replace(/^(.+\/node_modules)\/.*$/, "$1/.cache/pluggable-codegen.json");
31
+ try {
32
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(cacheFile), {
33
+ recursive: true,
34
+ mode: 488
35
+ });
36
+ } catch {}
37
+ return cacheFile;
38
+ }
39
+ function hasDevDep(packageJson, dep) {
40
+ return typeof packageJson === "object" && packageJson !== null && "devDependencies" in packageJson && typeof packageJson.devDependencies === "object" && packageJson.devDependencies !== null && dep in packageJson.devDependencies;
41
+ }
42
+ async function readPackageJson(dir) {
43
+ return require_utils.lookupPath(dir, "package.json", async (path) => {
44
+ const content = await (0, node_fs_promises.readFile)(path, "utf-8");
45
+ return JSON.parse(content);
46
+ });
47
+ }
48
+
49
+ //#endregion
50
+ exports.normalizeJobs = normalizeJobs;
51
+ exports.normalizeOptions = normalizeOptions;
@@ -0,0 +1,49 @@
1
+ import { lookupPath } from "./utils.mjs";
2
+ import { mkdir, readFile } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+
5
+ //#region src/options.ts
6
+ async function normalizeOptions(options = {}) {
7
+ let packageJson;
8
+ const rootDir = resolve(options.rootDir ?? process.cwd());
9
+ return {
10
+ rootDir,
11
+ cacheFile: await resolveCacheFile(rootDir, options.cacheFile),
12
+ prettier: options.prettier ?? hasDevDep(await getPackageJson(), "prettier"),
13
+ eslint: options.eslint ?? hasDevDep(await getPackageJson(), "eslint")
14
+ };
15
+ async function getPackageJson() {
16
+ return packageJson ??= readPackageJson(rootDir);
17
+ }
18
+ }
19
+ async function normalizeJobs(rootDir, inputs) {
20
+ return (await Promise.all(inputs.map(async (input) => {
21
+ return typeof input === "function" ? input(rootDir) : input;
22
+ }))).flat();
23
+ }
24
+ async function resolveCacheFile(rootDir, cacheFile) {
25
+ if (cacheFile === false) return;
26
+ else if (cacheFile !== void 0) return resolve(rootDir, cacheFile);
27
+ const codegenPath = typeof __dirname !== "undefined" ? __dirname : import.meta.dirname;
28
+ if (!codegenPath.includes("/node_modules/")) return;
29
+ cacheFile = codegenPath.replace(/^(.+\/node_modules)\/.*$/, "$1/.cache/pluggable-codegen.json");
30
+ try {
31
+ await mkdir(dirname(cacheFile), {
32
+ recursive: true,
33
+ mode: 488
34
+ });
35
+ } catch {}
36
+ return cacheFile;
37
+ }
38
+ function hasDevDep(packageJson, dep) {
39
+ return typeof packageJson === "object" && packageJson !== null && "devDependencies" in packageJson && typeof packageJson.devDependencies === "object" && packageJson.devDependencies !== null && dep in packageJson.devDependencies;
40
+ }
41
+ async function readPackageJson(dir) {
42
+ return lookupPath(dir, "package.json", async (path) => {
43
+ const content = await readFile(path, "utf-8");
44
+ return JSON.parse(content);
45
+ });
46
+ }
47
+
48
+ //#endregion
49
+ export { normalizeJobs, normalizeOptions };
@@ -0,0 +1,18 @@
1
+ const require_codegen = require('./codegen.cjs');
2
+
3
+ //#region src/plugin.ts
4
+ function codegen(jobOrOptions, ...moreJobs) {
5
+ const init = require_codegen.Codegen.init(jobOrOptions, ...moreJobs);
6
+ return {
7
+ name: "pluggable-codegen",
8
+ async buildStart() {
9
+ await (await init).generateAll();
10
+ },
11
+ async watchChange(id) {
12
+ await (await init).generateMatching(id);
13
+ }
14
+ };
15
+ }
16
+
17
+ //#endregion
18
+ exports.codegen = codegen;
@@ -0,0 +1,13 @@
1
+ import { CodegenInput, CodegenOptions } from "./types.mjs";
2
+
3
+ //#region src/plugin.d.ts
4
+ type Plugin = {
5
+ name: string;
6
+ buildStart(): Promise<void>;
7
+ watchChange(id: string): Promise<void>;
8
+ };
9
+ declare function codegen(...jobs: CodegenInput[]): Plugin;
10
+ declare function codegen(options: CodegenOptions, ...jobs: CodegenInput[]): Plugin;
11
+ declare function codegen(jobOrOptions: CodegenInput | CodegenOptions, ...moreJobs: CodegenInput[]): Plugin;
12
+ //#endregion
13
+ export { Plugin, codegen };
@@ -0,0 +1,18 @@
1
+ import { Codegen } from "./codegen.mjs";
2
+
3
+ //#region src/plugin.ts
4
+ function codegen(jobOrOptions, ...moreJobs) {
5
+ const init = Codegen.init(jobOrOptions, ...moreJobs);
6
+ return {
7
+ name: "pluggable-codegen",
8
+ async buildStart() {
9
+ await (await init).generateAll();
10
+ },
11
+ async watchChange(id) {
12
+ await (await init).generateMatching(id);
13
+ }
14
+ };
15
+ }
16
+
17
+ //#endregion
18
+ export { codegen };
@@ -1,63 +1,48 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/presets/graphql-codegen.ts
2
- var _cli = require('@graphql-codegen/cli');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let _graphql_codegen_cli = require("@graphql-codegen/cli");
4
+
5
+ //#region src/presets/graphql-codegen.ts
3
6
  function graphqlCodegen(options = {}) {
4
- return async () => {
5
- const context = await _cli.createContext.call(void 0, {
6
- config: _nullishCoalesce(options.config, () => ( "")),
7
- project: _nullishCoalesce(options.project, () => ( "")),
8
- watch: false,
9
- require: [],
10
- overwrite: false,
11
- silent: false,
12
- errorsOnly: false,
13
- profile: false,
14
- verbose: true,
15
- debug: true
16
- });
17
- const config = context.getConfig();
18
- return Object.entries(config.generates).map(([output, options2]) => {
19
- const input = [
20
- ...normalizeDocuments(config.documents),
21
- ...Array.isArray(options2) ? [] : normalizeDocuments(options2.documents)
22
- ];
23
- return {
24
- input,
25
- output,
26
- cacheBy: "contents",
27
- generate: async (files) => {
28
- const [generatedFile] = await _cli.generate.call(void 0,
29
- {
30
- ...config,
31
- documents: files.map((file) => file.localPath),
32
- generates: {
33
- [output]: {
34
- ...options2,
35
- documents: void 0
36
- }
37
- }
38
- },
39
- false
40
- );
41
- return generatedFile.content;
42
- }
43
- };
44
- });
45
- };
7
+ return async () => {
8
+ const config = (await (0, _graphql_codegen_cli.createContext)({
9
+ config: options.config ?? "",
10
+ project: options.project ?? "",
11
+ watch: false,
12
+ require: [],
13
+ overwrite: false,
14
+ silent: false,
15
+ errorsOnly: false,
16
+ profile: false,
17
+ verbose: true,
18
+ debug: true
19
+ })).getConfig();
20
+ return Object.entries(config.generates).map(([output, options]) => {
21
+ return {
22
+ input: [...normalizeDocuments(config.documents), ...Array.isArray(options) ? [] : normalizeDocuments(options.documents)],
23
+ output,
24
+ cacheBy: "contents",
25
+ generate: async (files) => {
26
+ const [generatedFile] = await (0, _graphql_codegen_cli.generate)({
27
+ ...config,
28
+ documents: files.map((file) => file.localPath),
29
+ generates: { [output]: {
30
+ ...options,
31
+ documents: void 0
32
+ } }
33
+ }, false);
34
+ return generatedFile.content;
35
+ }
36
+ };
37
+ });
38
+ };
46
39
  }
47
40
  function normalizeDocuments(documents) {
48
- if (documents === void 0) {
49
- return [];
50
- }
51
- if (!Array.isArray(documents)) {
52
- documents = [documents];
53
- }
54
- for (const document of documents) {
55
- if (typeof document !== "string") {
56
- throw new Error("Custom loaders are not supported");
57
- }
58
- }
59
- return documents;
41
+ if (documents === void 0) return [];
42
+ if (!Array.isArray(documents)) documents = [documents];
43
+ for (const document of documents) if (typeof document !== "string") throw new Error("Custom loaders are not supported");
44
+ return documents;
60
45
  }
61
46
 
62
-
63
- exports.graphqlCodegen = graphqlCodegen;
47
+ //#endregion
48
+ exports.graphqlCodegen = graphqlCodegen;
@@ -0,0 +1,10 @@
1
+ import { CodegenJob } from "../types.mjs";
2
+
3
+ //#region src/presets/graphql-codegen.d.ts
4
+ type GraphqlCodegenOptions = {
5
+ config?: string;
6
+ project?: string;
7
+ };
8
+ declare function graphqlCodegen(options?: GraphqlCodegenOptions): () => Promise<CodegenJob[]>;
9
+ //#endregion
10
+ export { GraphqlCodegenOptions, graphqlCodegen };
@@ -0,0 +1,46 @@
1
+ import { createContext, generate } from "@graphql-codegen/cli";
2
+
3
+ //#region src/presets/graphql-codegen.ts
4
+ function graphqlCodegen(options = {}) {
5
+ return async () => {
6
+ const config = (await createContext({
7
+ config: options.config ?? "",
8
+ project: options.project ?? "",
9
+ watch: false,
10
+ require: [],
11
+ overwrite: false,
12
+ silent: false,
13
+ errorsOnly: false,
14
+ profile: false,
15
+ verbose: true,
16
+ debug: true
17
+ })).getConfig();
18
+ return Object.entries(config.generates).map(([output, options]) => {
19
+ return {
20
+ input: [...normalizeDocuments(config.documents), ...Array.isArray(options) ? [] : normalizeDocuments(options.documents)],
21
+ output,
22
+ cacheBy: "contents",
23
+ generate: async (files) => {
24
+ const [generatedFile] = await generate({
25
+ ...config,
26
+ documents: files.map((file) => file.localPath),
27
+ generates: { [output]: {
28
+ ...options,
29
+ documents: void 0
30
+ } }
31
+ }, false);
32
+ return generatedFile.content;
33
+ }
34
+ };
35
+ });
36
+ };
37
+ }
38
+ function normalizeDocuments(documents) {
39
+ if (documents === void 0) return [];
40
+ if (!Array.isArray(documents)) documents = [documents];
41
+ for (const document of documents) if (typeof document !== "string") throw new Error("Custom loaders are not supported");
42
+ return documents;
43
+ }
44
+
45
+ //#endregion
46
+ export { graphqlCodegen };
package/dist/types.cjs ADDED
@@ -0,0 +1,8 @@
1
+
2
+ //#region src/types.ts
3
+ function defineCodegen(optionsOrJob, ...jobs) {
4
+ return [optionsOrJob, ...jobs];
5
+ }
6
+
7
+ //#endregion
8
+ exports.defineCodegen = defineCodegen;