@graphcommerce/next-config 9.1.0-canary.55 → 10.0.0-canary.57

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/Config.graphqls +3 -3
  3. package/__tests__/config/utils/__snapshots__/mergeEnvIntoConfig.ts.snap +1 -1
  4. package/__tests__/interceptors/generateInterceptors.ts +133 -150
  5. package/dist/config/loadConfig.js +7 -0
  6. package/dist/generated/config.js +9 -9
  7. package/dist/index.js +807 -2442
  8. package/dist/loadConfig-nJiCKeL1.js +311 -0
  9. package/dist/utils/findParentPath.js +36 -0
  10. package/package.json +41 -20
  11. package/src/commands/cleanupInterceptors.ts +26 -0
  12. package/src/commands/codegen.ts +13 -15
  13. package/src/commands/codegenInterceptors.ts +31 -0
  14. package/src/{config/commands → commands}/exportConfig.ts +3 -3
  15. package/src/{config/commands → commands}/generateConfig.ts +12 -9
  16. package/src/commands/generateConfigValues.ts +265 -0
  17. package/src/commands/index.ts +7 -0
  18. package/src/config/index.ts +0 -9
  19. package/src/config/loadConfig.ts +0 -1
  20. package/src/config/utils/mergeEnvIntoConfig.ts +27 -4
  21. package/src/generated/config.ts +13 -14
  22. package/src/index.ts +7 -39
  23. package/src/interceptors/generateInterceptor.ts +192 -157
  24. package/src/interceptors/generateInterceptors.ts +11 -4
  25. package/src/interceptors/updatePackageExports.ts +147 -0
  26. package/src/interceptors/writeInterceptors.ts +91 -36
  27. package/src/types.ts +26 -0
  28. package/src/utils/{isMonorepo.ts → findParentPath.ts} +2 -2
  29. package/src/utils/index.ts +7 -0
  30. package/src/utils/resolveDependenciesSync.ts +7 -9
  31. package/src/utils/resolveDependency.ts +1 -1
  32. package/src/withGraphCommerce.ts +30 -49
  33. package/tsconfig.json +3 -1
  34. package/__tests__/config/utils/configToImportMeta.ts +0 -121
  35. package/src/interceptors/InterceptorPlugin.ts +0 -141
  36. package/src/interceptors/commands/codegenInterceptors.ts +0 -27
