@graphcommerce/next-config 9.0.4-canary.0 → 9.0.4-canary.10

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 (61) hide show
  1. package/CHANGELOG.md +28 -8
  2. package/__tests__/commands/copyFiles.ts +8 -5
  3. package/__tests__/config/utils/__snapshots__/mergeEnvIntoConfig.ts.snap +0 -905
  4. package/__tests__/config/utils/mergeEnvIntoConfig.ts +21 -3
  5. package/__tests__/config/utils/replaceConfigInString.ts +0 -1
  6. package/__tests__/interceptors/findPlugins.ts +270 -272
  7. package/__tests__/interceptors/generateInterceptors.ts +1 -0
  8. package/__tests__/utils/resolveDependenciesSync.ts +45 -44
  9. package/dist/generated/config.js +110 -116
  10. package/dist/index.js +3359 -26
  11. package/package.json +34 -8
  12. package/src/commands/codegen.ts +3 -3
  13. package/src/commands/copyFiles.ts +14 -7
  14. package/src/config/commands/generateConfig.ts +17 -6
  15. package/src/config/demoConfig.ts +0 -1
  16. package/src/config/loadConfig.ts +3 -9
  17. package/src/config/utils/mergeEnvIntoConfig.ts +9 -9
  18. package/src/generated/config.ts +305 -245
  19. package/src/interceptors/Visitor.ts +1 -1
  20. package/src/interceptors/findOriginalSource.ts +1 -1
  21. package/src/interceptors/generateInterceptor.ts +0 -2
  22. package/src/interceptors/parseStructure.ts +3 -3
  23. package/src/interceptors/writeInterceptors.ts +1 -1
  24. package/src/utils/resolveDependenciesSync.ts +44 -7
  25. package/src/withGraphCommerce.ts +30 -42
  26. package/tsconfig.json +1 -1
  27. package/__tests__/config/utils/rewriteLegancyEnv.ts +0 -78
  28. package/dist/commands/codegen.js +0 -18
  29. package/dist/commands/copyFiles.js +0 -292
  30. package/dist/config/commands/exportConfig.js +0 -16
  31. package/dist/config/commands/generateConfig.js +0 -57
  32. package/dist/config/demoConfig.js +0 -52
  33. package/dist/config/index.js +0 -19
  34. package/dist/config/loadConfig.js +0 -62
  35. package/dist/config/utils/configToImportMeta.js +0 -39
  36. package/dist/config/utils/diff.js +0 -33
  37. package/dist/config/utils/exportConfigToEnv.js +0 -31
  38. package/dist/config/utils/mergeEnvIntoConfig.js +0 -184
  39. package/dist/config/utils/replaceConfigInString.js +0 -12
  40. package/dist/config/utils/rewriteLegacyEnv.js +0 -115
  41. package/dist/interceptors/InterceptorPlugin.js +0 -108
  42. package/dist/interceptors/RenameVisitor.js +0 -19
  43. package/dist/interceptors/Visitor.js +0 -1414
  44. package/dist/interceptors/commands/codegenInterceptors.js +0 -22
  45. package/dist/interceptors/extractExports.js +0 -159
  46. package/dist/interceptors/findOriginalSource.js +0 -103
  47. package/dist/interceptors/findPlugins.js +0 -68
  48. package/dist/interceptors/generateInterceptor.js +0 -219
  49. package/dist/interceptors/generateInterceptors.js +0 -56
  50. package/dist/interceptors/parseStructure.js +0 -84
  51. package/dist/interceptors/swc.js +0 -15
  52. package/dist/interceptors/writeInterceptors.js +0 -44
  53. package/dist/utils/PackagesSort.js +0 -7
  54. package/dist/utils/TopologicalSort.js +0 -87
  55. package/dist/utils/isMonorepo.js +0 -47
  56. package/dist/utils/packageRoots.js +0 -31
  57. package/dist/utils/resolveDependenciesSync.js +0 -78
  58. package/dist/utils/resolveDependency.js +0 -70
  59. package/dist/utils/sig.js +0 -34
  60. package/dist/withGraphCommerce.js +0 -162
  61. package/src/config/utils/rewriteLegacyEnv.ts +0 -125
