@graphcommerce/next-config 9.0.4-canary.9 → 9.1.0-canary.16

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 (53) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/__tests__/config/utils/mergeEnvIntoConfig.ts +12 -1
  3. package/__tests__/config/utils/replaceConfigInString.ts +0 -1
  4. package/__tests__/interceptors/findPlugins.ts +301 -254
  5. package/__tests__/utils/resolveDependenciesSync.ts +44 -44
  6. package/dist/generated/config.js +109 -120
  7. package/dist/index.js +3359 -26
  8. package/package.json +33 -8
  9. package/src/config/commands/generateConfig.ts +16 -4
  10. package/src/config/demoConfig.ts +0 -1
  11. package/src/config/loadConfig.ts +3 -9
  12. package/src/config/utils/mergeEnvIntoConfig.ts +8 -6
  13. package/src/generated/config.ts +11 -5
  14. package/src/interceptors/generateInterceptor.ts +0 -2
  15. package/src/interceptors/parseStructure.ts +3 -3
  16. package/src/utils/resolveDependenciesSync.ts +43 -6
  17. package/src/withGraphCommerce.ts +30 -42
  18. package/tsconfig.json +1 -1
  19. package/__tests__/config/utils/rewriteLegancyEnv.ts +0 -79
  20. package/dist/commands/codegen.js +0 -18
  21. package/dist/commands/copyFiles.js +0 -297
  22. package/dist/config/commands/exportConfig.js +0 -16
  23. package/dist/config/commands/generateConfig.js +0 -56
  24. package/dist/config/demoConfig.js +0 -52
  25. package/dist/config/index.js +0 -19
  26. package/dist/config/loadConfig.js +0 -62
  27. package/dist/config/utils/configToImportMeta.js +0 -39
  28. package/dist/config/utils/diff.js +0 -33
  29. package/dist/config/utils/exportConfigToEnv.js +0 -31
  30. package/dist/config/utils/mergeEnvIntoConfig.js +0 -182
  31. package/dist/config/utils/replaceConfigInString.js +0 -12
  32. package/dist/config/utils/rewriteLegacyEnv.js +0 -115
  33. package/dist/interceptors/InterceptorPlugin.js +0 -108
  34. package/dist/interceptors/RenameVisitor.js +0 -19
  35. package/dist/interceptors/Visitor.js +0 -1414
  36. package/dist/interceptors/commands/codegenInterceptors.js +0 -22
  37. package/dist/interceptors/extractExports.js +0 -159
  38. package/dist/interceptors/findOriginalSource.js +0 -103
  39. package/dist/interceptors/findPlugins.js +0 -68
  40. package/dist/interceptors/generateInterceptor.js +0 -219
  41. package/dist/interceptors/generateInterceptors.js +0 -56
  42. package/dist/interceptors/parseStructure.js +0 -84
  43. package/dist/interceptors/swc.js +0 -15
  44. package/dist/interceptors/writeInterceptors.js +0 -44
  45. package/dist/utils/PackagesSort.js +0 -7
  46. package/dist/utils/TopologicalSort.js +0 -87
  47. package/dist/utils/isMonorepo.js +0 -47
  48. package/dist/utils/packageRoots.js +0 -31
  49. package/dist/utils/resolveDependenciesSync.js +0 -78
  50. package/dist/utils/resolveDependency.js +0 -70
  51. package/dist/utils/sig.js +0 -34
  52. package/dist/withGraphCommerce.js +0 -162
  53. package/src/config/utils/rewriteLegacyEnv.ts +0 -125