@@ -0,0 +1,311 @@
1
+ import { cosmiconfigSync } from 'cosmiconfig';
2
+ import { GraphCommerceConfigSchema } from './generated/config.js';
3
+ import { cloneDeep, mergeDeep } from '@apollo/client/utilities/index.js';
4
+ import chalk from 'chalk';
5
+ import lodash from 'lodash';
6
+ import { z, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodLazy, ZodObject, ZodArray, ZodNumber, ZodString, ZodEnum, ZodBoolean } from 'zod';
7
+
8
+ const demoConfig = {
9
+ canonicalBaseUrl: "https://graphcommerce.vercel.app",
10
+ hygraphEndpoint: "https://eu-central-1.cdn.hygraph.com/content/ckhx7xadya6xs01yxdujt8i80/master",
11
+ magentoEndpoint: "https://configurator.reachdigital.dev/graphql",
12
+ magentoVersion: 247,
13
+ storefront: [
14
+ { locale: "en", magentoStoreCode: "en_US", defaultLocale: true },
15
+ {
16
+ locale: "nl",
17
+ magentoStoreCode: "nl_NL",
18
+ hygraphLocales: ["nl", "en_us"],
19
+ cartDisplayPricesInclTax: true
20
+ },
21
+ {
22
+ locale: "fr-be",
23
+ magentoStoreCode: "fr_BE",
24
+ cartDisplayPricesInclTax: true,
25
+ linguiLocale: "fr"
26
+ },
27
+ {
28
+ locale: "nl-be",
29
+ magentoStoreCode: "nl_BE",
30
+ cartDisplayPricesInclTax: true,
31
+ linguiLocale: "nl"
32
+ },
33
+ {
34
+ locale: "en-gb",
35
+ magentoStoreCode: "en_GB",
36
+ cartDisplayPricesInclTax: true,
37
+ linguiLocale: "en"
38
+ },
39
+ { locale: "en-ca", magentoStoreCode: "en_CA", linguiLocale: "en" }
40
+ ],
41
+ productFiltersPro: true,
42
+ productFiltersLayout: "DEFAULT",
43
+ productListPaginationVariant: "COMPACT",
44
+ compareVariant: "ICON",
45
+ robotsAllow: false,
46
+ demoMode: true,
47
+ limitSsg: true,
48
+ compare: true,
49
+ sidebarGallery: { paginationVariant: "DOTS" },
50
+ configurableVariantForSimple: true,
51
+ configurableVariantValues: { url: true, content: true, gallery: true },
52
+ recentlyViewedProducts: { enabled: true, maxCount: 20 },
53
+ breadcrumbs: false,
54
+ customerDeleteEnabled: true,
55
+ previewSecret: "SECRET"
56
+ };
57
+
58
+ function isObject(val) {
59
+ return typeof val === "object" && val !== null;
60
+ }
61
+ function isArray(val) {
62
+ return Array.isArray(val);
63
+ }
64
+ function diff(item1, item2) {
65
+ const item1Type = typeof item2;
66
+ const item2Type = typeof item2;
67
+ const isSame = item1Type === item2Type;
68
+ if (!isSame) return item2;
69
+ if (isArray(item1) && isArray(item2)) {
70
+ const res = item1.map((val, idx) => diff(val, item2[idx])).filter((val) => !!val);
71
+ return res.length ? res : void 0;
72
+ }
73
+ if (isObject(item1) && isObject(item2)) {
74
+ const entriesRight = Object.fromEntries(
75
+ Object.entries(item1).map(([key, val]) => [key, diff(val, item2[key])]).filter((entry) => !!entry[1])
76
+ );
77
+ const entriesLeft = Object.fromEntries(
78
+ Object.entries(item2).map(([key, val]) => [key, diff(item1[key], val)]).filter((entry) => !!entry[1])
79
+ );
80
+ const entries = { ...entriesRight, ...entriesLeft };
81
+ return Object.keys(entries).length ? entries : void 0;
82
+ }
83
+ return item2 === item1 ? void 0 : item2;
84
+ }
85
+
86
+ const fmt = (s) => s.split(/(\d+)/).map((v) => lodash.snakeCase(v)).join("");
87
+ const toEnvStr = (path) => ["GC", ...path].map(fmt).join("_").toUpperCase();
88
+ const dotNotation = (pathParts) => pathParts.map((v) => {
89
+ const idx = Number(v);
90
+ return !Number.isNaN(idx) ? `[${idx}]` : v;
91
+ }).join(".");
92
+ function isJSON(str) {
93
+ if (!str) return true;
94
+ try {
95
+ JSON.parse(str);
96
+ } catch (e) {
97
+ return false;
98
+ }
99
+ return true;
100
+ }
101
+ function configToEnvSchema(schema) {
102
+ const envSchema = {};
103
+ const envToDot = {};
104
+ function walk(incomming, path = []) {
105
+ let node = incomming;
106
+ while (true) {
107
+ if (node instanceof ZodEffects) {
108
+ node = node.innerType();
109
+ continue;
110
+ }
111
+ if (node instanceof ZodOptional) {
112
+ node = node.unwrap();
113
+ continue;
114
+ }
115
+ if (node instanceof ZodNullable) {
116
+ node = node.unwrap();
117
+ continue;
118
+ }
119
+ if (node instanceof ZodDefault) {
120
+ node = node.removeDefault();
121
+ continue;
122
+ }
123
+ if (node instanceof ZodLazy) {
124
+ node = node.schema;
125
+ continue;
126
+ }
127
+ break;
128
+ }
129
+ if (node instanceof ZodObject) {
130
+ if (path.length > 0) {
131
+ envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val);
132
+ envToDot[toEnvStr(path)] = dotNotation(path);
133
+ }
134
+ const typeNode = node;
135
+ Object.keys(typeNode.shape).forEach((key) => {
136
+ walk(typeNode.shape[key], [...path, key]);
137
+ });
138
+ return;
139
+ }
140
+ if (node instanceof ZodArray) {
141
+ const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
142
+ if (path.length > 0) {
143
+ envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val);
144
+ envToDot[toEnvStr(path)] = dotNotation(path);
145
+ }
146
+ arr.forEach((key) => {
147
+ walk(node.element, [...path, String(key)]);
148
+ });
149
+ return;
150
+ }
151
+ if (node instanceof ZodNumber) {
152
+ envSchema[toEnvStr(path)] = z.coerce.number().optional();
153
+ envToDot[toEnvStr(path)] = dotNotation(path);
154
+ return;
155
+ }
156
+ if (node instanceof ZodString || node instanceof ZodEnum) {
157
+ envSchema[toEnvStr(path)] = node.optional();
158
+ envToDot[toEnvStr(path)] = dotNotation(path);
159
+ return;
160
+ }
161
+ if (node instanceof ZodBoolean) {
162
+ envSchema[toEnvStr(path)] = z.enum(["true", "1", "false", "0"]).optional().transform((v) => {
163
+ if (v === "true" || v === "1") return true;
164
+ if (v === "false" || v === "0") return false;
165
+ return v;
166
+ });
167
+ envToDot[toEnvStr(path)] = dotNotation(path);
168
+ return;
169
+ }
170
+ throw Error(
171
+ `[@graphcommerce/next-config] Unknown type in schema ${node.constructor.name}. This is probably a bug please create an issue.`
172
+ );
173
+ }
174
+ walk(schema);
175
+ return [z.object(envSchema), envToDot];
176
+ }
177
+ const filterEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("GC_")));
178
+ function mergeEnvIntoConfig(schema, config, env) {
179
+ const filteredEnv = filterEnv(env);
180
+ const newConfig = cloneDeep(config);
181
+ const [envSchema, envToDot] = configToEnvSchema(schema);
182
+ const result = envSchema.safeParse(filteredEnv);
183
+ const applyResult = [];
184
+ if (!result.success) {
185
+ Object.entries(result.error.flatten().fieldErrors).forEach(([envVar, error]) => {
186
+ const dotVar = envToDot[envVar];
187
+ const envValue = filteredEnv[envVar];
188
+ applyResult.push({ envVar, envValue, dotVar, error });
189
+ });
190
+ return [void 0, applyResult];
191
+ }
192
+ Object.entries(result.data).forEach(([envVar, value]) => {
193
+ const dotVar = envToDot[envVar];
194
+ const envValue = filteredEnv[envVar];
195
+ if (!dotVar) {
196
+ applyResult.push({ envVar, envValue });
197
+ return;
198
+ }
199
+ const dotValue = lodash.get(newConfig, dotVar);
200
+ const merged = mergeDeep(dotValue, value);
201
+ const from = diff(merged, dotValue);
202
+ const to = diff(dotValue, merged);
203
+ applyResult.push({ envVar, envValue, dotVar, from, to });
204
+ lodash.set(newConfig, dotVar, merged);
205
+ });
206
+ return [newConfig, applyResult];
207
+ }
208
+ function formatAppliedEnv(applyResult) {
209
+ let hasError = false;
210
+ let hasWarning = false;
211
+ const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => {
212
+ const envVariableFmt = `${envVar}`;
213
+ const dotVariableFmt = chalk.bold.underline(`${dotVar}`);
214
+ const baseLog = `${envVariableFmt} => ${dotVariableFmt}`;
215
+ if (error) {
216
+ hasError = true;
217
+ return `${chalk.red(` \u2A09 ${envVariableFmt}`)} => ${error.join(", ")}`;
218
+ }
219
+ if (warning) {
220
+ hasWarning = true;
221
+ return `${chalk.yellowBright(` \u203C ${envVariableFmt}`)} => ${warning.join(", ")}`;
222
+ }
223
+ if (!dotVar) return chalk.red(`${envVariableFmt} => ignored (no matching config)`);
224
+ if (from === void 0 && to === void 0) return ` = ${baseLog}`;
225
+ if (from === void 0 && to !== void 0) return ` ${chalk.green("+")} ${baseLog}`;
226
+ if (from !== void 0 && to === void 0) return ` ${chalk.red("-")} ${baseLog}`;
227
+ return ` ${chalk.yellowBright("~")} ${baseLog}`;
228
+ });
229
+ let header = chalk.blueBright("info");
230
+ if (hasWarning) header = chalk.yellowBright("warning");
231
+ if (hasError) header = chalk.yellowBright("error");
232
+ header += " - Loaded GraphCommerce env variables";
233
+ return [header, ...lines].join("\n");
234
+ }
235
+
236
+ function flattenKeys(value, initialPathPrefix, stringify) {
237
+ if (value === null || value === void 0 || typeof value === "number") {
238
+ return { [initialPathPrefix]: value };
239
+ }
240
+ if (typeof value === "string") {
241
+ return { [initialPathPrefix]: stringify ? JSON.stringify(value) : value };
242
+ }
243
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
244
+ return {
245
+ [initialPathPrefix]: stringify || Array.isArray(value) ? JSON.stringify(value) : value
246
+ };
247
+ }
248
+ if (typeof value === "object") {
249
+ let outputValue = value;
250
+ if (stringify)
251
+ outputValue = process.env.NODE_ENV !== "production" ? `{ __debug: "'${initialPathPrefix}' can not be destructured, please access deeper properties directly" }` : "{}";
252
+ return {
253
+ [initialPathPrefix]: outputValue,
254
+ ...Object.keys(value).map((key) => {
255
+ const deep = value[key];
256
+ return {
257
+ ...flattenKeys(deep, `${initialPathPrefix}.${key}`, stringify),
258
+ ...flattenKeys(deep, `${initialPathPrefix}?.${key}`, stringify)
259
+ };
260
+ }).reduce((acc, path) => ({ ...acc, ...path }), {})
261
+ };
262
+ }
263
+ throw Error(`Unexpected value: ${value}`);
264
+ }
265
+ function configToImportMeta(config, path = "import.meta.graphCommerce", stringify = true) {
266
+ return flattenKeys(config, path, stringify);
267
+ }
268
+
269
+ function replaceConfigInString(str, config) {
270
+ let result = str;
271
+ const replacers = configToImportMeta(config, "graphCommerce", false);
272
+ Object.entries(replacers).forEach(([from, to]) => {
273
+ result = result.replace(new RegExp(`{${from}}`, "g"), to);
274
+ });
275
+ return result;
276
+ }
277
+
278
+ const moduleName = "graphcommerce";
279
+ const loader = cosmiconfigSync(moduleName);
280
+ function loadConfig(cwd) {
281
+ const isMainProcess = !process.send;
282
+ try {
283
+ const result = loader.search(cwd);
284
+ let confFile = result?.config;
285
+ if (!confFile) {
286
+ if (isMainProcess)
287
+ console.warn("No graphcommerce.config.js found in the project, using demo config");
288
+ confFile = demoConfig;
289
+ }
290
+ confFile ||= {};
291
+ const schema = GraphCommerceConfigSchema();
292
+ const [mergedConfig, applyResult] = mergeEnvIntoConfig(schema, confFile, process.env);
293
+ if (applyResult.length > 0 && isMainProcess) console.log(formatAppliedEnv(applyResult));
294
+ const finalParse = schema.parse(mergedConfig);
295
+ if (process.env.DEBUG && isMainProcess) {
296
+ console.log("Parsed configuration");
297
+ console.log(finalParse);
298
+ }
299
+ return finalParse;
300
+ } catch (error) {
301
+ if (error instanceof Error) {
302
+ if (isMainProcess) {
303
+ console.log("Error while parsing graphcommerce.config.js", error.message);
304
+ process.exit(1);
305
+ }
306
+ }
307
+ throw error;
308
+ }
309
+ }
310
+
311
+ export { loadConfig as l, replaceConfigInString as r, toEnvStr as t };
@@ -0,0 +1,36 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const debug = process.env.DEBUG === "1";
5
+ const log = (message) => debug && console.log(`isMonorepo: ${message}`);
6
+ function findPackageJson(directory) {
7
+ try {
8
+ const packageJsonPath = path.join(directory, "package.json");
9
+ const content = fs.readFileSync(packageJsonPath, "utf8");
10
+ return JSON.parse(content);
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+ function findParentPath(directory) {
16
+ let currentDir = directory;
17
+ log(`Starting directory: ${currentDir}`);
18
+ currentDir = path.dirname(currentDir);
19
+ log(`Looking for parent packages starting from: ${currentDir}`);
20
+ while (currentDir !== path.parse(currentDir).root) {
21
+ const packageJson = findPackageJson(currentDir);
22
+ if (packageJson) {
23
+ log(`Found package.json in: ${currentDir}`);
24
+ log(`Package name: ${packageJson.name}`);
25
+ if (packageJson.name.startsWith("@graphcommerce/")) {
26
+ log(`Found parent @graphcommerce package at: ${currentDir}`);
27
+ return currentDir;
28
+ }
29
+ }
30
+ currentDir = path.dirname(currentDir);
31
+ }
32
+ log("No parent @graphcommerce package found");
33
+ return null;
34
+ }
35
+
36
+ export { findParentPath };
package/package.json CHANGED
@@ -2,15 +2,39 @@
2
2
  "name": "@graphcommerce/next-config",
3
3
  "homepage": "https://www.graphcommerce.org/",
4
4
  "repository": "github:graphcommerce-org/graphcommerce",
5
- "version": "9.1.0-canary.55",
5
+ "version": "10.0.0-canary.57",
6
6
  "type": "module",
7
7
  "types": "./src/index.ts",
8
8
  "exports": {
9
9
  ".": {
10
+ "types": "./src/index.ts",
10
11
  "default": "./dist/index.js"
11
12
  },
12
- "./config": {
13
+ "./schema": {
14
+ "types": "./src/generated/config.ts",
13
15
  "default": "./dist/generated/config.js"
16
+ },
17
+ "./config": {
18
+ "types": "./src/generated/configValues/index.ts",
19
+ "default": "./dist/generated/configValues/index.js"
20
+ },
21
+ "./loadConfig": {
22
+ "types": "./src/config/loadConfig.ts",
23
+ "default": "./dist/config/loadConfig.js"
24
+ },
25
+ "./findParentPath": {
26
+ "types": "./src/utils/findParentPath.ts",
27
+ "default": "./dist/utils/findParentPath.js"
28
+ }
29
+ },
30
+ "typesVersions": {
31
+ "*": {
32
+ "schema": [
33
+ "src/generated/config.ts"
34
+ ],
35
+ "config": [
36
+ "src/generated/configValues/index.ts"
37
+ ]
14
38
  }
15
39
  },
16
40
  "scripts": {
@@ -19,31 +43,28 @@
19
43
  "prepack": "pkgroll --clean-dist"
20
44
  },
21
45
  "dependencies": {
22
- "@graphql-codegen/cli": "5.0.5",
23
- "@swc/core": "1.10.1",
24
- "@swc/wasm-web": "^1.10.1",
25
- "@types/circular-dependency-plugin": "^5.0.8",
26
- "@types/js-yaml": "^4",
27
- "@types/lodash": "^4.17.13",
28
- "babel-plugin-macros": "^3.1.0",
29
- "chalk": "^4",
30
- "circular-dependency-plugin": "^5.2.2",
46
+ "@graphql-codegen/cli": "6.1.0",
47
+ "@swc/core": "1.15.3",
48
+ "@swc/wasm-web": "^1.15.3",
49
+ "@types/js-yaml": "^4.0.9",
50
+ "@types/lodash": "^4.17.21",
51
+ "chalk": "^4.1.2",
31
52
  "cosmiconfig": "^8.3.6",
32
- "fast-glob": "^3.3.2",
53
+ "fast-glob": "^3.3.3",
33
54
  "glob": "^10.4.5",
34
- "graphql": "^16.10.0",
55
+ "graphql": "^16.12.0",
35
56
  "inspectpack": "^4.7.1",
36
- "js-yaml": "^4.1.0",
57
+ "js-yaml": "^4.1.1",
37
58
  "js-yaml-loader": "^1.2.2",
38
59
  "lodash": "^4.17.21",
39
- "react": "^18.3.1",
40
- "typescript": "5.7.2",
41
- "webpack": "^5.97.1",
60
+ "react": "^19.2.0",
61
+ "typescript": "5.9.3",
42
62
  "znv": "^0.4.0",
43
- "zod": "^3.24.1"
63
+ "zod": "^3.25.76"
44
64
  },
45
65
  "peerDependencies": {
46
- "@graphcommerce/prettier-config-pwa": "^9.1.0-canary.55",
66
+ "@apollo/client": "*",
67
+ "@graphcommerce/prettier-config-pwa": "^10.0.0-canary.57",
47
68
  "@lingui/loader": "*",
48
69
  "@lingui/macro": "*",
49
70
  "@lingui/react": "*",
@@ -62,6 +83,6 @@
62
83
  }
63
84
  },
64
85
  "devDependencies": {
65
- "pkgroll": "^2.5.1"
86
+ "pkgroll": "^2.21.4"
66
87
  }
67
88
  }
@@ -0,0 +1,26 @@
1
+ import dotenv from 'dotenv'
2
+ import { findDotOriginalFiles, restoreOriginalFile } from '../interceptors/writeInterceptors'
3
+
4
+ dotenv.config({ quiet: true })
5
+
6
+ export async function cleanupInterceptors(cwd: string = process.cwd()) {
7
+ console.info('🧹 Starting interceptor cleanup...')
8
+
9
+ let restoredCount = 0
10
+ let removedCount = 0
11
+
12
+ const originalFiles = await findDotOriginalFiles(cwd)
13
+ console.info(`📂 Found ${originalFiles.length} .original files to restore`)
14
+
15
+ for (const originalFile of originalFiles) {
16
+ try {
17
+ await restoreOriginalFile(originalFile)
18
+ removedCount++
19
+ } catch (error) {
20
+ console.error(`❌ Failed to restore ${originalFile}:`, error)
21
+ }
22
+ }
23
+
24
+ console.info('✅ Interceptor cleanup completed!')
25
+ console.info(`📊 ${restoredCount} files restored from .original`)
26
+ }
@@ -1,18 +1,16 @@
1
- import { generateConfig } from '../config/commands/generateConfig'
2
- import { codegenInterceptors } from '../interceptors/commands/codegenInterceptors'
3
- import { copyFiles } from './copyFiles'
1
+ import { spawn } from 'child_process'
4
2
 
5
- /** Run all code generation steps in sequence */
6
- export async function codegen() {
7
- // Copy files from packages to project
8
- console.info('🔄 Copying files from packages to project...')
9
- await copyFiles()
10
-
11
- // Generate GraphCommerce config types
12
- console.info('⚙️ Generating GraphCommerce config types...')
13
- await generateConfig()
3
+ function run(cmd: string): Promise<void> {
4
+ return new Promise((resolve, reject) => {
5
+ const child = spawn(cmd, { stdio: 'inherit', cwd: process.cwd(), shell: true })
6
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`${cmd} failed`))))
7
+ })
8
+ }
14
9
 