@@ -1,84 +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.parseStructure = parseStructure;
7
- const get_1 = __importDefault(require("lodash/get"));
8
- const zod_1 = require("zod");
9
- const extractExports_1 = require("./extractExports");
10
- const pluginConfigParsed = zod_1.z.object({
11
- type: zod_1.z.enum(['component', 'function', 'replace']),
12
- module: zod_1.z.string(),
13
- export: zod_1.z.string(),
14
- ifConfig: zod_1.z.union([zod_1.z.string(), zod_1.z.tuple([zod_1.z.string(), zod_1.z.unknown()])]).optional(),
15
- });
16
- function nonNullable(value) {
17
- return value !== null && value !== undefined;
18
- }
19
- const isObject = (input) => typeof input === 'object' && input !== null && !Array.isArray(input);
20
- function parseStructure(ast, gcConfig, sourceModule) {
21
- const [exports, errors] = (0, extractExports_1.extractExports)(ast);
22
- if (errors.length)
23
- console.error('Plugin error for', errors.join('\n'));
24
- const { config: moduleConfig, component, func, exported, ifConfig, plugin, Plugin, ...rest } = exports;
25
- const exportVals = Object.keys(rest);
26
- if (component && !moduleConfig)
27
- exportVals.push('Plugin');
28
- if (func && !moduleConfig)
29
- exportVals.push('plugin');
30
- const pluginConfigs = exportVals
31
- .map((exportVal) => {
32
- let config = isObject(moduleConfig) ? moduleConfig : {};
33
- if (!moduleConfig && component) {
34
- config = { type: 'component', module: exported, ifConfig, export: 'Plugin' };
35
- }
36
- else if (!moduleConfig && func) {
37
- config = { type: 'function', module: exported, ifConfig, export: 'plugin' };
38
- }
39
- else if (isObject(moduleConfig)) {
40
- config = { ...moduleConfig, export: exportVal };
41
- }
42
- else {
43
- console.error(`Plugin configuration invalid! See ${sourceModule}`);
44
- return null;
45
- }
46
- const parsed = pluginConfigParsed.safeParse(config);
47
- if (!parsed.success) {
48
- if (errors.length)
49
- console.error(parsed.error.errors.map((e) => `${e.path} ${e.message}`).join('\n'));
50
- return undefined;
51
- }
52
- let enabled = true;
53
- if (parsed.data.ifConfig) {
54
- if (Array.isArray(parsed.data.ifConfig)) {
55
- const isBoolean = typeof parsed.data.ifConfig[1] === 'boolean';
56
- let confValue = (0, get_1.default)(gcConfig, parsed.data.ifConfig[0]);
57
- confValue = isBoolean ? Boolean(confValue) : confValue;
58
- enabled = confValue === parsed.data.ifConfig[1];
59
- }
60
- else {
61
- enabled = Boolean((0, get_1.default)(gcConfig, parsed.data.ifConfig));
62
- }
63
- }
64
- const val = {
65
- targetExport: exports.component || exports.func || parsed.data.export,
66
- sourceModule,
67
- sourceExport: parsed.data.export,
68
- targetModule: parsed.data.module,
69
- type: parsed.data.type,
70
- enabled,
71
- };
72
- if (parsed.data.ifConfig)
73
- val.ifConfig = parsed.data.ifConfig;
74
- return val;
75
- })
76
- .filter(nonNullable);
77
- const newPluginConfigs = pluginConfigs.reduce((acc, pluginConfig) => {
78
- if (!acc.find((accPluginConfig) => accPluginConfig.sourceExport === pluginConfig.sourceExport)) {
79
- acc.push(pluginConfig);
80
- }
81
- return acc;
82
- }, []);
83
- return newPluginConfigs;
84
- }
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseSync = parseSync;
4
- exports.printSync = printSync;
5
- const core_1 = require("@swc/core");
6
- function parseSync(src) {
7
- return (0, core_1.parseSync)(src, {
8
- syntax: 'typescript',
9
- tsx: true,
10
- comments: true,
11
- });
12
- }
13
- function printSync(m) {
14
- return (0, core_1.printSync)(m);
15
- }
@@ -1,44 +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.writeInterceptors = writeInterceptors;
7
- // eslint-disable-next-line import/no-extraneous-dependencies
8
- const glob_1 = require("glob");
9
- const promises_1 = __importDefault(require("node:fs/promises"));
10
- const path_1 = __importDefault(require("path"));
11
- const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync");
12
- function checkFileExists(file) {
13
- return promises_1.default
14
- .access(file, promises_1.default.constants.F_OK)
15
- .then(() => true)
16
- .catch(() => false);
17
- }
18
- async function writeInterceptors(interceptors, cwd = process.cwd()) {
19
- const dependencies = (0, resolveDependenciesSync_1.resolveDependenciesSync)(cwd);
20
- const existing = new Set();
21
- dependencies.forEach((dependency) => {
22
- const files = (0, glob_1.sync)([`${dependency}/**/*.interceptor.tsx`, `${dependency}/**/*.interceptor.ts`], { cwd });
23
- files.forEach((file) => existing.add(file));
24
- });
25
- const written = Object.entries(interceptors).map(async ([, plugin]) => {
26
- const extension = plugin.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts';
27
- const relativeFile = `${plugin.fromRoot}.interceptor${extension}`;
28
- if (existing.has(relativeFile)) {
29
- existing.delete(relativeFile);
30
- }
31
- if (existing.has(`./${relativeFile}`)) {
32
- existing.delete(`./${relativeFile}`);
33
- }
34
- const fileToWrite = path_1.default.join(cwd, relativeFile);
35
- const isSame = (await checkFileExists(fileToWrite)) &&
36
- (await promises_1.default.readFile(fileToWrite, 'utf8')).toString() === plugin.template;
37
- if (!isSame)
38
- await promises_1.default.writeFile(fileToWrite, plugin.template);
39
- });
40
- // Cleanup unused interceptors
41
- const cleaned = [...existing].map(async (file) => (await checkFileExists(file)) && (await promises_1.default.unlink(file)));
42
- await Promise.all(written);
43
- await Promise.all(cleaned);
44
- }
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PackagesSort = void 0;
4
- const TopologicalSort_1 = require("./TopologicalSort");
5
- class PackagesSort extends TopologicalSort_1.TopologicalSort {
6
- }
7
- exports.PackagesSort = PackagesSort;
@@ -1,87 +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.TopologicalSort = void 0;
7
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
8
- const assert_1 = __importDefault(require("assert"));
9
- class TopologicalSort {
10
- #nodes;
11
- #visitedNodes;
12
- #sortedKeysStack;
13
- constructor(nodes) {
14
- this.#nodes = new Map();
15
- this.addMultipleInternalNodes(nodes);
16
- }
17
- /** @public */
18
- addNode(key, node) {
19
- return this.addInternalNode(key, node);
20
- }
21
- /** @public */
22
- addNodes(nodes) {
23
- this.addMultipleInternalNodes(nodes);
24
- }
25
- /** @public */
26
- addEdge(fromKey, toKey) {
27
- (0, assert_1.default)(this.#nodes.has(fromKey), `Source package with ${fromKey} key should exist`);
28
- (0, assert_1.default)(this.#nodes.has(toKey), `Target package with ${toKey} key should exist`);
29
- const sourceNode = this.#nodes.get(fromKey);
30
- const targetNode = this.#nodes.get(toKey);
31
- assert_1.default.strictEqual(sourceNode !== undefined, true, `Source package with key ${fromKey} doesn't exist`);
32
- assert_1.default.strictEqual(targetNode !== undefined, true, `Target package with key ${toKey} doesn't exist`);
33
- assert_1.default.strictEqual(sourceNode.children.has(toKey), false, `Source package ${fromKey} already has an edge to target node ${toKey}`);
34
- sourceNode.children.set(toKey, targetNode);
35
- }
36
- /** @public */
37
- sort() {
38
- this.#visitedNodes = new Set();
39
- this.#sortedKeysStack = [];
40
- const output = new Map();
41
- for (const [key] of this.#nodes) {
42
- this.exploreNode(key, []);
43
- }
44
- for (let i = this.#sortedKeysStack.length - 1; i >= 0; i--) {
45
- const node = this.#nodes.get(this.#sortedKeysStack[i]);
46
- output.set(this.#sortedKeysStack[i], node);
47
- }
48
- return output;
49
- }
50
- exploreNode(nodeKey, explorePath) {
51
- const newExplorePath = [...explorePath, nodeKey];
52
- // we should check circular dependencies starting from node 2
53
- if (explorePath.length) {
54
- if (explorePath.includes(nodeKey)) {
55
- throw Error(`Package ${nodeKey} forms circular dependency: ${newExplorePath
56
- .slice(newExplorePath.indexOf(nodeKey))
57
- .join(' -> ')}`);
58
- }
59
- }
60
- const node = this.#nodes.get(nodeKey);
61
- if (this.#visitedNodes.has(node))
62
- return;
63
- // mark node as visited so that it and its children
64
- // won't be explored next time
65
- this.#visitedNodes.add(node);
66
- for (const [childNodeKey] of node.children) {
67
- this.exploreNode(childNodeKey, newExplorePath);
68
- }
69
- this.#sortedKeysStack.push(nodeKey);
70
- }
71
- addInternalNode(key, node) {
72
- assert_1.default.strictEqual(this.#nodes.has(key), false, `Node ${key} already exists`);
73
- this.#nodes.set(key, {
74
- children: new Map(),
75
- node,
76
- });
77
- return this;
78
- }
79
- addMultipleInternalNodes(nodes) {
80
- const nodesFlat = [...nodes];
81
- for (let i = nodes.size - 1; i >= 0; i--) {
82
- const [key, node] = nodesFlat[i];
83
- this.addInternalNode(key, node);
84
- }
85
- }
86
- }
87
- exports.TopologicalSort = TopologicalSort;
@@ -1,47 +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.findParentPath = findParentPath;
7
- const node_fs_1 = __importDefault(require("node:fs"));
8
- const node_path_1 = __importDefault(require("node:path"));
9
- const debug = process.env.DEBUG === '1';
10
- // eslint-disable-next-line no-console
11
- const log = (message) => debug && console.log(`isMonorepo: ${message}`);
12
- function findPackageJson(directory) {
13
- try {
14
- const packageJsonPath = node_path_1.default.join(directory, 'package.json');
15
- const content = node_fs_1.default.readFileSync(packageJsonPath, 'utf8');
16
- return JSON.parse(content);
17
- }
18
- catch {
19
- return null;
20
- }
21
- }
22
- /**
23
- * Finds the path of the parent @graphcommerce package if it exists Returns null if no parent
24
- * package is found
25
- */
26
- function findParentPath(directory) {
27
- let currentDir = directory;
28
- log(`Starting directory: ${currentDir}`);
29
- // Start from the parent directory
30
- currentDir = node_path_1.default.dirname(currentDir);
31
- log(`Looking for parent packages starting from: ${currentDir}`);
32
- // Keep going up until we find a root package or hit the filesystem root
33
- while (currentDir !== node_path_1.default.parse(currentDir).root) {
34
- const packageJson = findPackageJson(currentDir);
35
- if (packageJson) {
36
- log(`Found package.json in: ${currentDir}`);
37
- log(`Package name: ${packageJson.name}`);
38
- if (packageJson.name.startsWith('@graphcommerce/')) {
39
- log(`Found parent @graphcommerce package at: ${currentDir}`);
40
- return currentDir;
41
- }
42
- }
43
- currentDir = node_path_1.default.dirname(currentDir);
44
- }
45
- log('No parent @graphcommerce package found');
46
- return null;
47
- }
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.packageRoots = void 0;
4
- const packageRoots = (packagePaths) => {
5
- const pathMap = {};
6
- // Iterate over each path in the array
7
- packagePaths.forEach((singlePath) => {
8
- const parts = singlePath.split('/');
9
- // Iterate through each part of the path
10
- for (let i = 1; i < parts.length; i++) {
11
- const subPath = parts.slice(0, i + 1).join('/');
12
- // Increment the count of this subPath
13
- if (pathMap[subPath]) {
14
- pathMap[subPath].count += 1;
15
- }
16
- else {
17
- pathMap[subPath] = { path: subPath, count: 1 };
18
- }
19
- }
20
- });
21
- // Filter the paths that appear more than once
22
- const roots = [];
23
- Object.values(pathMap).forEach(({ path, count }) => {
24
- if (count > 1) {
25
- roots.push(path);
26
- }
27
- });
28
- // Filter out the sub-paths which are part of another longer sub-path
29
- return roots.filter((root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1);
30
- };
31
- exports.packageRoots = packageRoots;
@@ -1,78 +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.sortDependencies = sortDependencies;
7
- exports.resolveDependenciesSync = resolveDependenciesSync;
8
- const node_fs_1 = __importDefault(require("node:fs"));
9
- const node_path_1 = __importDefault(require("node:path"));
10
- const PackagesSort_1 = require("./PackagesSort");
11
- const sig_1 = require("./sig");
12
- const resolveCache = new Map();
13
- function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, additionalDependencies = []) {
14
- const isRoot = dependencyPath === root;
15
- const fileName = require.resolve(node_path_1.default.join(dependencyPath, 'package.json'));
16
- const packageJsonFile = node_fs_1.default.readFileSync(fileName, 'utf-8').toString();
17
- const packageJson = JSON.parse(packageJsonFile);
18
- const e = [atob('QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=')].filter((n) => !globalThis.gcl ? true : !globalThis.gcl.includes(n));
19
- if (!packageJson.name)
20
- throw Error(`Package ${packageJsonFile} does not have a name field`);
21
- // Previously processed
22
- if (dependencyStructure[packageJson.name])
23
- return dependencyStructure;
24
- // To have additional namespaces be considered as a graphcommerce package, set PRIVATE_PACKAGE_NAMESPACES
25
- const namespaces = process.env.PRIVATE_PACKAGE_NAMESPACES?.split(',') ?? ['graphcommerce'];
26
- if (!isRoot && !namespaces.some((namespace) => packageJson.name?.includes(namespace)))
27
- return dependencyStructure;
28
- const dependencies = [
29
- ...new Set([
30
- ...Object.keys(packageJson.dependencies ?? []),
31
- ...Object.keys(packageJson.devDependencies ?? []),
32
- ...additionalDependencies,
33
- ...Object.keys(packageJson.peerDependencies ?? {}),
34
- ].filter((name) => name.includes('graphcommerce')
35
- ? !(e.length >= 0 && e.some((v) => name.startsWith(v)))
36
- : false)),
37
- ];
38
- const name = isRoot ? '.' : packageJson.name;
39
- dependencyStructure[name] = {
40
- dirName: node_path_1.default.dirname(node_path_1.default.relative(process.cwd(), fileName)),
41
- dependencies,
42
- };
43
- dependencies.forEach((dep) => {
44
- resolveRecursivePackageJson(dep, dependencyStructure, root);
45
- });
46
- return dependencyStructure;
47
- }
48
- /**
49
- * We're sorting all dependencies topologically
50
- *
51
- * This can detect dependency cycles and throw an error
52
- */
53
- function sortDependencies(dependencyStructure) {
54
- const packages = Object.entries(dependencyStructure);
55
- const sorter = new PackagesSort_1.PackagesSort(new Map(packages.map(([key, value]) => [key, value.dirName])));
56
- packages.forEach(([key, { dependencies }]) => dependencies.forEach((dependency) => sorter.addEdge(key, dependency)));
57
- const sortedKeys = [...sorter.sort().keys()];
58
- return new Map(sortedKeys.map((key) => [key, dependencyStructure[key].dirName]));
59
- }
60
- /**
61
- * This will return a list of all dependencies that have `graphcommerce` in the name, matching:
62
- *
63
- * - `@graphcommerce/package-name`
64
- * - `@mycompany/graphcommerce-my-feature`
65
- *
66
- * It will traverse children until it finds a package that doesn't contain graphcommerce in the name
67
- * and stop there, not checking children.
68
- */
69
- function resolveDependenciesSync(root = process.cwd()) {
70
- const cached = resolveCache.get(root);
71
- if (cached)
72
- return cached;
73
- (0, sig_1.sig)();
74
- const dependencyStructure = resolveRecursivePackageJson(root, {}, root, process.env.PRIVATE_ADDITIONAL_DEPENDENCIES?.split(',') ?? []);
75
- const sorted = sortDependencies(dependencyStructure);
76
- resolveCache.set(root, sorted);
77
- return sorted;
78
- }
@@ -1,70 +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.resolveDependency = void 0;
7
- const node_fs_1 = __importDefault(require("node:fs"));
8
- const resolveDependenciesSync_1 = require("./resolveDependenciesSync");
9
- const resolveDependency = (cwd = process.cwd()) => {
10
- const dependencies = (0, resolveDependenciesSync_1.resolveDependenciesSync)(cwd);
11
- function resolve(dependency, options = {}) {
12
- const { includeSources = false } = options;
13
- let dependencyPaths = {
14
- root: '.',
15
- source: '',
16
- sourcePath: '',
17
- sourcePathRelative: '',
18
- dependency,
19
- fromRoot: dependency,
20
- fromModule: dependency,
21
- denormalized: dependency,
22
- };
23
- dependencies.forEach((root, depCandidate) => {
24
- if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) {
25
- const relative = dependency.replace(depCandidate, '');
26
- const rootCandidate = dependency.replace(depCandidate, root);
27
- let source = '';
28
- let sourcePath = '';
29
- const fromRoot = [
30
- `${rootCandidate}`,
31
- `${rootCandidate}/index`,
32
- `${rootCandidate}/src/index`,
33
- ].find((location) => ['ts', 'tsx'].find((extension) => {
34
- const candidatePath = `${location}.${extension}`;
35
- const exists = node_fs_1.default.existsSync(candidatePath);
36
- if (includeSources && exists) {
37
- source = node_fs_1.default.readFileSync(candidatePath, 'utf-8');
38
- sourcePath = candidatePath;
39
- }
40
- return exists;
41
- }));
42
- if (!fromRoot) {
43
- return;
44
- }
45
- const denormalized = fromRoot.replace(root, depCandidate);
46
- let fromModule = !relative
47
- ? '.'
48
- : `./${relative.split('/')[relative.split('/').length - 1]}`;
49
- const sourcePathRelative = !sourcePath
50
- ? '.'
51
- : `./${sourcePath.split('/')[sourcePath.split('/').length - 1]}`;
52
- if (dependency.startsWith('./'))
53
- fromModule = `.${relative}`;
54
- dependencyPaths = {
55
- root,
56
- dependency,
57
- denormalized,
58
- fromRoot,
59
- fromModule,
60
- source,
61
- sourcePath,
62
- sourcePathRelative,
63
- };
64
- }
65
- });
66
- return dependencyPaths;
67
- }
68
- return resolve;
69
- };
70
- exports.resolveDependency = resolveDependency;
package/dist/utils/sig.js DELETED
@@ -1,34 +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.g = g;
7
- exports.sig = sig;
8
- // import necessary modules
9
- const crypto_1 = __importDefault(require("crypto"));
10
- // Function to generate a license key based on input data
11
- function g(data) {
12
- const iv = crypto_1.default.randomBytes(16); // Initialization vector
13
- const cipher = crypto_1.default.createCipheriv('aes-256-cbc', 'BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN', iv);
14
- let encrypted = cipher.update(JSON.stringify(data), 'utf-8', 'hex');
15
- encrypted += cipher.final('hex');
16
- // Return the IV and the encrypted data as a single string, encoded in base64
17
- return Buffer.from(`${iv.toString('hex')}:${encrypted}`).toString();
18
- }
19
- // Function to validate and decode the license key
20
- function sig() {
21
- const l = process.env[atob('R0NfTElDRU5TRQ==')];
22
- if (!l)
23
- return;
24
- if (!globalThis.gcl)
25
- try {
26
- const decipher = crypto_1.default.createDecipheriv('aes-256-cbc', 'BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN', Buffer.from(l.split(':')[0], 'hex'));
27
- let decrypted = decipher.update(l.split(':')[1], 'hex', 'utf-8');
28
- decrypted += decipher.final('utf-8');
29
- globalThis.gcl = JSON.parse(decrypted); // Parse and return the decoded data
30
- }
31
- catch (error) {
32
- // Silent
33
- }
34
- }
@@ -1,162 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.withGraphCommerce = withGraphCommerce;
4
- // import CircularDependencyPlugin from 'circular-dependency-plugin'
5
- const plugin_1 = require("inspectpack/plugin");
6
- const webpack_1 = require("webpack");
7
- const loadConfig_1 = require("./config/loadConfig");
8
- const configToImportMeta_1 = require("./config/utils/configToImportMeta");
9
- const InterceptorPlugin_1 = require("./interceptors/InterceptorPlugin");
10
- const resolveDependenciesSync_1 = require("./utils/resolveDependenciesSync");
11
- let graphcommerceConfig;
12
- function domains(config) {
13
- return Object.values(config.storefront.reduce((acc, loc) => {
14
- if (!loc.domain)
15
- return acc;
16
- acc[loc.domain] = {
17
- defaultLocale: loc.locale,
18
- locales: [...(acc[loc.domain]?.locales ?? []), loc.locale],
19
- domain: loc.domain,
20
- http: process.env.NODE_ENV === 'development' || undefined,
21
- };
22
- return acc;
23
- }, {}));
24
- }
25
- /**
26
- * GraphCommerce configuration: .
27
- *
28
- * ```ts
29
- * const { withGraphCommerce } = require('@graphcommerce/next-config')
30
- *
31
- * module.exports = withGraphCommerce(nextConfig)
32
- * ```
33
- */
34
- function withGraphCommerce(nextConfig, cwd = process.cwd()) {
35
- graphcommerceConfig ??= (0, loadConfig_1.loadConfig)(cwd);
36
- const importMetaPaths = (0, configToImportMeta_1.configToImportMeta)(graphcommerceConfig);
37
- const { storefront } = graphcommerceConfig;
38
- const transpilePackages = [
39
- ...[...(0, resolveDependenciesSync_1.resolveDependenciesSync)().keys()].slice(1),
40
- ...(nextConfig.transpilePackages ?? []),
41
- ];
42
- return {
43
- ...nextConfig,
44
- bundlePagesRouterDependencies: true,
45
- experimental: {
46
- ...nextConfig.experimental,
47
- scrollRestoration: true,
48
- swcPlugins: [...(nextConfig.experimental?.swcPlugins ?? []), ['@lingui/swc-plugin', {}]],
49
- },
50
- i18n: {
51
- ...nextConfig.i18n,
52
- defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale,
53
- locales: storefront.map((locale) => locale.locale),
54
- domains: [...domains(graphcommerceConfig), ...(nextConfig.i18n?.domains ?? [])],
55
- },
56
- images: {
57
- ...nextConfig.images,
58
- remotePatterns: [
59
- { hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname },
60
- { hostname: '**.graphassets.com' },
61
- { hostname: '*.graphcommerce.org' },
62
- ...(nextConfig.images?.remotePatterns ?? []),
63
- ],
64
- },
65
- redirects: async () => {
66
- const redirects = (await nextConfig.redirects?.()) ?? [];
67
- const destination = `${graphcommerceConfig.productRoute ?? '/p/'}:url*`;
68
- redirects.push(...[
69
- { source: '/product/bundle/:url*', destination, permanent: true },
70
- { source: '/product/configurable/:url*', destination, permanent: true },
71
- { source: '/product/downloadable/:url*', destination, permanent: true },
72
- { source: '/product/grouped/:url*', destination, permanent: true },
73
- { source: '/product/virtual/:url*', destination, permanent: true },
74
- { source: '/customer/account', destination: '/account', permanent: true },
75
- ]);
76
- if (destination !== '/product/:url*')
77
- redirects.push({ source: '/product/:url*', destination, permanent: true });
78
- return redirects;
79
- },
80
- rewrites: async () => {
81
- let rewrites = (await nextConfig.rewrites?.()) ?? [];
82
- if (Array.isArray(rewrites)) {
83
- rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] };
84
- }
85
- if (graphcommerceConfig.productRoute && graphcommerceConfig.productRoute !== '/p/') {
86
- rewrites.beforeFiles.push({
87
- source: `${graphcommerceConfig.productRoute ?? '/p/'}:path*`,
88
- destination: '/p/:path*',
89
- });
90
- }
91
- return rewrites;
92
- },
93
- transpilePackages,
94
- webpack: (config, options) => {
95
- if (!config.module)
96
- config.module = { rules: [] };
97
- config.module = {
98
- ...config.module,
99
- rules: [
100
- ...(config.module.rules ?? []),
101
- // Allow importing yml/yaml files for graphql-mesh
102
- { test: /\.ya?ml$/, use: 'js-yaml-loader' },
103
- // @lingui .po file support
104
- { test: /\.po/, use: '@lingui/loader' },
105
- ],
106
- exprContextCritical: false,
107
- };
108
- if (!config.plugins)
109
- config.plugins = [];
110
- // Make import.meta.graphCommerce available for usage.
111
- config.plugins.push(new webpack_1.DefinePlugin(importMetaPaths));
112
- // To properly properly treeshake @apollo/client we need to define the __DEV__ property
113
- config.plugins.push(new webpack_1.DefinePlugin({ 'globalThis.__DEV__': options.dev }));
114
- if (!options.isServer) {
115
- // if (graphcommerceConfig.debug?.webpackCircularDependencyPlugin) {
116
- // config.plugins.push(
117
- // new CircularDependencyPlugin({
118
- // exclude: /readable-stream|duplexer2|node_modules\/next/,
119
- // }),
120
- // )
121
- // }
122
- if (graphcommerceConfig.debug?.webpackDuplicatesPlugin) {
123
- config.plugins.push(new plugin_1.DuplicatesPlugin({
124
- ignoredPackages: [
125
- // very small
126
- 'react-is',
127
- // build issue
128
- 'tslib',
129
- // server
130
- 'isarray',
131
- 'readable-stream',
132
- ],
133
- }));
134
- }
135
- }
136
- config.snapshot = {
137
- ...(config.snapshot ?? {}),
138
- managedPaths: [
139
- new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join('|')})`),
140
- ],
141
- };
142
- config.watchOptions = {
143
- ...(config.watchOptions ?? {}),
144
- ignored: new RegExp(`^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join('|')})))(/((?:[^/]*(?:/|$))*)(?:$|/))?`),
145
- };
146
- if (!config.resolve)
147
- config.resolve = {};
148
- if (!options.isServer && !options.dev) {
149
- config.resolve.alias = {
150
- ...config.resolve.alias,
151
- '@mui/base': '@mui/base/modern',
152
- '@mui/lab': '@mui/lab/modern',
153
- '@mui/material': '@mui/material/modern',
154
- '@mui/styled-engine': '@mui/styled-engine/modern',
155
- '@mui/system': '@mui/system/modern',
156
- };
157
- }
158
- config.plugins.push(new InterceptorPlugin_1.InterceptorPlugin(graphcommerceConfig, !options.isServer));
159
- return typeof nextConfig.webpack === 'function' ? nextConfig.webpack(config, options) : config;
160
- },
161
- };
162
- }