@@ -1,182 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.toEnvStr = void 0;
7
- exports.configToEnvSchema = configToEnvSchema;
8
- exports.mergeEnvIntoConfig = mergeEnvIntoConfig;
9
- exports.formatAppliedEnv = formatAppliedEnv;
10
- /* eslint-disable import/no-extraneous-dependencies */
11
- const utilities_1 = require("@apollo/client/utilities");
12
- const chalk_1 = __importDefault(require("chalk"));
13
- const lodash_1 = require("lodash");
14
- const snakeCase_1 = __importDefault(require("lodash/snakeCase"));
15
- const zod_1 = require("zod");
16
- const diff_1 = __importDefault(require("./diff"));
17
- const fmt = (s) => s.split(/(\d+)/).map(snakeCase_1.default).join('');
18
- const toEnvStr = (path) => ['GC', ...path].map(fmt).join('_').toUpperCase();
19
- exports.toEnvStr = toEnvStr;
20
- const dotNotation = (pathParts) => pathParts
21
- .map((v) => {
22
- const idx = Number(v);
23
- return !Number.isNaN(idx) ? `[${idx}]` : v;
24
- })
25
- .join('.');
26
- function isJSON(str) {
27
- if (!str)
28
- return true;
29
- try {
30
- JSON.parse(str);
31
- }
32
- catch (e) {
33
- return false;
34
- }
35
- return true;
36
- }
37
- function configToEnvSchema(schema) {
38
- const envSchema = {};
39
- const envToDot = {};
40
- function walk(incomming, path = []) {
41
- let node = incomming;
42
- if (node instanceof zod_1.ZodEffects)
43
- node = node.innerType();
44
- if (node instanceof zod_1.ZodOptional)
45
- node = node.unwrap();
46
- if (node instanceof zod_1.ZodNullable)
47
- node = node.unwrap();
48
- if (node instanceof zod_1.ZodDefault)
49
- node = node.removeDefault();
50
- if (node instanceof zod_1.ZodObject) {
51
- if (path.length > 0) {
52
- envSchema[(0, exports.toEnvStr)(path)] = zod_1.z
53
- .string()
54
- .optional()
55
- .refine(isJSON, { message: 'Invalid JSON' })
56
- .transform((val) => (val ? JSON.parse(val) : val));
57
- envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path);
58
- }
59
- const typeNode = node;
60
- Object.keys(typeNode.shape).forEach((key) => {
61
- walk(typeNode.shape[key], [...path, key]);
62
- });
63
- return;
64
- }
65
- if (node instanceof zod_1.ZodArray) {
66
- const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
67
- if (path.length > 0) {
68
- envSchema[(0, exports.toEnvStr)(path)] = zod_1.z
69
- .string()
70
- .optional()
71
- .refine(isJSON, { message: 'Invalid JSON' })
72
- .transform((val) => (val ? JSON.parse(val) : val));
73
- envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path);
74
- }
75
- arr.forEach((key) => {
76
- walk(node.element, [...path, String(key)]);
77
- });
78
- return;
79
- }
80
- if (node instanceof zod_1.ZodNumber) {
81
- envSchema[(0, exports.toEnvStr)(path)] = zod_1.z.coerce.number().optional();
82
- envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path);
83
- return;
84
- }
85
- if (node instanceof zod_1.ZodString || node instanceof zod_1.ZodEnum) {
86
- envSchema[(0, exports.toEnvStr)(path)] = node.optional();
87
- envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path);
88
- return;
89
- }
90
- if (node instanceof zod_1.ZodBoolean) {
91
- envSchema[(0, exports.toEnvStr)(path)] = zod_1.z
92
- .enum(['true', '1', 'false', '0'])
93
- .optional()
94
- .transform((v) => {
95
- if (v === 'true' || v === '1')
96
- return true;
97
- if (v === 'false' || v === '0')
98
- return false;
99
- return v;
100
- });
101
- envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path);
102
- return;
103
- }
104
- throw Error(`[@graphcommerce/next-config] Unknown type in schema ${node.constructor.name}. This is probably a bug please create an issue.`);
105
- }
106
- walk(schema);
107
- return [zod_1.z.object(envSchema), envToDot];
108
- }
109
- const filterEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith('GC_')));
110
- function mergeEnvIntoConfig(schema, config, env) {
111
- const filteredEnv = filterEnv(env);
112
- const newConfig = (0, utilities_1.cloneDeep)(config);
113
- const [envSchema, envToDot] = configToEnvSchema(schema);
114
- const result = envSchema.safeParse(filteredEnv);
115
- const applyResult = [];
116
- if (!result.success) {
117
- Object.entries(result.error.flatten().fieldErrors).forEach(([envVar, error]) => {
118
- const dotVar = envToDot[envVar];
119
- const envValue = filteredEnv[envVar];
120
- applyResult.push({ envVar, envValue, dotVar, error });
121
- });
122
- return [undefined, applyResult];
123
- }
124
- Object.entries(result.data).forEach(([envVar, value]) => {
125
- const dotVar = envToDot[envVar];
126
- const envValue = filteredEnv[envVar];
127
- if (!dotVar) {
128
- applyResult.push({ envVar, envValue });
129
- return;
130
- }
131
- const dotValue = (0, lodash_1.get)(newConfig, dotVar);
132
- const merged = (0, utilities_1.mergeDeep)(dotValue, value);
133
- const from = (0, diff_1.default)(merged, dotValue);
134
- const to = (0, diff_1.default)(dotValue, merged);
135
- applyResult.push({ envVar, envValue, dotVar, from, to });
136
- (0, lodash_1.set)(newConfig, dotVar, merged);
137
- });
138
- return [newConfig, applyResult];
139
- }
140
- /**
141
- * Prints the applied env variables to the console
142
- *
143
- * The format is:
144
- *
145
- * - If from and to is empty, the value is unchanged: `=` (white)
146
- * - If the from is empty, a new value is applied: `+` (green)
147
- * - If the to is empty, a value is removed: `-` (red)
148
- * - If both from and to is not empty, a value is changed: `~` (yellow)
149
- */
150
- function formatAppliedEnv(applyResult) {
151
- let hasError = false;
152
- let hasWarning = false;
153
- const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => {
154
- const envVariableFmt = `${envVar}`;
155
- const dotVariableFmt = chalk_1.default.bold.underline(`${dotVar}`);
156
- const baseLog = `${envVariableFmt} => ${dotVariableFmt}`;
157
- if (error) {
158
- hasError = true;
159
- return `${chalk_1.default.red(` ⨉ ${envVariableFmt}`)} => ${error.join(', ')}`;
160
- }
161
- if (warning) {
162
- hasWarning = true;
163
- return `${chalk_1.default.yellowBright(` ‼ ${envVariableFmt}`)} => ${warning.join(', ')}`;
164
- }
165
- if (!dotVar)
166
- return chalk_1.default.red(`${envVariableFmt} => ignored (no matching config)`);
167
- if (from === undefined && to === undefined)
168
- return ` = ${baseLog}: (ignored)`;
169
- if (from === undefined && to !== undefined)
170
- return ` ${chalk_1.default.green('+')} ${baseLog}`;
171
- if (from !== undefined && to === undefined)
172
- return ` ${chalk_1.default.red('-')} ${baseLog}`;
173
- return ` ${chalk_1.default.yellowBright('~')} ${baseLog}`;
174
- });
175
- let header = chalk_1.default.blueBright('info');
176
- if (hasWarning)
177
- header = chalk_1.default.yellowBright('warning');
178
- if (hasError)
179
- header = chalk_1.default.yellowBright('error');
180
- header += ' - Loaded GraphCommerce env variables';
181
- return [header, ...lines].join('\n');
182
- }
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.replaceConfigInString = replaceConfigInString;
4
- const configToImportMeta_1 = require("./configToImportMeta");
5
- function replaceConfigInString(str, config) {
6
- let result = str;
7
- const replacers = (0, configToImportMeta_1.configToImportMeta)(config, 'graphCommerce', false);
8
- Object.entries(replacers).forEach(([from, to]) => {
9
- result = result.replace(new RegExp(`{${from}}`, 'g'), to);
10
- });
11
- return result;
12
- }
@@ -1,115 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.rewriteLegacyEnv = rewriteLegacyEnv;
7
- const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
8
- const mergeEnvIntoConfig_1 = require("./mergeEnvIntoConfig");
9
- function rewriteLegacyEnv(schema, env, config = {}) {
10
- const clonedEnv = (0, cloneDeep_1.default)(env);
11
- const applied = [];
12
- function renamedTo(to) {
13
- return (envVar, envValue) => {
14
- applied.push({
15
- warning: [`should be renamed to ${to}='${envValue}'`],
16
- envVar,
17
- envValue,
18
- });
19
- clonedEnv[to] = envValue;
20
- };
21
- }
22
- function notUsed() {
23
- return (envVar, envValue) => {
24
- applied.push({
25
- warning: ['should be removed'],
26
- envVar,
27
- envValue,
28
- });
29
- };
30
- }
31
- const parsers = {
32
- MAGENTO_ENDPOINT: renamedTo('GC_MAGENTO_ENDPOINT'),
33
- GRAPHCMS_URL: renamedTo('GC_HYGRAPH_ENDPOINT'),
34
- NEXT_PUBLIC_GRAPHQL_ENDPOINT: notUsed(),
35
- IMAGE_DOMAINS: (envVar, envValue) => {
36
- applied.push({
37
- warning: [
38
- 'should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options',
39
- ],
40
- envVar,
41
- envValue,
42
- });
43
- },
44
- NEXT_PUBLIC_LOCALE_STORES: (envVar, envValue) => {
45
- const parsed = JSON.parse(envValue);
46
- applied.push({
47
- warning: ['env variable is is modified, rewritten to GC_STOREFRONT.'],
48
- envVar,
49
- envValue,
50
- });
51
- clonedEnv.GC_STOREFRONT = JSON.stringify(Object.entries(parsed).map(([locale, magentoStoreCode], index) => {
52
- if (!config.storefront)
53
- config.storefront = [];
54
- config.storefront[index] = { ...config.storefront[index], locale, magentoStoreCode };
55
- return { locale, magentoStoreCode };
56
- }));
57
- },
58
- NEXT_PUBLIC_SITE_URL: renamedTo('GC_CANONICAL_BASE_URL'),
59
- NEXT_PUBLIC_GTM_ID: renamedTo('GC_GOOGLE_TAGMANAGER_ID'),
60
- NEXT_PUBLIC_GOOGLE_ANALYTICS: (envVar, envValue) => {
61
- if (envValue.startsWith('{')) {
62
- const parsed = JSON.parse(envValue);
63
- clonedEnv.GC_GOOGLE_ANALYTICS_ID = 'enabled';
64
- if (!config.storefront)
65
- config.storefront = [];
66
- config.storefront.forEach((storefront, index) => {
67
- if (parsed[storefront.locale]) {
68
- clonedEnv[`GC_STOREFRONT_${index}_GOOGLE_ANALYTICS_ID`] = parsed[storefront.locale];
69
- }
70
- });
71
- applied.push({
72
- warning: ['should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID'],
73
- envVar,
74
- envValue,
75
- });
76
- return;
77
- }
78
- renamedTo('GC_GOOGLE_ANALYTICS_ID');
79
- },
80
- NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: renamedTo('GC_GOOGLE_RECAPTCHA_KEY'),
81
- NEXT_PUBLIC_DISPLAY_INCL_TAX: (envVar, envValue) => {
82
- const inclTax = envValue.split(',').map((i) => i.trim());
83
- if (!config.storefront)
84
- config.storefront = [];
85
- config.storefront.forEach((storefront, index) => {
86
- if (!inclTax.includes(storefront.locale))
87
- return;
88
- clonedEnv[`GC_STOREFRONT_${index}_CART_DISPLAY_PRICES_INCL_TAX`] = '1';
89
- });
90
- applied.push({
91
- warning: ['env variable is renamed, move to configuration: cartDisplayPricesInclTax'],
92
- envVar,
93
- envValue,
94
- });
95
- clonedEnv.GC_DISPLAY_PRICES_INCL_TAX = envValue;
96
- },
97
- PREVIEW_SECRET: renamedTo('GC_PREVIEW_SECRET'),
98
- DEMO_MAGENTO_GRAPHCOMMERCE: renamedTo('GC_DEMO_MODE'),
99
- };
100
- if (env.SKIP_MIGRATION === '1' || env.SKIP_MIGRATION === 'true') {
101
- return (0, mergeEnvIntoConfig_1.mergeEnvIntoConfig)(schema, config, clonedEnv);
102
- }
103
- Object.entries(env).forEach(([key, value]) => {
104
- if (value === undefined)
105
- return;
106
- try {
107
- parsers[key]?.(key, value);
108
- }
109
- catch (e) {
110
- console.error(`Error parsing ${key}`, e);
111
- }
112
- });
113
- const [newConfig, envApplied] = (0, mergeEnvIntoConfig_1.mergeEnvIntoConfig)(schema, config, clonedEnv);
114
- return [newConfig, [...applied, ...envApplied]];
115
- }
@@ -1,108 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.InterceptorPlugin = void 0;
7
- const path_1 = __importDefault(require("path"));
8
- const resolveDependency_1 = require("../utils/resolveDependency");
9
- const findPlugins_1 = require("./findPlugins");
10
- const generateInterceptors_1 = require("./generateInterceptors");
11
- const writeInterceptors_1 = require("./writeInterceptors");
12
- let interceptors;
13
- let interceptorByDepependency;
14
- let generating = false;
15
- // let totalGenerationTime = 0
16
- class InterceptorPlugin {
17
- config;
18
- regenerate;
19
- resolveDependency;
20
- constructor(config, regenerate = false) {
21
- this.config = config;
22
- this.regenerate = regenerate;
23
- this.resolveDependency = (0, resolveDependency_1.resolveDependency)();
24
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
25
- if (regenerate)
26
- this.#generateInterceptors();
27
- }
28
- #generateInterceptors = async () => {
29
- if (generating)
30
- return {};
31
- generating = true;
32
- // const start = Date.now()
33
- // console.log('Generating interceptors...')
34
- const [plugins] = (0, findPlugins_1.findPlugins)(this.config);
35
- // console.log(errors)
36
- // const found = Date.now()
37
- // console.log('Found plugins in', found - start, 'ms')
38
- const generatedInterceptors = await (0, generateInterceptors_1.generateInterceptors)(plugins, this.resolveDependency, this.config.debug);
39
- // const generated = Date.now()
40
- // console.log('Generated interceptors in', generated - found, 'ms')
41
- await (0, writeInterceptors_1.writeInterceptors)(generatedInterceptors);
42
- // const wrote = Date.now()
43
- // console.log('Wrote interceptors in', wrote - generated, 'ms')
44
- interceptors = generatedInterceptors;
45
- interceptorByDepependency = Object.fromEntries(Object.values(interceptors).map((i) => [i.dependency, i]));
46
- // totalGenerationTime += Date.now() - start
47
- generating = false;
48
- return generatedInterceptors;
49
- };
50
- /** @public */
51
- apply(compiler) {
52
- const logger = compiler.getInfrastructureLogger('InterceptorPlugin');
53
- // After the compilation has succeeded we watch all possible plugin locations.
54
- if (this.regenerate) {
55
- compiler.hooks.afterCompile.tap('InterceptorPlugin', (compilation) => {
56
- // console.log('generate interceptors after compile')
57
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
58
- const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config);
59
- plugins.forEach((p) => {
60
- const source = this.resolveDependency(p.sourceModule);
61
- if (source) {
62
- const absoluteFilePath = `${path_1.default.join(process.cwd(), source.fromRoot)}.tsx`;
63
- compilation.fileDependencies.add(absoluteFilePath);
64
- }
65
- });
66
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
67
- this.#generateInterceptors().then((i) => {
68
- Object.entries(i).forEach(([, { sourcePath }]) => {
69
- const absoluteFilePath = path_1.default.join(process.cwd(), sourcePath);
70
- compilation.fileDependencies.add(absoluteFilePath);
71
- });
72
- });
73
- });
74
- }
75
- compiler.hooks.normalModuleFactory.tap('InterceptorPlugin', (nmf) => {
76
- nmf.hooks.beforeResolve.tap('InterceptorPlugin', (resource) => {
77
- const issuer = resource.contextInfo.issuer ?? '';
78
- const requestPath = path_1.default.relative(process.cwd(), path_1.default.resolve(resource.context, resource.request));
79
- if (!interceptors || !interceptorByDepependency) {
80
- // console.log('interceptors not ready')
81
- return;
82
- }
83
- const split = requestPath.split('/');
84
- const targets = [
85
- `${split[split.length - 1]}.interceptor.tsx`,
86
- `${split[split.length - 1]}.interceptor.ts`,
87
- ];
88
- if (targets.some((target) => issuer.endsWith(target)) && interceptors[requestPath]) {
89
- logger.log(`Interceptor ${issuer} is requesting the original ${requestPath}`);
90
- return;
91
- }
92
- const interceptorForRequest = interceptorByDepependency[resource.request];
93
- if (interceptorForRequest) {
94
- const extension = interceptorForRequest.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts';
95
- resource.request = `${interceptorForRequest.denormalized}.interceptor${extension}`;
96
- logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`, resource.request);
97
- }
98
- const interceptorForPath = interceptors[requestPath];
99
- if (interceptorForPath) {
100
- const extension = interceptorForPath.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts';
101
- resource.request = `${resource.request}.interceptor${extension}`;
102
- logger.log(`Intercepting fromRoot... ${interceptorForPath.dependency}`, resource.request);
103
- }
104
- });
105
- });
106
- }
107
- }
108
- exports.InterceptorPlugin = InterceptorPlugin;
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RenameVisitor = void 0;
4
- const Visitor_1 = require("./Visitor");
5
- class RenameVisitor extends Visitor_1.Visitor {
6
- replace;
7
- suffix;
8
- constructor(replace, suffix) {
9
- super();
10
- this.replace = replace;
11
- this.suffix = suffix;
12
- }
13
- visitIdentifier(n) {
14
- if (this.replace.includes(n.value))
15
- n.value = this.suffix(n.value);
16
- return n;
17
- }
18
- }
19
- exports.RenameVisitor = RenameVisitor;