15
- // Generate interceptors
16
- console.info('🔌 Generating interceptors...')
17
- await codegenInterceptors()
10
+ /** Run all code generation steps in sequence using separate processes */
11
+ export async function codegen() {
12
+ await run('graphcommerce copy-files')
13
+ await run('graphcommerce codegen-config')
14
+ await run('graphcommerce codegen-config-values')
15
+ await run('graphcommerce codegen-interceptors')
18
16
  }
@@ -0,0 +1,31 @@
1
+ import dotenv from 'dotenv'
2
+ import { loadConfig } from '../config/loadConfig'
3
+ import { findPlugins } from '../interceptors/findPlugins'
4
+ import { generateInterceptors } from '../interceptors/generateInterceptors'
5
+ import { updatePackageExports } from '../interceptors/updatePackageExports'
6
+ import { writeInterceptors } from '../interceptors/writeInterceptors'
7
+ import { resolveDependency } from '../utils/resolveDependency'
8
+
9
+ dotenv.config({ quiet: true })
10
+
11
+ // eslint-disable-next-line @typescript-eslint/require-await
12
+ export async function codegenInterceptors() {
13
+ const conf = loadConfig(process.cwd())
14
+
15
+ const [plugins] = findPlugins(conf)
16
+
17
+ // Update package.json exports before generating interceptors
18
+ console.info('🔄 Updating package.json exports for plugins...')
19
+ await updatePackageExports(plugins)
20
+
21
+ const generatedInterceptors = await generateInterceptors(
22
+ plugins,
23
+ resolveDependency(),
24
+ conf.debug,
25
+ true,
26
+ )
27
+
28
+ await writeInterceptors(generatedInterceptors)
29
+
30
+ console.info('✅ Generated interceptors and moved original files')
31
+ }
@@ -1,8 +1,8 @@
1
1
  import dotenv from 'dotenv'
2
- import { loadConfig } from '../loadConfig'
3
- import { exportConfigToEnv } from '../utils/exportConfigToEnv'
2
+ import { loadConfig } from '../config/loadConfig'
3
+ import { exportConfigToEnv } from '../config/utils/exportConfigToEnv'
4
4
 
5
- dotenv.config()
5
+ dotenv.config({ quiet: true })
6
6
 
7
7
  // eslint-disable-next-line @typescript-eslint/require-await
8
8
  export async function exportConfig() {
@@ -4,17 +4,14 @@ import { generate } from '@graphql-codegen/cli'
4
4
  import { transformFileSync } from '@swc/core'
5
5
  import dotenv from 'dotenv'
6
6
  import prettier from 'prettier'
7
- import { findParentPath } from '../../utils/isMonorepo'
8
- import { resolveDependenciesSync } from '../../utils/resolveDependenciesSync'
9
- import { resolveDependency } from '../../utils/resolveDependency'
10
-
11
- dotenv.config()
7
+ import { findParentPath } from '../utils/findParentPath'
8
+ import { resolveDependenciesSync } from '../utils/resolveDependenciesSync'
9
+ import { resolveDependency } from '../utils/resolveDependency'
12
10
 
13
11
  const packages = [...resolveDependenciesSync().values()].filter((p) => p !== '.')
14
-
15
12
  const resolve = resolveDependency()
16
13
 
17
- const schemaLocations = packages.map((p) => `${p}/**/Config.graphqls`)
14
+ dotenv.config({ quiet: true })
18
15
 
19
16
  export async function generateConfig() {
20
17
  const resolved = resolve('@graphcommerce/next-config')
@@ -23,9 +20,15 @@ export async function generateConfig() {
23
20
  const targetTs = `${resolved.root}/src/generated/config.ts`
24
21
  const targetJs = `${resolved.root}/dist/generated/config.js`
25
22
 
23
+ // Use specific patterns instead of ** to avoid expensive directory traversal
24
+ const schemaLocations = [
25
+ 'graphql/Config.graphqls',
26
+ ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`]),
27
+ ]
28
+
26
29
  await generate({
27
30
  silent: true,
28
- schema: ['graphql/**/Config.graphqls', ...schemaLocations],
31
+ schema: schemaLocations,
29
32
  generates: {
30
33
  [targetTs]: {
31
34
  plugins: ['typescript', 'typescript-validation-schema'],
@@ -63,7 +66,7 @@ export async function generateConfig() {
63
66
 
64
67
  const result = transformFileSync(targetTs, {
65
68
  module: { type: 'nodenext' },
66
- env: { targets: { node: '18' } },
69
+ env: { targets: { node: '20' } },
67
70
  })
68
71
 
69
72
  writeFileSync(targetJs, result.code)