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

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 (35) hide show
  1. package/CHANGELOG.md +80 -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 +804 -2436
  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 +9 -2
  25. package/src/interceptors/updatePackageExports.ts +147 -0
  26. package/src/interceptors/writeInterceptors.ts +90 -35
  27. package/src/types.ts +26 -0
  28. package/src/utils/index.ts +7 -0
  29. package/src/utils/resolveDependenciesSync.ts +5 -7
  30. package/src/withGraphCommerce.ts +30 -49
  31. package/tsconfig.json +3 -1
  32. package/__tests__/config/utils/configToImportMeta.ts +0 -121
  33. package/src/interceptors/InterceptorPlugin.ts +0 -141
  34. package/src/interceptors/commands/codegenInterceptors.ts +0 -27
  35. /package/src/utils/{isMonorepo.ts → findParentPath.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,56 +1,138 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
1
+ import dotenv from 'dotenv';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'path';
4
+ import { glob, sync } from 'glob';
5
+ import { findParentPath } from './utils/findParentPath.js';
6
+ import { spawn } from 'child_process';
7
+ import { l as loadConfig, t as toEnvStr } from './loadConfig-nJiCKeL1.js';
8
+ export { r as replaceConfigInString } from './loadConfig-nJiCKeL1.js';
9
+ import { parseFileSync, parseSync as parseSync$1, transformFileSync } from '@swc/core';
10
+ import fs$1 from 'node:fs';
11
+ import path$1 from 'node:path';
3
12
  import assert from 'assert';
4
13
  import crypto from 'crypto';
5
- import { GraphCommerceConfigSchema } from './generated/config.js';
6
- export { GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
7
- import webpack from 'webpack';
8
- import { cosmiconfigSync } from 'cosmiconfig';
9
- import chalk from 'chalk';
10
14
  import lodash from 'lodash';
11
- import { z, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodObject, ZodArray, ZodNumber, ZodString, ZodEnum, ZodBoolean } from 'zod';
12
- import path$1 from 'path';
13
- import { parseFileSync, parseSync as parseSync$1, printSync as printSync$1, transformFileSync } from '@swc/core';
14
- import { sync } from 'glob';
15
- import fs$1 from 'node:fs/promises';
15
+ import { z } from 'zod';
16
16
  import prettierConf from '@graphcommerce/prettier-config-pwa';
17
17
  import prettier from 'prettier';
18
- import { writeFileSync, readFileSync } from 'fs';
19
- import { generate } from '@graphql-codegen/cli';
20
- import dotenv from 'dotenv';
21
18
  import fs$2 from 'fs/promises';
22
19
  import fg from 'fast-glob';
20
+ import { writeFileSync, readFileSync, existsSync, rmSync, mkdirSync } from 'fs';
21
+ import { generate } from '@graphql-codegen/cli';
22
+ import { GraphCommerceConfigSchema } from './generated/config.js';
23
+ export { GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
24
+ import 'cosmiconfig';
25
+ import '@apollo/client/utilities/index.js';
26
+ import 'chalk';
23
27
 
24
- const debug$1 = process.env.DEBUG === "1";
25
- const log = (message) => debug$1 && console.log(`isMonorepo: ${message}`);
26
- function findPackageJson$1(directory) {
28
+ async function fsExists(file) {
27
29
  try {
28
- const packageJsonPath = path.join(directory, "package.json");
29
- const content = fs.readFileSync(packageJsonPath, "utf8");
30
- return JSON.parse(content);
30
+ await fs.access(file, fs.constants.F_OK);
31
+ return true;
31
32
  } catch {
32
- return null;
33
+ return false;
34
+ }
35
+ }
36
+ async function fsRealpath(file) {
37
+ return await fsExists(file) ? fs.realpath(file) : file;
38
+ }
39
+ async function restoreOriginalFile(fileWithOriginalInTheName) {
40
+ const restoredPath = fileWithOriginalInTheName.replace(/\.original\.(tsx?)$/, ".$1");
41
+ if (await fsExists(fileWithOriginalInTheName)) {
42
+ if (await fsExists(restoredPath)) {
43
+ await fs.unlink(restoredPath);
44
+ }
45
+ await fs.rename(fileWithOriginalInTheName, restoredPath);
46
+ return true;
33
47
  }
48
+ return false;
34
49
  }
35
- function findParentPath(directory) {
36
- let currentDir = directory;
37
- log(`Starting directory: ${currentDir}`);
38
- currentDir = path.dirname(currentDir);
39
- log(`Looking for parent packages starting from: ${currentDir}`);
40
- while (currentDir !== path.parse(currentDir).root) {
41
- const packageJson = findPackageJson$1(currentDir);
42
- if (packageJson) {
43
- log(`Found package.json in: ${currentDir}`);
44
- log(`Package name: ${packageJson.name}`);
45
- if (packageJson.name.startsWith("@graphcommerce/")) {
46
- log(`Found parent @graphcommerce package at: ${currentDir}`);
47
- return currentDir;
50
+ async function findDotOriginalFiles(cwd) {
51
+ let parentPath = findParentPath(process.cwd());
52
+ while (parentPath) {
53
+ const p = findParentPath(parentPath);
54
+ if (p) parentPath = p;
55
+ else break;
56
+ }
57
+ return Promise.all(
58
+ (await glob([`${parentPath}/**/*.original.tsx`, `${parentPath}/**/*.original.ts`], { cwd })).map((file) => fs.realpath(file))
59
+ );
60
+ }
61
+ async function writeInterceptors(interceptors, cwd = process.cwd()) {
62
+ const processedFiles = [];
63
+ const existingDotOriginalFiles = findDotOriginalFiles(cwd);
64
+ const written = Object.entries(interceptors).map(async ([, plugin]) => {
65
+ const extension = plugin.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
66
+ const targetFileName = `${plugin.fromRoot}${extension}`;
67
+ const fileNameDotOriginal = `${plugin.fromRoot}.original${extension}`;
68
+ const targetFilePath = await fsRealpath(path.resolve(cwd, targetFileName));
69
+ const dotOriginalPath = await fsRealpath(path.resolve(cwd, fileNameDotOriginal));
70
+ processedFiles.push(dotOriginalPath);
71
+ const targetSource = await fsExists(targetFilePath) ? await fs.readFile(targetFilePath, "utf8") : null;
72
+ const dotOriginalSource = await fsExists(dotOriginalPath) ? await fs.readFile(dotOriginalPath, "utf8") : null;
73
+ const isPreviouslyApplied = dotOriginalSource !== null && targetSource?.includes("/* hash:");
74
+ let status = "";
75
+ if (isPreviouslyApplied) {
76
+ if (targetSource === plugin.template) {
77
+ status = "\u2705 Unchanged interceptor";
78
+ } else {
79
+ status = "\u{1F504} Updating interceptor";
80
+ await fs.writeFile(targetFilePath, plugin.template);
48
81
  }
82
+ } else {
83
+ status = "\u{1F195} Creating interceptor";
84
+ await fs.rename(targetFilePath, dotOriginalPath);
85
+ await fs.writeFile(targetFilePath, plugin.template);
86
+ }
87
+ console.log(`${status} ${plugin.dependency}`);
88
+ Object.entries(plugin.targetExports).forEach(([target, plugins]) => {
89
+ plugins.forEach((plugin2) => {
90
+ console.log(` \u{1F50C} ${target} <- ${plugin2.sourceModule}`);
91
+ });
92
+ });
93
+ });
94
+ await Promise.all(written);
95
+ const toRestore = (await existingDotOriginalFiles).filter(
96
+ (file) => !processedFiles.includes(file)
97
+ );
98
+ await Promise.all(
99
+ toRestore.map((file) => {
100
+ console.log(`\u21A9 Removing old interceptor ${file}`);
101
+ return restoreOriginalFile(file);
102
+ })
103
+ );
104
+ }
105
+
106
+ dotenv.config({ quiet: true });
107
+ async function cleanupInterceptors(cwd = process.cwd()) {
108
+ console.info("\u{1F9F9} Starting interceptor cleanup...");
109
+ let restoredCount = 0;
110
+ let removedCount = 0;
111
+ const originalFiles = await findDotOriginalFiles(cwd);
112
+ console.info(`\u{1F4C2} Found ${originalFiles.length} .original files to restore`);
113
+ for (const originalFile of originalFiles) {
114
+ try {
115
+ await restoreOriginalFile(originalFile);
116
+ removedCount++;
117
+ } catch (error) {
118
+ console.error(`\u274C Failed to restore ${originalFile}:`, error);
49
119
  }
50
- currentDir = path.dirname(currentDir);
51
120
  }
52
- log("No parent @graphcommerce package found");
53
- return null;
121
+ console.info("\u2705 Interceptor cleanup completed!");
122
+ console.info(`\u{1F4CA} ${restoredCount} files restored from .original`);
123
+ }
124
+
125
+ function run(cmd) {
126
+ return new Promise((resolve, reject) => {
127
+ const child = spawn(cmd, { stdio: "inherit", cwd: process.cwd(), shell: true });
128
+ child.on("close", (code) => code === 0 ? resolve() : reject(new Error(`${cmd} failed`)));
129
+ });
130
+ }
131
+ async function codegen() {
132
+ await run("graphcommerce copy-files");
133
+ await run("graphcommerce codegen-config");
134
+ await run("graphcommerce codegen-config-values");
135
+ await run("graphcommerce codegen-interceptors");
54
136
  }
55
137
 
56
138
  class TopologicalSort {
@@ -169,25 +251,21 @@ function sig() {
169
251
 
170
252
  const resolveCache = /* @__PURE__ */ new Map();
171
253
  function findPackageJson(id, root) {
172
- let dir = id.startsWith("/") ? id : require.resolve(id);
173
- let packageJsonLocation = path.join(dir, "package.json");
174
- while (!fs.existsSync(packageJsonLocation)) {
175
- dir = path.dirname(dir);
254
+ let dir = id.startsWith("/") ? id : import.meta.resolve(id);
255
+ if (dir.startsWith("file://")) dir = new URL(dir).pathname;
256
+ let packageJsonLocation = path$1.join(dir, "package.json");
257
+ while (!fs$1.existsSync(packageJsonLocation)) {
258
+ dir = path$1.dirname(dir);
176
259
  if (dir === root) throw Error(`Can't find package.json for ${id}`);
177
- packageJsonLocation = path.join(dir, "package.json");
260
+ packageJsonLocation = path$1.join(dir, "package.json");
178
261
  }
179
262
  return packageJsonLocation;
180
263
  }
181
264
  function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, additionalDependencies = []) {
182
265
  const isRoot = dependencyPath === root;
183
- let fileName;
184
- try {
185
- fileName = require.resolve(path.join(dependencyPath, "package.json"));
186
- } catch (e2) {
187
- fileName = findPackageJson(dependencyPath, root);
188
- }
266
+ const fileName = findPackageJson(dependencyPath, root);
189
267
  if (!fileName) throw Error(`Can't find package.json for ${dependencyPath}`);
190
- const packageJsonFile = fs.readFileSync(fileName, "utf-8").toString();
268
+ const packageJsonFile = fs$1.readFileSync(fileName, "utf-8").toString();
191
269
  const packageJson = JSON.parse(packageJsonFile);
192
270
  const e = [atob("QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=")].filter(
193
271
  (n) => !globalThis.gcl ? true : !globalThis.gcl.includes(n)
@@ -227,7 +305,7 @@ function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root,
227
305
  });
228
306
  const name = isRoot ? "." : packageJson.name;
229
307
  dependencyStructure[name] = {
230
- dirName: path.dirname(path.relative(process.cwd(), fileName)),
308
+ dirName: path$1.dirname(path$1.relative(process.cwd(), fileName)),
231
309
  dependencies: availableDependencies
232
310
  };
233
311
  return dependencyStructure;
@@ -256,514 +334,6 @@ function resolveDependenciesSync(root = process.cwd()) {
256
334
  return sorted;
257
335
  }
258
336
 
259
- const packageRoots = (packagePaths) => {
260
- const pathMap = {};
261
- packagePaths.forEach((singlePath) => {
262
- const parts = singlePath.split("/");
263
- for (let i = 1; i < parts.length; i++) {
264
- const subPath = parts.slice(0, i + 1).join("/");
265
- if (pathMap[subPath]) {
266
- pathMap[subPath].count += 1;
267
- } else {
268
- pathMap[subPath] = { path: subPath, count: 1 };
269
- }
270
- }
271
- });
272
- const roots = [];
273
- Object.values(pathMap).forEach(({ path, count }) => {
274
- if (count > 1) {
275
- roots.push(path);
276
- }
277
- });
278
- return roots.filter(
279
- (root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1
280
- );
281
- };
282
-
283
- const demoConfig = {
284
- canonicalBaseUrl: "https://graphcommerce.vercel.app",
285
- hygraphEndpoint: "https://eu-central-1.cdn.hygraph.com/content/ckhx7xadya6xs01yxdujt8i80/master",
286
- magentoEndpoint: "https://configurator.reachdigital.dev/graphql",
287
- magentoVersion: 247,
288
- storefront: [
289
- { locale: "en", magentoStoreCode: "en_US", defaultLocale: true },
290
- {
291
- locale: "nl",
292
- magentoStoreCode: "nl_NL",
293
- hygraphLocales: ["nl", "en_us"],
294
- cartDisplayPricesInclTax: true
295
- },
296
- {
297
- locale: "fr-be",
298
- magentoStoreCode: "fr_BE",
299
- cartDisplayPricesInclTax: true,
300
- linguiLocale: "fr"
301
- },
302
- {
303
- locale: "nl-be",
304
- magentoStoreCode: "nl_BE",
305
- cartDisplayPricesInclTax: true,
306
- linguiLocale: "nl"
307
- },
308
- {
309
- locale: "en-gb",
310
- magentoStoreCode: "en_GB",
311
- cartDisplayPricesInclTax: true,
312
- linguiLocale: "en"
313
- },
314
- { locale: "en-ca", magentoStoreCode: "en_CA", linguiLocale: "en" }
315
- ],
316
- productFiltersPro: true,
317
- productFiltersLayout: "DEFAULT",
318
- productListPaginationVariant: "COMPACT",
319
- compareVariant: "ICON",
320
- robotsAllow: false,
321
- demoMode: true,
322
- limitSsg: true,
323
- compare: true,
324
- sidebarGallery: { paginationVariant: "DOTS" },
325
- configurableVariantForSimple: true,
326
- configurableVariantValues: { url: true, content: true, gallery: true },
327
- recentlyViewedProducts: { enabled: true, maxCount: 20 },
328
- breadcrumbs: false,
329
- customerDeleteEnabled: true,
330
- previewSecret: "SECRET"
331
- };
332
-
333
- var __assign = function() {
334
- __assign = Object.assign || function __assign2(t) {
335
- for (var s, i = 1, n = arguments.length; i < n; i++) {
336
- s = arguments[i];
337
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
338
- }
339
- return t;
340
- };
341
- return __assign.apply(this, arguments);
342
- };
343
- function __spreadArray(to, from, pack) {
344
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
345
- if (ar || !(i in from)) {
346
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
347
- ar[i] = from[i];
348
- }
349
- }
350
- return to.concat(ar || Array.prototype.slice.call(from));
351
- }
352
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
353
- var e = new Error(message);
354
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
355
- };
356
-
357
- function isNonNullObject(obj) {
358
- return obj !== null && typeof obj === "object";
359
- }
360
-
361
- var hasOwnProperty = Object.prototype.hasOwnProperty;
362
- function mergeDeep() {
363
- var sources = [];
364
- for (var _i = 0; _i < arguments.length; _i++) {
365
- sources[_i] = arguments[_i];
366
- }
367
- return mergeDeepArray(sources);
368
- }
369
- function mergeDeepArray(sources) {
370
- var target = sources[0] || {};
371
- var count = sources.length;
372
- if (count > 1) {
373
- var merger = new DeepMerger();
374
- for (var i = 1; i < count; ++i) {
375
- target = merger.merge(target, sources[i]);
376
- }
377
- }
378
- return target;
379
- }
380
- var defaultReconciler = function(target, source, property) {
381
- return this.merge(target[property], source[property]);
382
- };
383
- var DeepMerger = (
384
- /** @class */
385
- (function() {
386
- function DeepMerger2(reconciler) {
387
- if (reconciler === void 0) {
388
- reconciler = defaultReconciler;
389
- }
390
- this.reconciler = reconciler;
391
- this.isObject = isNonNullObject;
392
- this.pastCopies = /* @__PURE__ */ new Set();
393
- }
394
- DeepMerger2.prototype.merge = function(target, source) {
395
- var _this = this;
396
- var context = [];
397
- for (var _i = 2; _i < arguments.length; _i++) {
398
- context[_i - 2] = arguments[_i];
399
- }
400
- if (isNonNullObject(source) && isNonNullObject(target)) {
401
- Object.keys(source).forEach(function(sourceKey) {
402
- if (hasOwnProperty.call(target, sourceKey)) {
403
- var targetValue = target[sourceKey];
404
- if (source[sourceKey] !== targetValue) {
405
- var result = _this.reconciler.apply(_this, __spreadArray([
406
- target,
407
- source,
408
- sourceKey
409
- ], context, false));
410
- if (result !== targetValue) {
411
- target = _this.shallowCopyForMerge(target);
412
- target[sourceKey] = result;
413
- }
414
- }
415
- } else {
416
- target = _this.shallowCopyForMerge(target);
417
- target[sourceKey] = source[sourceKey];
418
- }
419
- });
420
- return target;
421
- }
422
- return source;
423
- };
424
- DeepMerger2.prototype.shallowCopyForMerge = function(value) {
425
- if (isNonNullObject(value)) {
426
- if (!this.pastCopies.has(value)) {
427
- if (Array.isArray(value)) {
428
- value = value.slice(0);
429
- } else {
430
- value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);
431
- }
432
- this.pastCopies.add(value);
433
- }
434
- }
435
- return value;
436
- };
437
- return DeepMerger2;
438
- })()
439
- );
440
-
441
- var toString = Object.prototype.toString;
442
- function cloneDeep(value) {
443
- return cloneDeepHelper(value);
444
- }
445
- function cloneDeepHelper(val, seen) {
446
- switch (toString.call(val)) {
447
- case "[object Array]": {
448
- seen = seen || /* @__PURE__ */ new Map();
449
- if (seen.has(val))
450
- return seen.get(val);
451
- var copy_1 = val.slice(0);
452
- seen.set(val, copy_1);
453
- copy_1.forEach(function(child, i) {
454
- copy_1[i] = cloneDeepHelper(child, seen);
455
- });
456
- return copy_1;
457
- }
458
- case "[object Object]": {
459
- seen = seen || /* @__PURE__ */ new Map();
460
- if (seen.has(val))
461
- return seen.get(val);
462
- var copy_2 = Object.create(Object.getPrototypeOf(val));
463
- seen.set(val, copy_2);
464
- Object.keys(val).forEach(function(key) {
465
- copy_2[key] = cloneDeepHelper(val[key], seen);
466
- });
467
- return copy_2;
468
- }
469
- default:
470
- return val;
471
- }
472
- }
473
-
474
- function isObject$1(val) {
475
- return typeof val === "object" && val !== null;
476
- }
477
- function isArray(val) {
478
- return Array.isArray(val);
479
- }
480
- function diff(item1, item2) {
481
- const item1Type = typeof item2;
482
- const item2Type = typeof item2;
483
- const isSame = item1Type === item2Type;
484
- if (!isSame) return item2;
485
- if (isArray(item1) && isArray(item2)) {
486
- const res = item1.map((val, idx) => diff(val, item2[idx])).filter((val) => !!val);
487
- return res.length ? res : void 0;
488
- }
489
- if (isObject$1(item1) && isObject$1(item2)) {
490
- const entriesRight = Object.fromEntries(
491
- Object.entries(item1).map(([key, val]) => [key, diff(val, item2[key])]).filter((entry) => !!entry[1])
492
- );
493
- const entriesLeft = Object.fromEntries(
494
- Object.entries(item2).map(([key, val]) => [key, diff(item1[key], val)]).filter((entry) => !!entry[1])
495
- );
496
- const entries = { ...entriesRight, ...entriesLeft };
497
- return Object.keys(entries).length ? entries : void 0;
498
- }
499
- return item2 === item1 ? void 0 : item2;
500
- }
501
-
502
- const fmt$1 = (s) => s.split(/(\d+)/).map((v) => lodash.snakeCase(v)).join("");
503
- const toEnvStr = (path) => ["GC", ...path].map(fmt$1).join("_").toUpperCase();
504
- const dotNotation = (pathParts) => pathParts.map((v) => {
505
- const idx = Number(v);
506
- return !Number.isNaN(idx) ? `[${idx}]` : v;
507
- }).join(".");
508
- function isJSON(str) {
509
- if (!str) return true;
510
- try {
511
- JSON.parse(str);
512
- } catch (e) {
513
- return false;
514
- }
515
- return true;
516
- }
517
- function configToEnvSchema(schema) {
518
- const envSchema = {};
519
- const envToDot = {};
520
- function walk(incomming, path = []) {
521
- let node = incomming;
522
- if (node instanceof ZodEffects) node = node.innerType();
523
- if (node instanceof ZodOptional) node = node.unwrap();
524
- if (node instanceof ZodNullable) node = node.unwrap();
525
- if (node instanceof ZodDefault) node = node.removeDefault();
526
- if (node instanceof ZodObject) {
527
- if (path.length > 0) {
528
- envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val);
529
- envToDot[toEnvStr(path)] = dotNotation(path);
530
- }
531
- const typeNode = node;
532
- Object.keys(typeNode.shape).forEach((key) => {
533
- walk(typeNode.shape[key], [...path, key]);
534
- });
535
- return;
536
- }
537
- if (node instanceof ZodArray) {
538
- const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
539
- if (path.length > 0) {
540
- envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val);
541
- envToDot[toEnvStr(path)] = dotNotation(path);
542
- }
543
- arr.forEach((key) => {
544
- walk(node.element, [...path, String(key)]);
545
- });
546
- return;
547
- }
548
- if (node instanceof ZodNumber) {
549
- envSchema[toEnvStr(path)] = z.coerce.number().optional();
550
- envToDot[toEnvStr(path)] = dotNotation(path);
551
- return;
552
- }
553
- if (node instanceof ZodString || node instanceof ZodEnum) {
554
- envSchema[toEnvStr(path)] = node.optional();
555
- envToDot[toEnvStr(path)] = dotNotation(path);
556
- return;
557
- }
558
- if (node instanceof ZodBoolean) {
559
- envSchema[toEnvStr(path)] = z.enum(["true", "1", "false", "0"]).optional().transform((v) => {
560
- if (v === "true" || v === "1") return true;
561
- if (v === "false" || v === "0") return false;
562
- return v;
563
- });
564
- envToDot[toEnvStr(path)] = dotNotation(path);
565
- return;
566
- }
567
- throw Error(
568
- `[@graphcommerce/next-config] Unknown type in schema ${node.constructor.name}. This is probably a bug please create an issue.`
569
- );
570
- }
571
- walk(schema);
572
- return [z.object(envSchema), envToDot];
573
- }
574
- const filterEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("GC_")));
575
- function mergeEnvIntoConfig(schema, config, env) {
576
- const filteredEnv = filterEnv(env);
577
- const newConfig = cloneDeep(config);
578
- const [envSchema, envToDot] = configToEnvSchema(schema);
579
- const result = envSchema.safeParse(filteredEnv);
580
- const applyResult = [];
581
- if (!result.success) {
582
- Object.entries(result.error.flatten().fieldErrors).forEach(([envVar, error]) => {
583
- const dotVar = envToDot[envVar];
584
- const envValue = filteredEnv[envVar];
585
- applyResult.push({ envVar, envValue, dotVar, error });
586
- });
587
- return [void 0, applyResult];
588
- }
589
- Object.entries(result.data).forEach(([envVar, value]) => {
590
- const dotVar = envToDot[envVar];
591
- const envValue = filteredEnv[envVar];
592
- if (!dotVar) {
593
- applyResult.push({ envVar, envValue });
594
- return;
595
- }
596
- const dotValue = lodash.get(newConfig, dotVar);
597
- const merged = mergeDeep(dotValue, value);
598
- const from = diff(merged, dotValue);
599
- const to = diff(dotValue, merged);
600
- applyResult.push({ envVar, envValue, dotVar, from, to });
601
- lodash.set(newConfig, dotVar, merged);
602
- });
603
- return [newConfig, applyResult];
604
- }
605
- function formatAppliedEnv(applyResult) {
606
- let hasError = false;
607
- let hasWarning = false;
608
- const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => {
609
- const envVariableFmt = `${envVar}`;
610
- const dotVariableFmt = chalk.bold.underline(`${dotVar}`);
611
- const baseLog = `${envVariableFmt} => ${dotVariableFmt}`;
612
- if (error) {
613
- hasError = true;
614
- return `${chalk.red(` \u2A09 ${envVariableFmt}`)} => ${error.join(", ")}`;
615
- }
616
- if (warning) {
617
- hasWarning = true;
618
- return `${chalk.yellowBright(` \u203C ${envVariableFmt}`)} => ${warning.join(", ")}`;
619
- }
620
- if (!dotVar) return chalk.red(`${envVariableFmt} => ignored (no matching config)`);
621
- if (from === void 0 && to === void 0) return ` = ${baseLog}`;
622
- if (from === void 0 && to !== void 0) return ` ${chalk.green("+")} ${baseLog}`;
623
- if (from !== void 0 && to === void 0) return ` ${chalk.red("-")} ${baseLog}`;
624
- return ` ${chalk.yellowBright("~")} ${baseLog}`;
625
- });
626
- let header = chalk.blueBright("info");
627
- if (hasWarning) header = chalk.yellowBright("warning");
628
- if (hasError) header = chalk.yellowBright("error");
629
- header += " - Loaded GraphCommerce env variables";
630
- return [header, ...lines].join("\n");
631
- }
632
-
633
- function flattenKeys(value, initialPathPrefix, stringify) {
634
- if (value === null || value === void 0 || typeof value === "number") {
635
- return { [initialPathPrefix]: value };
636
- }
637
- if (typeof value === "string") {
638
- return { [initialPathPrefix]: stringify ? JSON.stringify(value) : value };
639
- }
640
- if (!value || typeof value !== "object" || Array.isArray(value)) {
641
- return {
642
- [initialPathPrefix]: stringify || Array.isArray(value) ? JSON.stringify(value) : value
643
- };
644
- }
645
- if (typeof value === "object") {
646
- let outputValue = value;
647
- if (stringify)
648
- outputValue = process.env.NODE_ENV !== "production" ? `{ __debug: "'${initialPathPrefix}' can not be destructured, please access deeper properties directly" }` : "{}";
649
- return {
650
- [initialPathPrefix]: outputValue,
651
- ...Object.keys(value).map((key) => {
652
- const deep = value[key];
653
- return {
654
- ...flattenKeys(deep, `${initialPathPrefix}.${key}`, stringify),
655
- ...flattenKeys(deep, `${initialPathPrefix}?.${key}`, stringify)
656
- };
657
- }).reduce((acc, path) => ({ ...acc, ...path }), {})
658
- };
659
- }
660
- throw Error(`Unexpected value: ${value}`);
661
- }
662
- function configToImportMeta(config, path = "import.meta.graphCommerce", stringify = true) {
663
- return flattenKeys(config, path, stringify);
664
- }
665
-
666
- function replaceConfigInString(str, config) {
667
- let result = str;
668
- const replacers = configToImportMeta(config, "graphCommerce", false);
669
- Object.entries(replacers).forEach(([from, to]) => {
670
- result = result.replace(new RegExp(`{${from}}`, "g"), to);
671
- });
672
- return result;
673
- }
674
-
675
- const moduleName = "graphcommerce";
676
- const loader = cosmiconfigSync(moduleName);
677
- function loadConfig(cwd) {
678
- const isMainProcess = !process.send;
679
- try {
680
- const result = loader.search(cwd);
681
- let confFile = result?.config;
682
- if (!confFile) {
683
- if (isMainProcess)
684
- console.warn("No graphcommerce.config.js found in the project, using demo config");
685
- confFile = demoConfig;
686
- }
687
- confFile ||= {};
688
- const schema = GraphCommerceConfigSchema();
689
- const [mergedConfig, applyResult] = mergeEnvIntoConfig(schema, confFile, process.env);
690
- if (applyResult.length > 0 && isMainProcess) console.log(formatAppliedEnv(applyResult));
691
- const finalParse = schema.parse(mergedConfig);
692
- if (process.env.DEBUG && isMainProcess) {
693
- console.log("Parsed configuration");
694
- console.log(finalParse);
695
- }
696
- return finalParse;
697
- } catch (error) {
698
- if (error instanceof Error) {
699
- if (isMainProcess) {
700
- console.log("Error while parsing graphcommerce.config.js", error.message);
701
- process.exit(1);
702
- }
703
- }
704
- throw error;
705
- }
706
- }
707
-
708
- const resolveDependency = (cwd = process.cwd()) => {
709
- const dependencies = resolveDependenciesSync(cwd);
710
- function resolve(dependency, options = {}) {
711
- const { includeSources = false } = options;
712
- let dependencyPaths = {
713
- root: ".",
714
- source: "",
715
- sourcePath: "",
716
- sourcePathRelative: "",
717
- dependency,
718
- fromRoot: dependency,
719
- fromModule: dependency,
720
- denormalized: dependency
721
- };
722
- dependencies.forEach((root, depCandidate) => {
723
- if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) {
724
- const relative = dependency.replace(depCandidate, "");
725
- const rootCandidate = dependency.replace(depCandidate, root);
726
- let source = "";
727
- let sourcePath = "";
728
- const fromRoot = [
729
- `${rootCandidate}`,
730
- `${rootCandidate}/index`,
731
- `${rootCandidate}/src/index`
732
- ].find(
733
- (location) => ["ts", "tsx"].find((extension) => {
734
- const candidatePath = `${location}.${extension}`;
735
- const exists = fs.existsSync(candidatePath);
736
- if (includeSources && exists) {
737
- source = fs.readFileSync(candidatePath, "utf-8");
738
- sourcePath = candidatePath;
739
- }
740
- return exists;
741
- })
742
- );
743
- if (!fromRoot) {
744
- return;
745
- }
746
- const denormalized = fromRoot.replace(root, depCandidate);
747
- let fromModule = !relative ? "." : `./${relative.split("/")[relative.split("/").length - 1]}`;
748
- const sourcePathRelative = !sourcePath ? "." : `./${sourcePath.split("/")[sourcePath.split("/").length - 1]}`;
749
- if (dependency.startsWith("./")) fromModule = `.${relative}`;
750
- dependencyPaths = {
751
- root,
752
- dependency,
753
- denormalized,
754
- fromRoot,
755
- fromModule,
756
- source,
757
- sourcePath,
758
- sourcePathRelative
759
- };
760
- }
761
- });
762
- return dependencyPaths;
763
- }
764
- return resolve;
765
- };
766
-
767
337
  function isIdentifier(node) {
768
338
  return node.type === "Identifier";
769
339
  }
@@ -860,7 +430,7 @@ function extractValue(node, path, optional = false) {
860
430
  }
861
431
  }
862
432
  function extractExports(module) {
863
- const exports = {};
433
+ const exports$1 = {};
864
434
  const errors = [];
865
435
  for (const moduleItem of module.body) {
866
436
  switch (moduleItem.type) {
@@ -874,19 +444,19 @@ function extractExports(module) {
874
444
  switch (moduleItem.declaration.type) {
875
445
  case "ClassDeclaration":
876
446
  case "FunctionDeclaration":
877
- exports[moduleItem.declaration.identifier.value] = RUNTIME_VALUE;
447
+ exports$1[moduleItem.declaration.identifier.value] = RUNTIME_VALUE;
878
448
  break;
879
449
  case "VariableDeclaration":
880
450
  moduleItem.declaration.declarations.forEach((decl) => {
881
451
  if (isIdentifier(decl.id) && decl.init) {
882
- exports[decl.id.value] = extractValue(decl.init, void 0, true);
452
+ exports$1[decl.id.value] = extractValue(decl.init, void 0, true);
883
453
  }
884
454
  });
885
455
  break;
886
456
  }
887
457
  }
888
458
  }
889
- return [exports, errors];
459
+ return [exports$1, errors];
890
460
  }
891
461
 
892
462
  const pluginConfigParsed = z.object({
@@ -900,7 +470,7 @@ function nonNullable(value) {
900
470
  }
901
471
  const isObject = (input) => typeof input === "object" && input !== null && !Array.isArray(input);
902
472
  function parseStructure(ast, gcConfig, sourceModule) {
903
- const [exports, errors] = extractExports(ast);
473
+ const [exports$1, errors] = extractExports(ast);
904
474
  if (errors.length) console.error("Plugin error for", errors.join("\n"));
905
475
  const {
906
476
  config: moduleConfig,
@@ -911,7 +481,7 @@ function parseStructure(ast, gcConfig, sourceModule) {
911
481
  plugin,
912
482
  Plugin,
913
483
  ...rest
914
- } = exports;
484
+ } = exports$1;
915
485
  const exportVals = Object.keys(rest);
916
486
  if (component && !moduleConfig) exportVals.push("Plugin");
917
487
  if (func && !moduleConfig) exportVals.push("plugin");
@@ -945,7 +515,7 @@ function parseStructure(ast, gcConfig, sourceModule) {
945
515
  }
946
516
  }
947
517
  const val = {
948
- targetExport: exports.component || exports.func || parsed.data.export,
518
+ targetExport: exports$1.component || exports$1.func || parsed.data.export,
949
519
  sourceModule,
950
520
  sourceExport: parsed.data.export,
951
521
  targetModule: parsed.data.module,
@@ -1023,9 +593,6 @@ function parseSync(src) {
1023
593
  comments: true
1024
594
  });
1025
595
  }
1026
- function printSync(m) {
1027
- return printSync$1(m);
1028
- }
1029
596
 
1030
597
  function parseAndFindExport(resolved, findExport, resolve) {
1031
598
  if (!resolved?.source) return void 0;
@@ -1058,16 +625,16 @@ function parseAndFindExport(resolved, findExport, resolve) {
1058
625
  }
1059
626
  }
1060
627
  }
1061
- const exports = ast.body.filter((node) => node.type === "ExportAllDeclaration").sort((a, b) => {
628
+ const exports$1 = ast.body.filter((node) => node.type === "ExportAllDeclaration").sort((a, b) => {
1062
629
  const probablyA = a.source.value.includes(findExport);
1063
630
  const probablyB = b.source.value.includes(findExport);
1064
631
  return probablyA === probablyB ? 0 : probablyA ? -1 : 1;
1065
632
  });
1066
- for (const node of exports) {
633
+ for (const node of exports$1) {
1067
634
  const isRelative = node.source.value.startsWith(".");
1068
635
  if (isRelative) {
1069
636
  const d = resolved.dependency === resolved.denormalized ? resolved.dependency.substring(0, resolved.dependency.lastIndexOf("/")) : resolved.dependency;
1070
- const newPath = path$1.join(d, node.source.value);
637
+ const newPath = path.join(d, node.source.value);
1071
638
  const resolveResult = resolve(newPath, { includeSources: true });
1072
639
  if (!resolveResult) continue;
1073
640
  const newResolved = parseAndFindExport(resolveResult, findExport, resolve);
@@ -1094,1443 +661,12 @@ function findOriginalSource(plug, resolved, resolve) {
1094
661
  return { resolved: newResolved, error: void 0 };
1095
662
  }
1096
663
 
1097
- class Visitor {
1098
- visitProgram(n) {
1099
- switch (n.type) {
1100
- case "Module":
1101
- return this.visitModule(n);
1102
- case "Script":
1103
- return this.visitScript(n);
1104
- }
1105
- }
1106
- visitModule(m) {
1107
- m.body = this.visitModuleItems(m.body);
1108
- return m;
1109
- }
1110
- visitScript(m) {
1111
- m.body = this.visitStatements(m.body);
1112
- return m;
1113
- }
1114
- visitModuleItems(items) {
1115
- return items.map(this.visitModuleItem.bind(this));
1116
- }
1117
- visitModuleItem(n) {
1118
- switch (n.type) {
1119
- case "ExportDeclaration":
1120
- case "ExportDefaultDeclaration":
1121
- case "ExportNamedDeclaration":
1122
- case "ExportDefaultExpression":
1123
- case "ImportDeclaration":
1124
- case "ExportAllDeclaration":
1125
- case "TsImportEqualsDeclaration":
1126
- case "TsExportAssignment":
1127
- case "TsNamespaceExportDeclaration":
1128
- return this.visitModuleDeclaration(n);
1129
- default:
1130
- return this.visitStatement(n);
1131
- }
1132
- }
1133
- visitModuleDeclaration(n) {
1134
- switch (n.type) {
1135
- case "ExportDeclaration":
1136
- return this.visitExportDeclaration(n);
1137
- case "ExportDefaultDeclaration":
1138
- return this.visitExportDefaultDeclaration(n);
1139
- case "ExportNamedDeclaration":
1140
- return this.visitExportNamedDeclaration(n);
1141
- case "ExportDefaultExpression":
1142
- return this.visitExportDefaultExpression(n);
1143
- case "ImportDeclaration":
1144
- return this.visitImportDeclaration(n);
1145
- case "ExportAllDeclaration":
1146
- return this.visitExportAllDeclaration(n);
1147
- case "TsImportEqualsDeclaration":
1148
- return this.visitTsImportEqualsDeclaration(n);
1149
- case "TsExportAssignment":
1150
- return this.visitTsExportAssignment(n);
1151
- case "TsNamespaceExportDeclaration":
1152
- return this.visitTsNamespaceExportDeclaration(n);
1153
- }
1154
- }
1155
- visitTsNamespaceExportDeclaration(n) {
1156
- n.id = this.visitBindingIdentifier(n.id);
1157
- return n;
1158
- }
1159
- visitTsExportAssignment(n) {
1160
- n.expression = this.visitExpression(n.expression);
1161
- return n;
1162
- }
1163
- visitTsImportEqualsDeclaration(n) {
1164
- n.id = this.visitBindingIdentifier(n.id);
1165
- n.moduleRef = this.visitTsModuleReference(n.moduleRef);
1166
- return n;
1167
- }
1168
- visitTsModuleReference(n) {
1169
- switch (n.type) {
1170
- case "Identifier":
1171
- return this.visitIdentifierReference(n);
1172
- case "TsExternalModuleReference":
1173
- return this.visitTsExternalModuleReference(n);
1174
- case "TsQualifiedName":
1175
- return this.visitTsQualifiedName(n);
1176
- }
1177
- }
1178
- visitTsExternalModuleReference(n) {
1179
- n.expression = this.visitStringLiteral(n.expression);
1180
- return n;
1181
- }
1182
- visitExportAllDeclaration(n) {
1183
- n.source = this.visitStringLiteral(n.source);
1184
- return n;
1185
- }
1186
- visitExportDefaultExpression(n) {
1187
- n.expression = this.visitExpression(n.expression);
1188
- return n;
1189
- }
1190
- visitExportNamedDeclaration(n) {
1191
- n.specifiers = this.visitExportSpecifiers(n.specifiers);
1192
- n.source = this.visitOptionalStringLiteral(n.source);
1193
- return n;
1194
- }
1195
- visitExportSpecifiers(nodes) {
1196
- return nodes.map(this.visitExportSpecifier.bind(this));
1197
- }
1198
- visitExportSpecifier(n) {
1199
- switch (n.type) {
1200
- case "ExportDefaultSpecifier":
1201
- return this.visitExportDefaultSpecifier(n);
1202
- case "ExportNamespaceSpecifier":
1203
- return this.visitExportNamespaceSpecifier(n);
1204
- case "ExportSpecifier":
1205
- return this.visitNamedExportSpecifier(n);
1206
- }
1207
- }
1208
- visitNamedExportSpecifier(n) {
1209
- if (n.exported) {
1210
- n.exported = this.visitModuleExportName(n.exported);
1211
- }
1212
- n.orig = this.visitModuleExportName(n.orig);
1213
- return n;
1214
- }
1215
- visitModuleExportName(n) {
1216
- switch (n.type) {
1217
- case "Identifier":
1218
- return this.visitIdentifier(n);
1219
- case "StringLiteral":
1220
- return this.visitStringLiteral(n);
1221
- }
1222
- }
1223
- visitExportNamespaceSpecifier(n) {
1224
- n.name = this.visitModuleExportName(n.name);
1225
- return n;
1226
- }
1227
- visitExportDefaultSpecifier(n) {
1228
- n.exported = this.visitBindingIdentifier(n.exported);
1229
- return n;
1230
- }
1231
- visitOptionalStringLiteral(n) {
1232
- if (n) {
1233
- return this.visitStringLiteral(n);
1234
- }
1235
- }
1236
- visitExportDefaultDeclaration(n) {
1237
- n.decl = this.visitDefaultDeclaration(n.decl);
1238
- return n;
1239
- }
1240
- visitDefaultDeclaration(n) {
1241
- switch (n.type) {
1242
- case "ClassExpression":
1243
- return this.visitClassExpression(n);
1244
- case "FunctionExpression":
1245
- return this.visitFunctionExpression(n);
1246
- case "TsInterfaceDeclaration":
1247
- return this.visitTsInterfaceDeclaration(n);
1248
- }
1249
- }
1250
- visitFunctionExpression(n) {
1251
- n = this.visitFunction(n);
1252
- if (n.identifier) {
1253
- n.identifier = this.visitBindingIdentifier(n.identifier);
1254
- }
1255
- return n;
1256
- }
1257
- visitClassExpression(n) {
1258
- n = this.visitClass(n);
1259
- if (n.identifier) {
1260
- n.identifier = this.visitBindingIdentifier(n.identifier);
1261
- }
1262
- return n;
1263
- }
1264
- visitExportDeclaration(n) {
1265
- n.declaration = this.visitDeclaration(n.declaration);
1266
- return n;
1267
- }
1268
- visitArrayExpression(e) {
1269
- if (e.elements) {
1270
- e.elements = e.elements.map(this.visitArrayElement.bind(this));
1271
- }
1272
- return e;
1273
- }
1274
- visitArrayElement(e) {
1275
- if (e) {
1276
- return this.visitExprOrSpread(e);
1277
- }
1278
- }
1279
- visitExprOrSpread(e) {
1280
- return {
1281
- ...e,
1282
- expression: this.visitExpression(e.expression)
1283
- };
1284
- }
1285
- visitExprOrSpreads(nodes) {
1286
- return nodes.map(this.visitExprOrSpread.bind(this));
1287
- }
1288
- visitSpreadElement(e) {
1289
- e.arguments = this.visitExpression(e.arguments);
1290
- return e;
1291
- }
1292
- visitOptionalExpression(e) {
1293
- if (e) {
1294
- return this.visitExpression(e);
1295
- }
1296
- }
1297
- visitArrowFunctionExpression(e) {
1298
- e.body = this.visitArrowBody(e.body);
1299
- e.params = this.visitPatterns(e.params);
1300
- e.returnType = this.visitTsTypeAnnotation(e.returnType);
1301
- e.typeParameters = this.visitTsTypeParameterDeclaration(e.typeParameters);
1302
- return e;
1303
- }
1304
- visitArrowBody(body) {
1305
- switch (body.type) {
1306
- case "BlockStatement":
1307
- return this.visitBlockStatement(body);
1308
- default:
1309
- return this.visitExpression(body);
1310
- }
1311
- }
1312
- visitBlockStatement(block) {
1313
- block.stmts = this.visitStatements(block.stmts);
1314
- return block;
1315
- }
1316
- visitStatements(stmts) {
1317
- return stmts.map(this.visitStatement.bind(this));
1318
- }
1319
- visitStatement(stmt) {
1320
- switch (stmt.type) {
1321
- case "ClassDeclaration":
1322
- case "FunctionDeclaration":
1323
- case "TsEnumDeclaration":
1324
- case "TsInterfaceDeclaration":
1325
- case "TsModuleDeclaration":
1326
- case "TsTypeAliasDeclaration":
1327
- case "VariableDeclaration":
1328
- return this.visitDeclaration(stmt);
1329
- case "BreakStatement":
1330
- return this.visitBreakStatement(stmt);
1331
- case "BlockStatement":
1332
- return this.visitBlockStatement(stmt);
1333
- case "ContinueStatement":
1334
- return this.visitContinueStatement(stmt);
1335
- case "DebuggerStatement":
1336
- return this.visitDebuggerStatement(stmt);
1337
- case "DoWhileStatement":
1338
- return this.visitDoWhileStatement(stmt);
1339
- case "EmptyStatement":
1340
- return this.visitEmptyStatement(stmt);
1341
- case "ForInStatement":
1342
- return this.visitForInStatement(stmt);
1343
- case "ForOfStatement":
1344
- return this.visitForOfStatement(stmt);
1345
- case "ForStatement":
1346
- return this.visitForStatement(stmt);
1347
- case "IfStatement":
1348
- return this.visitIfStatement(stmt);
1349
- case "LabeledStatement":
1350
- return this.visitLabeledStatement(stmt);
1351
- case "ReturnStatement":
1352
- return this.visitReturnStatement(stmt);
1353
- case "SwitchStatement":
1354
- return this.visitSwitchStatement(stmt);
1355
- case "ThrowStatement":
1356
- return this.visitThrowStatement(stmt);
1357
- case "TryStatement":
1358
- return this.visitTryStatement(stmt);
1359
- case "WhileStatement":
1360
- return this.visitWhileStatement(stmt);
1361
- case "WithStatement":
1362
- return this.visitWithStatement(stmt);
1363
- case "ExpressionStatement":
1364
- return this.visitExpressionStatement(stmt);
1365
- default:
1366
- throw new Error(`Unknown statement type: ${stmt.type}`);
1367
- }
1368
- }
1369
- visitSwitchStatement(stmt) {
1370
- stmt.discriminant = this.visitExpression(stmt.discriminant);
1371
- stmt.cases = this.visitSwitchCases(stmt.cases);
1372
- return stmt;
1373
- }
1374
- visitSwitchCases(cases) {
1375
- return cases.map(this.visitSwitchCase.bind(this));
1376
- }
1377
- visitSwitchCase(c) {
1378
- c.test = this.visitOptionalExpression(c.test);
1379
- c.consequent = this.visitStatements(c.consequent);
1380
- return c;
1381
- }
1382
- visitIfStatement(stmt) {
1383
- stmt.test = this.visitExpression(stmt.test);
1384
- stmt.consequent = this.visitStatement(stmt.consequent);
1385
- stmt.alternate = this.visitOptionalStatement(stmt.alternate);
1386
- return stmt;
1387
- }
1388
- visitOptionalStatement(stmt) {
1389
- if (stmt) {
1390
- return this.visitStatement(stmt);
1391
- }
1392
- }
1393
- visitBreakStatement(stmt) {
1394
- if (stmt.label) {
1395
- stmt.label = this.visitLabelIdentifier(stmt.label);
1396
- }
1397
- return stmt;
1398
- }
1399
- visitWhileStatement(stmt) {
1400
- stmt.test = this.visitExpression(stmt.test);
1401
- stmt.body = this.visitStatement(stmt.body);
1402
- return stmt;
1403
- }
1404
- visitTryStatement(stmt) {
1405
- stmt.block = this.visitBlockStatement(stmt.block);
1406
- stmt.handler = this.visitCatchClause(stmt.handler);
1407
- if (stmt.finalizer) {
1408
- stmt.finalizer = this.visitBlockStatement(stmt.finalizer);
1409
- }
1410
- return stmt;
1411
- }
1412
- visitCatchClause(handler) {
1413
- if (handler) {
1414
- if (handler.param) {
1415
- handler.param = this.visitPattern(handler.param);
1416
- }
1417
- handler.body = this.visitBlockStatement(handler.body);
1418
- }
1419
- return handler;
1420
- }
1421
- visitThrowStatement(stmt) {
1422
- stmt.argument = this.visitExpression(stmt.argument);
1423
- return stmt;
1424
- }
1425
- visitReturnStatement(stmt) {
1426
- if (stmt.argument) {
1427
- stmt.argument = this.visitExpression(stmt.argument);
1428
- }
1429
- return stmt;
1430
- }
1431
- visitLabeledStatement(stmt) {
1432
- stmt.label = this.visitLabelIdentifier(stmt.label);
1433
- stmt.body = this.visitStatement(stmt.body);
1434
- return stmt;
1435
- }
1436
- visitForStatement(stmt) {
1437
- if (stmt.init) {
1438
- if (stmt.init.type === "VariableDeclaration") {
1439
- stmt.init = this.visitVariableDeclaration(stmt.init);
1440
- } else {
1441
- stmt.init = this.visitOptionalExpression(stmt.init);
1442
- }
1443
- }
1444
- stmt.test = this.visitOptionalExpression(stmt.test);
1445
- stmt.update = this.visitOptionalExpression(stmt.update);
1446
- stmt.body = this.visitStatement(stmt.body);
1447
- return stmt;
1448
- }
1449
- visitForOfStatement(stmt) {
1450
- if (stmt.left.type === "VariableDeclaration") {
1451
- stmt.left = this.visitVariableDeclaration(stmt.left);
1452
- } else {
1453
- stmt.left = this.visitPattern(stmt.left);
1454
- }
1455
- stmt.right = this.visitExpression(stmt.right);
1456
- stmt.body = this.visitStatement(stmt.body);
1457
- return stmt;
1458
- }
1459
- visitForInStatement(stmt) {
1460
- if (stmt.left.type === "VariableDeclaration") {
1461
- stmt.left = this.visitVariableDeclaration(stmt.left);
1462
- } else {
1463
- stmt.left = this.visitPattern(stmt.left);
1464
- }
1465
- stmt.right = this.visitExpression(stmt.right);
1466
- stmt.body = this.visitStatement(stmt.body);
1467
- return stmt;
1468
- }
1469
- visitEmptyStatement(stmt) {
1470
- return stmt;
1471
- }
1472
- visitDoWhileStatement(stmt) {
1473
- stmt.body = this.visitStatement(stmt.body);
1474
- stmt.test = this.visitExpression(stmt.test);
1475
- return stmt;
1476
- }
1477
- visitDebuggerStatement(stmt) {
1478
- return stmt;
1479
- }
1480
- visitWithStatement(stmt) {
1481
- stmt.object = this.visitExpression(stmt.object);
1482
- stmt.body = this.visitStatement(stmt.body);
1483
- return stmt;
1484
- }
1485
- visitDeclaration(decl) {
1486
- switch (decl.type) {
1487
- case "ClassDeclaration":
1488
- return this.visitClassDeclaration(decl);
1489
- case "FunctionDeclaration":
1490
- return this.visitFunctionDeclaration(decl);
1491
- case "TsEnumDeclaration":
1492
- return this.visitTsEnumDeclaration(decl);
1493
- case "TsInterfaceDeclaration":
1494
- return this.visitTsInterfaceDeclaration(decl);
1495
- case "TsModuleDeclaration":
1496
- return this.visitTsModuleDeclaration(decl);
1497
- case "TsTypeAliasDeclaration":
1498
- return this.visitTsTypeAliasDeclaration(decl);
1499
- case "VariableDeclaration":
1500
- return this.visitVariableDeclaration(decl);
1501
- }
1502
- }
1503
- visitVariableDeclaration(n) {
1504
- n.declarations = this.visitVariableDeclarators(n.declarations);
1505
- return n;
1506
- }
1507
- visitVariableDeclarators(nodes) {
1508
- return nodes.map(this.visitVariableDeclarator.bind(this));
1509
- }
1510
- visitVariableDeclarator(n) {
1511
- n.id = this.visitPattern(n.id);
1512
- n.init = this.visitOptionalExpression(n.init);
1513
- return n;
1514
- }
1515
- visitTsTypeAliasDeclaration(n) {
1516
- n.id = this.visitBindingIdentifier(n.id);
1517
- n.typeAnnotation = this.visitTsType(n.typeAnnotation);
1518
- n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams);
1519
- return n;
1520
- }
1521
- visitTsModuleDeclaration(n) {
1522
- n.id = this.visitTsModuleName(n.id);
1523
- if (n.body) {
1524
- n.body = this.visitTsNamespaceBody(n.body);
1525
- }
1526
- return n;
1527
- }
1528
- visitTsModuleName(n) {
1529
- switch (n.type) {
1530
- case "Identifier":
1531
- return this.visitBindingIdentifier(n);
1532
- case "StringLiteral":
1533
- return this.visitStringLiteral(n);
1534
- }
1535
- }
1536
- visitTsNamespaceBody(n) {
1537
- if (n) {
1538
- switch (n.type) {
1539
- case "TsModuleBlock":
1540
- return this.visitTsModuleBlock(n);
1541
- case "TsNamespaceDeclaration":
1542
- return this.visitTsNamespaceDeclaration(n);
1543
- }
1544
- }
1545
- }
1546
- visitTsNamespaceDeclaration(n) {
1547
- const body = this.visitTsNamespaceBody(n.body);
1548
- if (body) {
1549
- n.body = body;
1550
- }
1551
- n.id = this.visitBindingIdentifier(n.id);
1552
- return n;
1553
- }
1554
- visitTsModuleBlock(n) {
1555
- n.body = this.visitModuleItems(n.body);
1556
- return n;
1557
- }
1558
- visitTsInterfaceDeclaration(n) {
1559
- n.id = this.visitBindingIdentifier(n.id);
1560
- n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams);
1561
- n.extends = this.visitTsExpressionsWithTypeArguments(n.extends);
1562
- n.body = this.visitTsInterfaceBody(n.body);
1563
- return n;
1564
- }
1565
- visitTsInterfaceBody(n) {
1566
- n.body = this.visitTsTypeElements(n.body);
1567
- return n;
1568
- }
1569
- visitTsTypeElements(nodes) {
1570
- return nodes.map(this.visitTsTypeElement.bind(this));
1571
- }
1572
- visitTsTypeElement(n) {
1573
- switch (n.type) {
1574
- case "TsCallSignatureDeclaration":
1575
- return this.visitTsCallSignatureDeclaration(n);
1576
- case "TsConstructSignatureDeclaration":
1577
- return this.visitTsConstructSignatureDeclaration(n);
1578
- case "TsPropertySignature":
1579
- return this.visitTsPropertySignature(n);
1580
- case "TsGetterSignature":
1581
- return this.visitTsGetterSignature(n);
1582
- case "TsSetterSignature":
1583
- return this.visitTsSetterSignature(n);
1584
- case "TsMethodSignature":
1585
- return this.visitTsMethodSignature(n);
1586
- case "TsIndexSignature":
1587
- return this.visitTsIndexSignature(n);
1588
- }
1589
- }
1590
- visitTsCallSignatureDeclaration(n) {
1591
- n.params = this.visitTsFnParameters(n.params);
1592
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1593
- return n;
1594
- }
1595
- visitTsConstructSignatureDeclaration(n) {
1596
- n.params = this.visitTsFnParameters(n.params);
1597
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1598
- return n;
1599
- }
1600
- visitTsPropertySignature(n) {
1601
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1602
- return n;
1603
- }
1604
- visitTsGetterSignature(n) {
1605
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1606
- return n;
1607
- }
1608
- visitTsSetterSignature(n) {
1609
- n.param = this.visitTsFnParameter(n.param);
1610
- return n;
1611
- }
1612
- visitTsMethodSignature(n) {
1613
- n.params = this.visitTsFnParameters(n.params);
1614
- n.typeAnn = this.visitTsTypeAnnotation(n.typeAnn);
1615
- return n;
1616
- }
1617
- visitTsEnumDeclaration(n) {
1618
- n.id = this.visitIdentifier(n.id);
1619
- n.members = this.visitTsEnumMembers(n.members);
1620
- return n;
1621
- }
1622
- visitTsEnumMembers(nodes) {
1623
- return nodes.map(this.visitTsEnumMember.bind(this));
1624
- }
1625
- visitTsEnumMember(n) {
1626
- n.id = this.visitTsEnumMemberId(n.id);
1627
- n.init = this.visitOptionalExpression(n.init);
1628
- return n;
1629
- }
1630
- visitTsEnumMemberId(n) {
1631
- switch (n.type) {
1632
- case "Identifier":
1633
- return this.visitBindingIdentifier(n);
1634
- case "StringLiteral":
1635
- return this.visitStringLiteral(n);
1636
- }
1637
- }
1638
- visitFunctionDeclaration(decl) {
1639
- decl.identifier = this.visitIdentifier(decl.identifier);
1640
- decl = this.visitFunction(decl);
1641
- return decl;
1642
- }
1643
- visitClassDeclaration(decl) {
1644
- decl = this.visitClass(decl);
1645
- decl.identifier = this.visitIdentifier(decl.identifier);
1646
- return decl;
1647
- }
1648
- visitClassBody(members) {
1649
- return members.map(this.visitClassMember.bind(this));
1650
- }
1651
- visitClassMember(member) {
1652
- switch (member.type) {
1653
- case "ClassMethod":
1654
- return this.visitClassMethod(member);
1655
- case "ClassProperty":
1656
- return this.visitClassProperty(member);
1657
- case "Constructor":
1658
- return this.visitConstructor(member);
1659
- case "PrivateMethod":
1660
- return this.visitPrivateMethod(member);
1661
- case "PrivateProperty":
1662
- return this.visitPrivateProperty(member);
1663
- case "TsIndexSignature":
1664
- return this.visitTsIndexSignature(member);
1665
- case "EmptyStatement":
1666
- return this.visitEmptyStatement(member);
1667
- case "StaticBlock":
1668
- return this.visitStaticBlock(member);
1669
- }
1670
- }
1671
- visitTsIndexSignature(n) {
1672
- n.params = this.visitTsFnParameters(n.params);
1673
- if (n.typeAnnotation) n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1674
- return n;
1675
- }
1676
- visitTsFnParameters(params) {
1677
- return params.map(this.visitTsFnParameter.bind(this));
1678
- }
1679
- visitTsFnParameter(n) {
1680
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1681
- return n;
1682
- }
1683
- visitPrivateProperty(n) {
1684
- n.decorators = this.visitDecorators(n.decorators);
1685
- n.key = this.visitPrivateName(n.key);
1686
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1687
- n.value = this.visitOptionalExpression(n.value);
1688
- return n;
1689
- }
1690
- visitPrivateMethod(n) {
1691
- n.accessibility = this.visitAccessibility(n.accessibility);
1692
- n.function = this.visitFunction(n.function);
1693
- n.key = this.visitPrivateName(n.key);
1694
- return n;
1695
- }
1696
- visitPrivateName(n) {
1697
- return n;
1698
- }
1699
- visitConstructor(n) {
1700
- n.accessibility = this.visitAccessibility(n.accessibility);
1701
- n.key = this.visitPropertyName(n.key);
1702
- n.params = this.visitConstructorParameters(n.params);
1703
- if (n.body) {
1704
- n.body = this.visitBlockStatement(n.body);
1705
- }
1706
- return n;
1707
- }
1708
- visitConstructorParameters(nodes) {
1709
- return nodes.map(this.visitConstructorParameter.bind(this));
1710
- }
1711
- visitConstructorParameter(n) {
1712
- switch (n.type) {
1713
- case "TsParameterProperty":
1714
- return this.visitTsParameterProperty(n);
1715
- default:
1716
- return this.visitParameter(n);
1717
- }
1718
- }
1719
- visitStaticBlock(n) {
1720
- n.body = this.visitBlockStatement(n.body);
1721
- return n;
1722
- }
1723
- visitTsParameterProperty(n) {
1724
- n.accessibility = this.visitAccessibility(n.accessibility);
1725
- n.decorators = this.visitDecorators(n.decorators);
1726
- n.param = this.visitTsParameterPropertyParameter(n.param);
1727
- return n;
1728
- }
1729
- visitTsParameterPropertyParameter(n) {
1730
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1731
- return n;
1732
- }
1733
- visitPropertyName(key) {
1734
- switch (key.type) {
1735
- case "Identifier":
1736
- return this.visitBindingIdentifier(key);
1737
- case "StringLiteral":
1738
- return this.visitStringLiteral(key);
1739
- case "NumericLiteral":
1740
- return this.visitNumericLiteral(key);
1741
- case "BigIntLiteral":
1742
- return this.visitBigIntLiteral(key);
1743
- default:
1744
- return this.visitComputedPropertyKey(key);
1745
- }
1746
- }
1747
- visitAccessibility(n) {
1748
- return n;
1749
- }
1750
- visitClassProperty(n) {
1751
- n.accessibility = this.visitAccessibility(n.accessibility);
1752
- n.decorators = this.visitDecorators(n.decorators);
1753
- n.key = this.visitPropertyName(n.key);
1754
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
1755
- n.value = this.visitOptionalExpression(n.value);
1756
- return n;
1757
- }
1758
- visitClassMethod(n) {
1759
- n.accessibility = this.visitAccessibility(n.accessibility);
1760
- n.function = this.visitFunction(n.function);
1761
- n.key = this.visitPropertyName(n.key);
1762
- return n;
1763
- }
1764
- visitComputedPropertyKey(n) {
1765
- n.expression = this.visitExpression(n.expression);
1766
- return n;
1767
- }
1768
- visitClass(n) {
1769
- n.decorators = this.visitDecorators(n.decorators);
1770
- n.superClass = this.visitOptionalExpression(n.superClass);
1771
- n.superTypeParams = this.visitTsTypeParameterInstantiation(n.superTypeParams);
1772
- if (n.implements) {
1773
- n.implements = this.visitTsExpressionsWithTypeArguments(n.implements);
1774
- }
1775
- n.body = this.visitClassBody(n.body);
1776
- return n;
1777
- }
1778
- visitFunction(n) {
1779
- n.decorators = this.visitDecorators(n.decorators);
1780
- n.params = this.visitParameters(n.params);
1781
- if (n.body) {
1782
- n.body = this.visitBlockStatement(n.body);
1783
- }
1784
- n.returnType = this.visitTsTypeAnnotation(n.returnType);
1785
- n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters);
1786
- return n;
1787
- }
1788
- visitTsExpressionsWithTypeArguments(nodes) {
1789
- return nodes.map(this.visitTsExpressionWithTypeArguments.bind(this));
1790
- }
1791
- visitTsExpressionWithTypeArguments(n) {
1792
- n.expression = this.visitExpression(n.expression);
1793
- n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments);
1794
- return n;
1795
- }
1796
- visitTsTypeParameterInstantiation(n) {
1797
- if (n) {
1798
- n.params = this.visitTsTypes(n.params);
1799
- }
1800
- return n;
1801
- }
1802
- visitTsTypes(nodes) {
1803
- return nodes.map(this.visitTsType.bind(this));
1804
- }
1805
- visitTsEntityName(n) {
1806
- switch (n.type) {
1807
- case "Identifier":
1808
- return this.visitBindingIdentifier(n);
1809
- case "TsQualifiedName":
1810
- return this.visitTsQualifiedName(n);
1811
- }
1812
- }
1813
- visitTsQualifiedName(n) {
1814
- n.left = this.visitTsEntityName(n.left);
1815
- n.right = this.visitIdentifier(n.right);
1816
- return n;
1817
- }
1818
- visitDecorators(nodes) {
1819
- if (nodes) {
1820
- return nodes.map(this.visitDecorator.bind(this));
1821
- }
1822
- }
1823
- visitDecorator(n) {
1824
- n.expression = this.visitExpression(n.expression);
1825
- return n;
1826
- }
1827
- visitExpressionStatement(stmt) {
1828
- stmt.expression = this.visitExpression(stmt.expression);
1829
- return stmt;
1830
- }
1831
- visitContinueStatement(stmt) {
1832
- if (stmt.label) {
1833
- stmt.label = this.visitLabelIdentifier(stmt.label);
1834
- }
1835
- return stmt;
1836
- }
1837
- visitExpression(n) {
1838
- switch (n.type) {
1839
- case "ArrayExpression":
1840
- return this.visitArrayExpression(n);
1841
- case "ArrowFunctionExpression":
1842
- return this.visitArrowFunctionExpression(n);
1843
- case "AssignmentExpression":
1844
- return this.visitAssignmentExpression(n);
1845
- case "AwaitExpression":
1846
- return this.visitAwaitExpression(n);
1847
- case "BigIntLiteral":
1848
- return this.visitBigIntLiteral(n);
1849
- case "BinaryExpression":
1850
- return this.visitBinaryExpression(n);
1851
- case "BooleanLiteral":
1852
- return this.visitBooleanLiteral(n);
1853
- case "CallExpression":
1854
- return this.visitCallExpression(n);
1855
- case "ClassExpression":
1856
- return this.visitClassExpression(n);
1857
- case "ConditionalExpression":
1858
- return this.visitConditionalExpression(n);
1859
- case "FunctionExpression":
1860
- return this.visitFunctionExpression(n);
1861
- case "Identifier":
1862
- return this.visitIdentifierReference(n);
1863
- case "JSXElement":
1864
- return this.visitJSXElement(n);
1865
- case "JSXEmptyExpression":
1866
- return this.visitJSXEmptyExpression(n);
1867
- case "JSXFragment":
1868
- return this.visitJSXFragment(n);
1869
- case "JSXMemberExpression":
1870
- return this.visitJSXMemberExpression(n);
1871
- case "JSXNamespacedName":
1872
- return this.visitJSXNamespacedName(n);
1873
- case "JSXText":
1874
- return this.visitJSXText(n);
1875
- case "MemberExpression":
1876
- return this.visitMemberExpression(n);
1877
- case "SuperPropExpression":
1878
- return this.visitSuperPropExpression(n);
1879
- case "MetaProperty":
1880
- return this.visitMetaProperty(n);
1881
- case "NewExpression":
1882
- return this.visitNewExpression(n);
1883
- case "NullLiteral":
1884
- return this.visitNullLiteral(n);
1885
- case "NumericLiteral":
1886
- return this.visitNumericLiteral(n);
1887
- case "ObjectExpression":
1888
- return this.visitObjectExpression(n);
1889
- case "ParenthesisExpression":
1890
- return this.visitParenthesisExpression(n);
1891
- case "PrivateName":
1892
- return this.visitPrivateName(n);
1893
- case "RegExpLiteral":
1894
- return this.visitRegExpLiteral(n);
1895
- case "SequenceExpression":
1896
- return this.visitSequenceExpression(n);
1897
- case "StringLiteral":
1898
- return this.visitStringLiteral(n);
1899
- case "TaggedTemplateExpression":
1900
- return this.visitTaggedTemplateExpression(n);
1901
- case "TemplateLiteral":
1902
- return this.visitTemplateLiteral(n);
1903
- case "ThisExpression":
1904
- return this.visitThisExpression(n);
1905
- case "TsAsExpression":
1906
- return this.visitTsAsExpression(n);
1907
- case "TsSatisfiesExpression":
1908
- return this.visitTsSatisfiesExpression(n);
1909
- case "TsNonNullExpression":
1910
- return this.visitTsNonNullExpression(n);
1911
- case "TsTypeAssertion":
1912
- return this.visitTsTypeAssertion(n);
1913
- case "TsConstAssertion":
1914
- return this.visitTsConstAssertion(n);
1915
- case "TsInstantiation":
1916
- return this.visitTsInstantiation(n);
1917
- case "UnaryExpression":
1918
- return this.visitUnaryExpression(n);
1919
- case "UpdateExpression":
1920
- return this.visitUpdateExpression(n);
1921
- case "YieldExpression":
1922
- return this.visitYieldExpression(n);
1923
- case "OptionalChainingExpression":
1924
- return this.visitOptionalChainingExpression(n);
1925
- case "Invalid":
1926
- return n;
1927
- }
1928
- }
1929
- visitOptionalChainingExpression(n) {
1930
- n.base = this.visitMemberExpressionOrOptionalChainingCall(n.base);
1931
- return n;
1932
- }
1933
- visitMemberExpressionOrOptionalChainingCall(n) {
1934
- switch (n.type) {
1935
- case "MemberExpression":
1936
- return this.visitMemberExpression(n);
1937
- case "CallExpression":
1938
- return this.visitOptionalChainingCall(n);
1939
- }
1940
- }
1941
- visitOptionalChainingCall(n) {
1942
- n.callee = this.visitExpression(n.callee);
1943
- n.arguments = this.visitExprOrSpreads(n.arguments);
1944
- if (n.typeArguments) n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments);
1945
- return n;
1946
- }
1947
- visitAssignmentExpression(n) {
1948
- n.left = this.visitPatternOrExpression(n.left);
1949
- n.right = this.visitExpression(n.right);
1950
- return n;
1951
- }
1952
- visitPatternOrExpression(n) {
1953
- switch (n.type) {
1954
- case "ObjectPattern":
1955
- case "ArrayPattern":
1956
- case "Identifier":
1957
- case "AssignmentPattern":
1958
- case "RestElement":
1959
- return this.visitPattern(n);
1960
- default:
1961
- return this.visitExpression(n);
1962
- }
1963
- }
1964
- visitYieldExpression(n) {
1965
- n.argument = this.visitOptionalExpression(n.argument);
1966
- return n;
1967
- }
1968
- visitUpdateExpression(n) {
1969
- n.argument = this.visitExpression(n.argument);
1970
- return n;
1971
- }
1972
- visitUnaryExpression(n) {
1973
- n.argument = this.visitExpression(n.argument);
1974
- return n;
1975
- }
1976
- visitTsTypeAssertion(n) {
1977
- n.expression = this.visitExpression(n.expression);
1978
- n.typeAnnotation = this.visitTsType(n.typeAnnotation);
1979
- return n;
1980
- }
1981
- visitTsConstAssertion(n) {
1982
- n.expression = this.visitExpression(n.expression);
1983
- return n;
1984
- }
1985
- visitTsInstantiation(n) {
1986
- n.expression = this.visitExpression(n.expression);
1987
- return n;
1988
- }
1989
- visitTsNonNullExpression(n) {
1990
- n.expression = this.visitExpression(n.expression);
1991
- return n;
1992
- }
1993
- visitTsAsExpression(n) {
1994
- n.expression = this.visitExpression(n.expression);
1995
- n.typeAnnotation = this.visitTsType(n.typeAnnotation);
1996
- return n;
1997
- }
1998
- visitTsSatisfiesExpression(n) {
1999
- n.expression = this.visitExpression(n.expression);
2000
- n.typeAnnotation = this.visitTsType(n.typeAnnotation);
2001
- return n;
2002
- }
2003
- visitThisExpression(n) {
2004
- return n;
2005
- }
2006
- visitTemplateLiteral(n) {
2007
- n.expressions = n.expressions.map(this.visitExpression.bind(this));
2008
- return n;
2009
- }
2010
- visitParameters(n) {
2011
- return n.map(this.visitParameter.bind(this));
2012
- }
2013
- visitParameter(n) {
2014
- n.pat = this.visitPattern(n.pat);
2015
- return n;
2016
- }
2017
- visitTaggedTemplateExpression(n) {
2018
- n.tag = this.visitExpression(n.tag);
2019
- const template = this.visitTemplateLiteral(n.template);
2020
- if (template.type === "TemplateLiteral") {
2021
- n.template = template;
2022
- }
2023
- return n;
2024
- }
2025
- visitSequenceExpression(n) {
2026
- n.expressions = n.expressions.map(this.visitExpression.bind(this));
2027
- return n;
2028
- }
2029
- visitRegExpLiteral(n) {
2030
- return n;
2031
- }
2032
- visitParenthesisExpression(n) {
2033
- n.expression = this.visitExpression(n.expression);
2034
- return n;
2035
- }
2036
- visitObjectExpression(n) {
2037
- if (n.properties) {
2038
- n.properties = this.visitObjectProperties(n.properties);
2039
- }
2040
- return n;
2041
- }
2042
- visitObjectProperties(nodes) {
2043
- return nodes.map(this.visitObjectProperty.bind(this));
2044
- }
2045
- visitObjectProperty(n) {
2046
- switch (n.type) {
2047
- case "SpreadElement":
2048
- return this.visitSpreadElement(n);
2049
- default:
2050
- return this.visitProperty(n);
2051
- }
2052
- }
2053
- visitProperty(n) {
2054
- switch (n.type) {
2055
- case "Identifier":
2056
- return this.visitIdentifier(n);
2057
- case "AssignmentProperty":
2058
- return this.visitAssignmentProperty(n);
2059
- case "GetterProperty":
2060
- return this.visitGetterProperty(n);
2061
- case "KeyValueProperty":
2062
- return this.visitKeyValueProperty(n);
2063
- case "MethodProperty":
2064
- return this.visitMethodProperty(n);
2065
- case "SetterProperty":
2066
- return this.visitSetterProperty(n);
2067
- }
2068
- }
2069
- visitSetterProperty(n) {
2070
- n.key = this.visitPropertyName(n.key);
2071
- n.param = this.visitPattern(n.param);
2072
- if (n.body) {
2073
- n.body = this.visitBlockStatement(n.body);
2074
- }
2075
- return n;
2076
- }
2077
- visitMethodProperty(n) {
2078
- n.key = this.visitPropertyName(n.key);
2079
- if (n.body) {
2080
- n.body = this.visitBlockStatement(n.body);
2081
- }
2082
- n.decorators = this.visitDecorators(n.decorators);
2083
- n.params = this.visitParameters(n.params);
2084
- n.returnType = this.visitTsTypeAnnotation(n.returnType);
2085
- n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters);
2086
- return n;
2087
- }
2088
- visitKeyValueProperty(n) {
2089
- n.key = this.visitPropertyName(n.key);
2090
- n.value = this.visitExpression(n.value);
2091
- return n;
2092
- }
2093
- visitGetterProperty(n) {
2094
- n.key = this.visitPropertyName(n.key);
2095
- if (n.body) {
2096
- n.body = this.visitBlockStatement(n.body);
2097
- }
2098
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
2099
- return n;
2100
- }
2101
- visitAssignmentProperty(n) {
2102
- n.key = this.visitIdentifier(n.key);
2103
- n.value = this.visitExpression(n.value);
2104
- return n;
2105
- }
2106
- visitNullLiteral(n) {
2107
- return n;
2108
- }
2109
- visitNewExpression(n) {
2110
- n.callee = this.visitExpression(n.callee);
2111
- if (n.arguments) {
2112
- n.arguments = this.visitArguments(n.arguments);
2113
- }
2114
- n.typeArguments = this.visitTsTypeArguments(n.typeArguments);
2115
- return n;
2116
- }
2117
- visitTsTypeArguments(n) {
2118
- if (n) {
2119
- n.params = this.visitTsTypes(n.params);
2120
- }
2121
- return n;
2122
- }
2123
- visitArguments(nodes) {
2124
- return nodes.map(this.visitArgument.bind(this));
2125
- }
2126
- visitArgument(n) {
2127
- n.expression = this.visitExpression(n.expression);
2128
- return n;
2129
- }
2130
- visitMetaProperty(n) {
2131
- return n;
2132
- }
2133
- visitMemberExpression(n) {
2134
- n.object = this.visitExpression(n.object);
2135
- switch (n.property.type) {
2136
- case "Computed": {
2137
- n.property = this.visitComputedPropertyKey(n.property);
2138
- return n;
2139
- }
2140
- case "Identifier": {
2141
- n.property = this.visitIdentifier(n.property);
2142
- return n;
2143
- }
2144
- case "PrivateName": {
2145
- n.property = this.visitPrivateName(n.property);
2146
- return n;
2147
- }
2148
- }
2149
- }
2150
- visitSuperPropExpression(n) {
2151
- switch (n.property.type) {
2152
- case "Computed": {
2153
- n.property = this.visitComputedPropertyKey(n.property);
2154
- return n;
2155
- }
2156
- case "Identifier": {
2157
- n.property = this.visitIdentifier(n.property);
2158
- return n;
2159
- }
2160
- }
2161
- }
2162
- visitCallee(n) {
2163
- if (n.type === "Super" || n.type === "Import") {
2164
- return n;
2165
- }
2166
- return this.visitExpression(n);
2167
- }
2168
- visitJSXText(n) {
2169
- return n;
2170
- }
2171
- visitJSXNamespacedName(n) {
2172
- n.namespace = this.visitIdentifierReference(n.namespace);
2173
- n.name = this.visitIdentifierReference(n.name);
2174
- return n;
2175
- }
2176
- visitJSXMemberExpression(n) {
2177
- n.object = this.visitJSXObject(n.object);
2178
- n.property = this.visitIdentifierReference(n.property);
2179
- return n;
2180
- }
2181
- visitJSXObject(n) {
2182
- switch (n.type) {
2183
- case "Identifier":
2184
- return this.visitIdentifierReference(n);
2185
- case "JSXMemberExpression":
2186
- return this.visitJSXMemberExpression(n);
2187
- }
2188
- }
2189
- visitJSXFragment(n) {
2190
- n.opening = this.visitJSXOpeningFragment(n.opening);
2191
- if (n.children) {
2192
- n.children = this.visitJSXElementChildren(n.children);
2193
- }
2194
- n.closing = this.visitJSXClosingFragment(n.closing);
2195
- return n;
2196
- }
2197
- visitJSXClosingFragment(n) {
2198
- return n;
2199
- }
2200
- visitJSXElementChildren(nodes) {
2201
- return nodes.map(this.visitJSXElementChild.bind(this));
2202
- }
2203
- visitJSXElementChild(n) {
2204
- switch (n.type) {
2205
- case "JSXElement":
2206
- return this.visitJSXElement(n);
2207
- case "JSXExpressionContainer":
2208
- return this.visitJSXExpressionContainer(n);
2209
- case "JSXFragment":
2210
- return this.visitJSXFragment(n);
2211
- case "JSXSpreadChild":
2212
- return this.visitJSXSpreadChild(n);
2213
- case "JSXText":
2214
- return this.visitJSXText(n);
2215
- }
2216
- }
2217
- visitJSXExpressionContainer(n) {
2218
- n.expression = this.visitExpression(n.expression);
2219
- return n;
2220
- }
2221
- visitJSXSpreadChild(n) {
2222
- n.expression = this.visitExpression(n.expression);
2223
- return n;
2224
- }
2225
- visitJSXOpeningFragment(n) {
2226
- return n;
2227
- }
2228
- visitJSXEmptyExpression(n) {
2229
- return n;
2230
- }
2231
- visitJSXElement(n) {
2232
- n.opening = this.visitJSXOpeningElement(n.opening);
2233
- n.children = this.visitJSXElementChildren(n.children);
2234
- n.closing = this.visitJSXClosingElement(n.closing);
2235
- return n;
2236
- }
2237
- visitJSXClosingElement(n) {
2238
- if (n) {
2239
- n.name = this.visitJSXElementName(n.name);
2240
- }
2241
- return n;
2242
- }
2243
- visitJSXElementName(n) {
2244
- switch (n.type) {
2245
- case "Identifier":
2246
- return this.visitIdentifierReference(n);
2247
- case "JSXMemberExpression":
2248
- return this.visitJSXMemberExpression(n);
2249
- case "JSXNamespacedName":
2250
- return this.visitJSXNamespacedName(n);
2251
- }
2252
- }
2253
- visitJSXOpeningElement(n) {
2254
- n.name = this.visitJSXElementName(n.name);
2255
- n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments);
2256
- n.attributes = this.visitJSXAttributeOrSpreads(n.attributes);
2257
- return n;
2258
- }
2259
- visitJSXAttributes(attrs) {
2260
- if (attrs) return attrs.map(this.visitJSXAttributeOrSpread.bind(this));
2261
- }
2262
- visitJSXAttributeOrSpread(n) {
2263
- switch (n.type) {
2264
- case "JSXAttribute":
2265
- return this.visitJSXAttribute(n);
2266
- case "SpreadElement":
2267
- return this.visitSpreadElement(n);
2268
- }
2269
- }
2270
- visitJSXAttributeOrSpreads(nodes) {
2271
- return nodes.map(this.visitJSXAttributeOrSpread.bind(this));
2272
- }
2273
- visitJSXAttribute(n) {
2274
- n.name = this.visitJSXAttributeName(n.name);
2275
- n.value = this.visitJSXAttributeValue(n.value);
2276
- return n;
2277
- }
2278
- visitJSXAttributeValue(n) {
2279
- if (!n) return n;
2280
- switch (n.type) {
2281
- case "BooleanLiteral":
2282
- return this.visitBooleanLiteral(n);
2283
- case "NullLiteral":
2284
- return this.visitNullLiteral(n);
2285
- case "NumericLiteral":
2286
- return this.visitNumericLiteral(n);
2287
- case "JSXText":
2288
- return this.visitJSXText(n);
2289
- case "StringLiteral":
2290
- return this.visitStringLiteral(n);
2291
- case "JSXElement":
2292
- return this.visitJSXElement(n);
2293
- case "JSXExpressionContainer":
2294
- return this.visitJSXExpressionContainer(n);
2295
- case "JSXFragment":
2296
- return this.visitJSXFragment(n);
2297
- }
2298
- return n;
2299
- }
2300
- visitJSXAttributeName(n) {
2301
- switch (n.type) {
2302
- case "Identifier":
2303
- return this.visitIdentifierReference(n);
2304
- case "JSXNamespacedName":
2305
- return this.visitJSXNamespacedName(n);
2306
- }
2307
- }
2308
- visitConditionalExpression(n) {
2309
- n.test = this.visitExpression(n.test);
2310
- n.consequent = this.visitExpression(n.consequent);
2311
- n.alternate = this.visitExpression(n.alternate);
2312
- return n;
2313
- }
2314
- visitCallExpression(n) {
2315
- n.callee = this.visitCallee(n.callee);
2316
- n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments);
2317
- if (n.arguments) {
2318
- n.arguments = this.visitArguments(n.arguments);
2319
- }
2320
- return n;
2321
- }
2322
- visitBooleanLiteral(n) {
2323
- return n;
2324
- }
2325
- visitBinaryExpression(n) {
2326
- n.left = this.visitExpression(n.left);
2327
- n.right = this.visitExpression(n.right);
2328
- return n;
2329
- }
2330
- visitAwaitExpression(n) {
2331
- n.argument = this.visitExpression(n.argument);
2332
- return n;
2333
- }
2334
- visitTsTypeParameterDeclaration(n) {
2335
- if (n) {
2336
- n.parameters = this.visitTsTypeParameters(n.parameters);
2337
- }
2338
- return n;
2339
- }
2340
- visitTsTypeParameters(nodes) {
2341
- return nodes.map(this.visitTsTypeParameter.bind(this));
2342
- }
2343
- visitTsTypeParameter(n) {
2344
- if (n.constraint) {
2345
- n.constraint = this.visitTsType(n.constraint);
2346
- }
2347
- if (n.default) {
2348
- n.default = this.visitTsType(n.default);
2349
- }
2350
- n.name = this.visitIdentifierReference(n.name);
2351
- return n;
2352
- }
2353
- visitTsTypeAnnotation(a) {
2354
- if (a) {
2355
- a.typeAnnotation = this.visitTsType(a.typeAnnotation);
2356
- }
2357
- return a;
2358
- }
2359
- visitTsType(n) {
2360
- return n;
2361
- }
2362
- visitPatterns(nodes) {
2363
- return nodes.map(this.visitPattern.bind(this));
2364
- }
2365
- visitImportDeclaration(n) {
2366
- n.source = this.visitStringLiteral(n.source);
2367
- n.specifiers = this.visitImportSpecifiers(n.specifiers || []);
2368
- return n;
2369
- }
2370
- visitImportSpecifiers(nodes) {
2371
- return nodes.map(this.visitImportSpecifier.bind(this));
2372
- }
2373
- visitImportSpecifier(node) {
2374
- switch (node.type) {
2375
- case "ImportDefaultSpecifier":
2376
- return this.visitImportDefaultSpecifier(node);
2377
- case "ImportNamespaceSpecifier":
2378
- return this.visitImportNamespaceSpecifier(node);
2379
- case "ImportSpecifier":
2380
- return this.visitNamedImportSpecifier(node);
2381
- }
2382
- }
2383
- visitNamedImportSpecifier(node) {
2384
- node.local = this.visitBindingIdentifier(node.local);
2385
- if (node.imported) {
2386
- node.imported = this.visitModuleExportName(node.imported);
2387
- }
2388
- return node;
2389
- }
2390
- visitImportNamespaceSpecifier(node) {
2391
- node.local = this.visitBindingIdentifier(node.local);
2392
- return node;
2393
- }
2394
- visitImportDefaultSpecifier(node) {
2395
- node.local = this.visitBindingIdentifier(node.local);
2396
- return node;
2397
- }
2398
- visitBindingIdentifier(i) {
2399
- if (i.typeAnnotation) {
2400
- i.typeAnnotation = this.visitTsTypeAnnotation(i.typeAnnotation);
2401
- }
2402
- return this.visitIdentifier(i);
2403
- }
2404
- visitIdentifierReference(i) {
2405
- return this.visitIdentifier(i);
2406
- }
2407
- visitLabelIdentifier(label) {
2408
- return this.visitIdentifier(label);
2409
- }
2410
- visitIdentifier(n) {
2411
- return n;
2412
- }
2413
- visitStringLiteral(n) {
2414
- return n;
2415
- }
2416
- visitNumericLiteral(n) {
2417
- return n;
2418
- }
2419
- visitBigIntLiteral(n) {
2420
- return n;
2421
- }
2422
- visitPattern(n) {
2423
- switch (n.type) {
2424
- case "Identifier":
2425
- return this.visitBindingIdentifier(n);
2426
- case "ArrayPattern":
2427
- return this.visitArrayPattern(n);
2428
- case "ObjectPattern":
2429
- return this.visitObjectPattern(n);
2430
- case "AssignmentPattern":
2431
- return this.visitAssignmentPattern(n);
2432
- case "RestElement":
2433
- return this.visitRestElement(n);
2434
- default:
2435
- return this.visitExpression(n);
2436
- }
2437
- }
2438
- visitRestElement(n) {
2439
- n.argument = this.visitPattern(n.argument);
2440
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
2441
- return n;
2442
- }
2443
- visitAssignmentPattern(n) {
2444
- n.left = this.visitPattern(n.left);
2445
- n.right = this.visitExpression(n.right);
2446
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
2447
- return n;
2448
- }
2449
- visitObjectPattern(n) {
2450
- n.properties = this.visitObjectPatternProperties(n.properties || []);
2451
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
2452
- return n;
2453
- }
2454
- visitObjectPatternProperties(nodes) {
2455
- return nodes.map(this.visitObjectPatternProperty.bind(this));
2456
- }
2457
- visitObjectPatternProperty(n) {
2458
- switch (n.type) {
2459
- case "AssignmentPatternProperty":
2460
- return this.visitAssignmentPatternProperty(n);
2461
- case "KeyValuePatternProperty":
2462
- return this.visitKeyValuePatternProperty(n);
2463
- case "RestElement":
2464
- return this.visitRestElement(n);
2465
- }
2466
- }
2467
- visitKeyValuePatternProperty(n) {
2468
- n.key = this.visitPropertyName(n.key);
2469
- n.value = this.visitPattern(n.value);
2470
- return n;
2471
- }
2472
- visitAssignmentPatternProperty(n) {
2473
- n.key = this.visitBindingIdentifier(n.key);
2474
- n.value = this.visitOptionalExpression(n.value);
2475
- return n;
2476
- }
2477
- visitArrayPattern(n) {
2478
- n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation);
2479
- n.elements = this.visitArrayPatternElements(n.elements);
2480
- return n;
2481
- }
2482
- visitArrayPatternElements(nodes) {
2483
- return nodes.map(this.visitArrayPatternElement.bind(this));
2484
- }
2485
- visitArrayPatternElement(n) {
2486
- if (n) {
2487
- n = this.visitPattern(n);
2488
- }
2489
- return n;
2490
- }
2491
- }
2492
-
2493
- class RenameVisitor extends Visitor {
2494
- constructor(replace, suffix) {
2495
- super();
2496
- this.replace = replace;
2497
- this.suffix = suffix;
2498
- }
2499
- visitIdentifier(n) {
2500
- if (this.replace.includes(n.value)) n.value = this.suffix(n.value);
2501
- return n;
2502
- }
2503
- }
2504
-
2505
664
  function isPluginBaseConfig(plugin) {
2506
665
  return typeof plugin.type === "string" && typeof plugin.sourceModule === "string" && typeof plugin.enabled === "boolean" && typeof plugin.targetExport === "string";
2507
666
  }
2508
- function isReactPluginConfig(plugin) {
2509
- if (!isPluginBaseConfig(plugin)) return false;
2510
- return plugin.type === "component";
2511
- }
2512
- function isMethodPluginConfig(plugin) {
2513
- if (!isPluginBaseConfig(plugin)) return false;
2514
- return plugin.type === "function";
2515
- }
2516
- function isReplacePluginConfig(plugin) {
2517
- if (!isPluginBaseConfig(plugin)) return false;
2518
- return plugin.type === "replace";
2519
- }
2520
667
  function isPluginConfig(plugin) {
2521
668
  return isPluginBaseConfig(plugin);
2522
669
  }
2523
- const SOURCE_START = "/** SOURCE_START */";
2524
- const SOURCE_END = "/** SOURCE_END */";
2525
- const originalSuffix = "Original";
2526
- const interceptorSuffix = "Interceptor";
2527
- const disabledSuffix = "Disabled";
2528
- const name = (plugin) => `${plugin.sourceExport}${plugin.sourceModule.split("/")[plugin.sourceModule.split("/").length - 1].replace(/[^a-zA-Z0-9]/g, "")}`;
2529
- const fileName = (plugin) => `${plugin.sourceModule}#${plugin.sourceExport}`;
2530
- const originalName = (n) => `${n}${originalSuffix}`;
2531
- const sourceName = (n) => `${n}`;
2532
- const interceptorName = (n) => `${n}${interceptorSuffix}`;
2533
- const interceptorPropsName = (n) => `${n}Props`;
2534
670
  function moveRelativeDown(plugins) {
2535
671
  return [...plugins].sort((a, b) => {
2536
672
  if (a.sourceModule.startsWith(".") && !b.sourceModule.startsWith(".")) return 1;
@@ -2538,23 +674,33 @@ function moveRelativeDown(plugins) {
2538
674
  return 0;
2539
675
  });
2540
676
  }
677
+ const originalSuffix = "Original";
678
+ const interceptorSuffix = "Interceptor";
679
+ const name = (plugin) => `${plugin.sourceExport}${plugin.sourceModule.split("/")[plugin.sourceModule.split("/").length - 1].replace(/[^a-zA-Z0-9]/g, "")}`;
680
+ const sourceName = (n) => `${n}`;
2541
681
  const generateIdentifyer = (s) => Math.abs(
2542
682
  s.split("").reduce((a, b) => {
2543
- a = (a << 5) - a + b.charCodeAt(0);
2544
- return a & a;
683
+ const value = (a << 5) - a + b.charCodeAt(0) & 4294967295;
684
+ return value < 0 ? value * -2 : value;
2545
685
  }, 0)
2546
686
  ).toString();
2547
- function extractIdentifier(source) {
2548
- if (!source) return null;
2549
- const match = source.match(/\/\* hash:(\d+) \*\//);
2550
- if (!match) return null;
2551
- return match[1];
2552
- }
687
+ const stableStringify = (obj) => {
688
+ if (obj === null || obj === void 0) return String(obj);
689
+ if (typeof obj !== "object") return String(obj);
690
+ if (Array.isArray(obj)) return `[${obj.map(stableStringify).join(",")}]`;
691
+ const keys = Object.keys(obj).sort();
692
+ const pairs = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`);
693
+ return `{${pairs.join(",")}}`;
694
+ };
2553
695
  async function generateInterceptor(interceptor, config, oldInterceptorSource) {
2554
- const identifer = generateIdentifyer(JSON.stringify(interceptor) + JSON.stringify(config));
2555
- const { dependency, targetExports, source } = interceptor;
2556
- if (oldInterceptorSource && identifer === extractIdentifier(oldInterceptorSource))
2557
- return { ...interceptor, template: oldInterceptorSource };
696
+ const hashInput = {
697
+ dependency: interceptor.dependency,
698
+ targetExports: interceptor.targetExports,
699
+ // Only include config properties that affect the output
700
+ debugConfig: config.pluginStatus ? { pluginStatus: config.pluginStatus } : {}
701
+ };
702
+ const identifer = generateIdentifyer(stableStringify(hashInput));
703
+ const { dependency, targetExports } = interceptor;
2558
704
  const pluginConfigs = [...Object.entries(targetExports)].map(([, plugins]) => plugins).flat();
2559
705
  const duplicateImports = /* @__PURE__ */ new Set();
2560
706
  const pluginImports = moveRelativeDown(
@@ -2565,92 +711,103 @@ async function generateInterceptor(interceptor, config, oldInterceptorSource) {
2565
711
  if (duplicateImports.has(str)) return false;
2566
712
  duplicateImports.add(str);
2567
713
  return true;
2568
- }).join("\n");
2569
- const ast = parseSync(source);
2570
- new RenameVisitor(Object.keys(targetExports), (s) => originalName(s)).visitModule(ast);
2571
- const pluginExports = Object.entries(targetExports).map(([base, plugins]) => {
2572
- const duplicateInterceptors = /* @__PURE__ */ new Set();
2573
- let carry = originalName(base);
2574
- let carryProps = [];
2575
- const pluginSee = [];
2576
- pluginSee.push(
2577
- `@see {@link file://${interceptor.sourcePathRelative}} for original source file`
2578
- );
2579
- const pluginStr = plugins.reverse().filter((p) => {
2580
- if (duplicateInterceptors.has(name(p))) return false;
2581
- duplicateInterceptors.add(name(p));
2582
- return true;
2583
- }).map((p) => {
2584
- let result;
2585
- const wrapChain = plugins.reverse().map((pl) => name(pl)).join(" wrapping ");
2586
- if (isReplacePluginConfig(p)) {
2587
- new RenameVisitor(
2588
- [originalName(p.targetExport)],
2589
- (s) => s.replace(originalSuffix, disabledSuffix)
2590
- ).visitModule(ast);
2591
- carryProps.push(`React.ComponentProps<typeof ${sourceName(name(p))}>`);
714
+ }).join("\n ");
715
+ const originalImports = [...Object.entries(targetExports)].filter(([targetExport, plugins]) => {
716
+ return !plugins.some((p) => p.type === "replace");
717
+ }).map(([targetExport]) => {
718
+ interceptor.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
719
+ const importPath = `./${interceptor.target.split("/").pop()}.original`;
720
+ return `import { ${targetExport} as ${targetExport}${originalSuffix} } from '${importPath}'`;
721
+ }).join("\n ");
722
+ let logOnce = "";
723
+ const pluginExports = [...Object.entries(targetExports)].map(([targetExport, plugins]) => {
724
+ if (plugins.some((p) => p.type === "component")) {
725
+ const componentPlugins = plugins.filter((p) => p.type === "component");
726
+ const replacePlugin = plugins.find((p) => p.type === "replace");
727
+ let carry = replacePlugin ? sourceName(name(replacePlugin)) : `${targetExport}${originalSuffix}`;
728
+ const pluginSee = [];
729
+ if (replacePlugin) {
2592
730
  pluginSee.push(
2593
- `@see {${sourceName(name(p))}} for replacement of the original source (original source not used)`
731
+ `@see {${sourceName(name(replacePlugin))}} for source of replaced component`
2594
732
  );
733
+ } else {
734
+ pluginSee.push(`@see {@link file://./${targetExport}.tsx} for original source file`);
2595
735
  }
2596
- if (isReactPluginConfig(p)) {
2597
- const withBraces = config.pluginStatus || process.env.NODE_ENV === "development";
2598
- result = `
2599
- type ${interceptorPropsName(name(p))} = ${carryProps.join(" & ")} & OmitPrev<React.ComponentProps<typeof ${sourceName(name(p))}>, 'Prev'>
2600
-
2601
- const ${interceptorName(name(p))} = (props: ${interceptorPropsName(name(p))}) => ${withBraces ? "{" : "("}
2602
- ${config.pluginStatus ? `logOnce(\`\u{1F50C} Rendering ${base} with plugin(s): ${wrapChain} wrapping <${base}/>\`)` : ""}
736
+ const pluginInterceptors = componentPlugins.reverse().map((plugin) => {
737
+ const pluginName = sourceName(name(plugin));
738
+ const interceptorName2 = `${pluginName}${interceptorSuffix}`;
739
+ const propsName = `${pluginName}Props`;
740
+ pluginSee.push(`@see {${pluginName}} for source of applied plugin`);
741
+ const result = `type ${propsName} = OmitPrev<
742
+ React.ComponentProps<typeof ${pluginName}>,
743
+ 'Prev'
744
+ >
745
+
746
+ const ${interceptorName2} = (
747
+ props: ${propsName},
748
+ ) => (
749
+ <${pluginName}
750
+ {...props}
751
+ Prev={${carry}}
752
+ />
753
+ )`;
754
+ carry = interceptorName2;
755
+ return result;
756
+ }).join("\n\n");
757
+ const seeString = `/**
758
+ * Here you see the 'interceptor' that is applying all the configured plugins.
759
+ *
760
+ * This file is NOT meant to be modified directly and is auto-generated if the plugins or the
761
+ * original source changes.
762
+ *
763
+ ${pluginSee.map((s) => ` * ${s}`).join("\n")}
764
+ */`;
765
+ return `${pluginInterceptors}
2603
766
 
2604
- ${process.env.NODE_ENV === "development" ? `if(!props['data-plugin'])
2605
- logOnce('${fileName(p)} does not spread props to prev: <Prev {...props}/>. This will cause issues if multiple plugins are applied to this component.')` : ""}
2606
- ${withBraces ? "return" : ""} <${sourceName(name(p))} {...props} Prev={${carry}} />
2607
- ${withBraces ? "}" : ")"}`;
2608
- carryProps = [interceptorPropsName(name(p))];
2609
- pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`);
767
+ ${seeString}
768
+ export const ${targetExport} = ${carry}`;
769
+ } else if (plugins.some((p) => p.type === "function")) {
770
+ const functionPlugins = plugins.filter((p) => p.type === "function");
771
+ const replacePlugin = plugins.find((p) => p.type === "replace");
772
+ let carry = replacePlugin ? sourceName(name(replacePlugin)) : `${targetExport}${originalSuffix}`;
773
+ const pluginSee = [];
774
+ if (replacePlugin) {
775
+ pluginSee.push(
776
+ `@see {${sourceName(name(replacePlugin))}} for source of replaced function`
777
+ );
778
+ } else {
779
+ pluginSee.push(`@see {@link file://./${targetExport}.ts} for original source file`);
2610
780
  }
2611
- if (isMethodPluginConfig(p)) {
2612
- result = `const ${interceptorName(name(p))}: typeof ${carry} = (...args) => {
2613
- ${config.pluginStatus ? `logOnce(\`\u{1F50C} Calling ${base} with plugin(s): ${wrapChain} wrapping ${base}()\`)` : ""}
2614
- return ${sourceName(name(p))}(${carry}, ...args)
2615
- }`;
2616
- pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`);
781
+ const pluginInterceptors = functionPlugins.reverse().map((plugin) => {
782
+ const pluginName = sourceName(name(plugin));
783
+ const interceptorName2 = `${pluginName}${interceptorSuffix}`;
784
+ pluginSee.push(`@see {${pluginName}} for source of applied plugin`);
785
+ const result = `const ${interceptorName2}: typeof ${carry} = (...args) => {
786
+ return ${pluginName}(${carry}, ...args)
787
+ }`;
788
+ carry = interceptorName2;
789
+ return result;
790
+ }).join("\n");
791
+ const seeString = `/**
792
+ * Here you see the 'interceptor' that is applying all the configured plugins.
793
+ *
794
+ * This file is NOT meant to be modified directly and is auto-generated if the plugins or the
795
+ * original source changes.
796
+ *
797
+ ${pluginSee.map((s) => ` * ${s}`).join("\n")}
798
+ */`;
799
+ return `${pluginInterceptors}
800
+
801
+ ${seeString}
802
+ export const ${targetExport} = ${carry}`;
803
+ } else if (plugins.some((p) => p.type === "replace")) {
804
+ const replacePlugin = plugins.find((p) => p.type === "replace");
805
+ if (replacePlugin) {
806
+ return `export { ${replacePlugin.sourceExport} as ${targetExport} } from '${replacePlugin.sourceModule}'`;
2617
807
  }
2618
- carry = p.type === "replace" ? sourceName(name(p)) : interceptorName(name(p));
2619
- return result;
2620
- }).filter((v) => !!v).join("\n");
2621
- const isComponent = plugins.every((p) => isReactPluginConfig(p));
2622
- if (isComponent && plugins.some((p) => isMethodPluginConfig(p))) {
2623
- throw new Error(`Cannot mix React and Method plugins for ${base} in ${dependency}.`);
2624
808
  }
2625
- const seeString = `
2626
- /**
2627
- * Here you see the 'interceptor' that is applying all the configured plugins.
2628
- *
2629
- * This file is NOT meant to be modified directly and is auto-generated if the plugins or the original source changes.
2630
- *
2631
- ${pluginSee.map((s) => `* ${s}`).join("\n")}
2632
- */`;
2633
- if (process.env.NODE_ENV === "development" && isComponent) {
2634
- return `${pluginStr}
2635
- ${seeString}
2636
- export const ${base}: typeof ${carry} = (props) => {
2637
- return <${carry} {...props} data-plugin />
2638
- }`;
2639
- }
2640
- return `
2641
- ${pluginStr}
2642
- ${seeString}
2643
- export const ${base} = ${carry}
2644
- `;
2645
- }).join("\n");
2646
- const logOnce = config.pluginStatus || process.env.NODE_ENV === "development" ? `
2647
- const logged: Set<string> = new Set();
2648
- const logOnce = (log: string, ...additional: unknown[]) => {
2649
- if (logged.has(log)) return
2650
- logged.add(log)
2651
- console.warn(log, ...additional)
2652
- }
2653
- ` : "";
809
+ return "";
810
+ }).filter(Boolean).join("\n\n ");
2654
811
  const template = `/* hash:${identifer} */
2655
812
  /* eslint-disable */
2656
813
  /* This file is automatically generated for ${dependency} */
@@ -2658,20 +815,18 @@ async function generateInterceptor(interceptor, config, oldInterceptorSource) {
2658
815
 
2659
816
  ${pluginImports}
2660
817
 
2661
- /** @see {@link file://${interceptor.sourcePathRelative}} for source of original */
2662
- ${SOURCE_START}
2663
- ${printSync(ast).code}
2664
- ${SOURCE_END}
818
+ ${originalImports}
819
+
820
+ // Re-export everything from the original file except the intercepted exports
821
+ export * from './${interceptor.target.split("/").pop()}.original'
822
+
2665
823
  ${logOnce}${pluginExports}
2666
- `;
2667
- let templateFormatted;
2668
- try {
2669
- templateFormatted = await prettier.format(template, { ...prettierConf, parser: "typescript" });
2670
- } catch (e) {
2671
- console.log("Error formatting interceptor: ", e, "using raw template.");
2672
- templateFormatted = template;
2673
- }
2674
- return { ...interceptor, template: templateFormatted };
824
+ `;
825
+ const formatted = await prettier.format(template, {
826
+ ...prettierConf,
827
+ parser: "typescript"
828
+ });
829
+ return { ...interceptor, template: formatted };
2675
830
  }
2676
831
 
2677
832
  async function generateInterceptors(plugins, resolve, config, force) {
@@ -2689,7 +844,7 @@ async function generateInterceptors(plugins, resolve, config, force) {
2689
844
  if (pluginPath.startsWith(".")) {
2690
845
  const resolvedPlugin = resolve(pluginPath);
2691
846
  if (resolvedPlugin) {
2692
- pluginPath = path.relative(
847
+ pluginPath = path$1.relative(
2693
848
  resolved.fromRoot.split("/").slice(0, -1).join("/"),
2694
849
  resolvedPlugin.fromRoot
2695
850
  );
@@ -2698,7 +853,7 @@ async function generateInterceptors(plugins, resolve, config, force) {
2698
853
  if (!acc[resolved.fromRoot]) {
2699
854
  acc[resolved.fromRoot] = {
2700
855
  ...resolved,
2701
- target: `${resolved.fromRoot}.interceptor`,
856
+ target: resolved.fromRoot,
2702
857
  targetExports: {}
2703
858
  };
2704
859
  }
@@ -2712,346 +867,199 @@ async function generateInterceptors(plugins, resolve, config, force) {
2712
867
  return Object.fromEntries(
2713
868
  await Promise.all(
2714
869
  Object.entries(byTargetModuleAndExport).map(async ([target, interceptor]) => {
2715
- const file = `${interceptor.fromRoot}.interceptor.tsx`;
2716
- const originalSource = !force && await fs$1.access(file, fs$1.constants.F_OK).then(() => true).catch(() => false) ? (await fs$1.readFile(file)).toString() : void 0;
870
+ `${interceptor.fromRoot}.tsx`;
871
+ `${interceptor.fromRoot}.ts`;
872
+ const extension = interceptor.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
873
+ `${interceptor.fromRoot}${extension}`;
2717
874
  return [
2718
875
  target,
2719
- await generateInterceptor(interceptor, config ?? {}, originalSource)
876
+ await generateInterceptor(interceptor, config ?? {})
2720
877
  ];
2721
878
  })
2722
879
  )
2723
880
  );
2724
881
  }
2725
882
 
2726
- function checkFileExists(file) {
2727
- return fs$1.access(file, fs$1.constants.F_OK).then(() => true).catch(() => false);
2728
- }
2729
- async function writeInterceptors(interceptors, cwd = process.cwd()) {
2730
- const dependencies = resolveDependenciesSync(cwd);
2731
- const existing = /* @__PURE__ */ new Set();
2732
- dependencies.forEach((dependency) => {
2733
- const files = sync(
2734
- [`${dependency}/**/*.interceptor.tsx`, `${dependency}/**/*.interceptor.ts`],
2735
- { cwd }
2736
- );
2737
- files.forEach((file) => existing.add(file));
2738
- });
2739
- const written = Object.entries(interceptors).map(async ([, plugin]) => {
2740
- const extension = plugin.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
2741
- const relativeFile = `${plugin.fromRoot}.interceptor${extension}`;
2742
- if (existing.has(relativeFile)) {
2743
- existing.delete(relativeFile);
883
+ const packageRoots = (packagePaths) => {
884
+ const pathMap = {};
885
+ packagePaths.forEach((singlePath) => {
886
+ const parts = singlePath.split("/");
887
+ for (let i = 1; i < parts.length; i++) {
888
+ const subPath = parts.slice(0, i + 1).join("/");
889
+ if (pathMap[subPath]) {
890
+ pathMap[subPath].count += 1;
891
+ } else {
892
+ pathMap[subPath] = { path: subPath, count: 1 };
893
+ }
2744
894
  }
2745
- if (existing.has(`./${relativeFile}`)) {
2746
- existing.delete(`./${relativeFile}`);
895
+ });
896
+ const roots = [];
897
+ Object.values(pathMap).forEach(({ path, count }) => {
898
+ if (count > 1) {
899
+ roots.push(path);
2747
900
  }
2748
- const fileToWrite = path$1.join(cwd, relativeFile);
2749
- const isSame = await checkFileExists(fileToWrite) && (await fs$1.readFile(fileToWrite, "utf8")).toString() === plugin.template;
2750
- if (!isSame) await fs$1.writeFile(fileToWrite, plugin.template);
2751
901
  });
2752
- const cleaned = [...existing].map(
2753
- async (file) => await checkFileExists(file) && await fs$1.unlink(file)
902
+ return roots.filter(
903
+ (root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1
2754
904
  );
2755
- await Promise.all(written);
2756
- await Promise.all(cleaned);
2757
- }
905
+ };
2758
906
 
2759
- let interceptors;
2760
- let interceptorByDepependency;
2761
- let generating = false;
2762
- class InterceptorPlugin {
2763
- constructor(config, regenerate = false) {
2764
- this.config = config;
2765
- this.regenerate = regenerate;
2766
- this.resolveDependency = resolveDependency();
2767
- if (regenerate) this.#generateInterceptors();
2768
- }
2769
- resolveDependency;
2770
- #generateInterceptors = async () => {
2771
- if (generating) return {};
2772
- generating = true;
2773
- const [plugins] = findPlugins(this.config);
2774
- const generatedInterceptors = await generateInterceptors(
2775
- plugins,
2776
- this.resolveDependency,
2777
- this.config.debug
2778
- );
2779
- await writeInterceptors(generatedInterceptors);
2780
- interceptors = generatedInterceptors;
2781
- interceptorByDepependency = Object.fromEntries(
2782
- Object.values(interceptors).map((i) => [i.dependency, i])
2783
- );
2784
- generating = false;
2785
- return generatedInterceptors;
2786
- };
2787
- /** @public */
2788
- apply(compiler) {
2789
- const logger = compiler.getInfrastructureLogger("InterceptorPlugin");
2790
- if (this.regenerate) {
2791
- compiler.hooks.afterCompile.tap("InterceptorPlugin", (compilation) => {
2792
- const [plugins, errors] = findPlugins(this.config);
2793
- plugins.forEach((p) => {
2794
- const source = this.resolveDependency(p.sourceModule);
2795
- if (source) {
2796
- const absoluteFilePath = `${path$1.join(process.cwd(), source.fromRoot)}.tsx`;
2797
- compilation.fileDependencies.add(absoluteFilePath);
2798
- }
2799
- });
2800
- this.#generateInterceptors().then((i) => {
2801
- Object.entries(i).forEach(([, { sourcePath }]) => {
2802
- const absoluteFilePath = path$1.join(process.cwd(), sourcePath);
2803
- compilation.fileDependencies.add(absoluteFilePath);
2804
- });
2805
- });
2806
- });
2807
- }
2808
- compiler.hooks.normalModuleFactory.tap("InterceptorPlugin", (nmf) => {
2809
- nmf.hooks.beforeResolve.tap("InterceptorPlugin", (resource) => {
2810
- const issuer = resource.contextInfo.issuer ?? "";
2811
- const requestPath = path$1.relative(
2812
- process.cwd(),
2813
- path$1.resolve(resource.context, resource.request)
907
+ const resolveDependency = (cwd = process.cwd()) => {
908
+ const dependencies = resolveDependenciesSync(cwd);
909
+ function resolve(dependency, options = {}) {
910
+ const { includeSources = false } = options;
911
+ let dependencyPaths = {
912
+ root: ".",
913
+ source: "",
914
+ sourcePath: "",
915
+ sourcePathRelative: "",
916
+ dependency,
917
+ fromRoot: dependency,
918
+ fromModule: dependency,
919
+ denormalized: dependency
920
+ };
921
+ dependencies.forEach((root, depCandidate) => {
922
+ if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) {
923
+ const relative = dependency.replace(depCandidate, "");
924
+ const rootCandidate = dependency.replace(depCandidate, root);
925
+ let source = "";
926
+ let sourcePath = "";
927
+ const fromRoot = [
928
+ `${rootCandidate}`,
929
+ `${rootCandidate}/index`,
930
+ `${rootCandidate}/src/index`
931
+ ].find(
932
+ (location) => ["ts", "tsx"].find((extension) => {
933
+ const candidatePath = `${location}.${extension}`;
934
+ const exists = fs$1.existsSync(candidatePath);
935
+ if (includeSources && exists) {
936
+ source = fs$1.readFileSync(candidatePath, "utf-8");
937
+ sourcePath = candidatePath;
938
+ }
939
+ return exists;
940
+ })
2814
941
  );
2815
- if (!interceptors || !interceptorByDepependency) {
2816
- return;
2817
- }
2818
- const split = requestPath.split("/");
2819
- const targets = [
2820
- `${split[split.length - 1]}.interceptor.tsx`,
2821
- `${split[split.length - 1]}.interceptor.ts`
2822
- ];
2823
- if (targets.some((target) => issuer.endsWith(target)) && interceptors[requestPath]) {
2824
- logger.log(`Interceptor ${issuer} is requesting the original ${requestPath}`);
942
+ if (!fromRoot) {
2825
943
  return;
2826
944
  }
2827
- const interceptorForRequest = interceptorByDepependency[resource.request];
2828
- if (interceptorForRequest) {
2829
- const extension = interceptorForRequest.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
2830
- resource.request = `${interceptorForRequest.denormalized}.interceptor${extension}`;
2831
- logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`, resource.request);
2832
- }
2833
- const interceptorForPath = interceptors[requestPath];
2834
- if (interceptorForPath) {
2835
- const extension = interceptorForPath.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
2836
- resource.request = `${resource.request}.interceptor${extension}`;
2837
- logger.log(`Intercepting fromRoot... ${interceptorForPath.dependency}`, resource.request);
2838
- }
2839
- });
2840
- });
2841
- }
2842
- }
2843
-
2844
- let graphcommerceConfig;
2845
- function domains(config) {
2846
- return Object.values(
2847
- config.storefront.reduce(
2848
- (acc, loc) => {
2849
- if (!loc.domain) return acc;
2850
- acc[loc.domain] = {
2851
- defaultLocale: loc.locale,
2852
- locales: [...acc[loc.domain]?.locales ?? [], loc.locale],
2853
- domain: loc.domain,
2854
- http: process.env.NODE_ENV === "development" || void 0
2855
- };
2856
- return acc;
2857
- },
2858
- {}
2859
- )
2860
- );
2861
- }
2862
- function withGraphCommerce(nextConfig, cwd = process.cwd()) {
2863
- graphcommerceConfig ??= loadConfig(cwd);
2864
- const importMetaPaths = configToImportMeta(graphcommerceConfig);
2865
- const { storefront } = graphcommerceConfig;
2866
- const transpilePackages = [
2867
- ...[...resolveDependenciesSync().keys()].slice(1),
2868
- ...nextConfig.transpilePackages ?? []
2869
- ];
2870
- return {
2871
- ...nextConfig,
2872
- bundlePagesRouterDependencies: true,
2873
- experimental: {
2874
- ...nextConfig.experimental,
2875
- scrollRestoration: true,
2876
- swcPlugins: [...nextConfig.experimental?.swcPlugins ?? [], ["@lingui/swc-plugin", {}]]
2877
- },
2878
- i18n: {
2879
- ...nextConfig.i18n,
2880
- defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale,
2881
- locales: storefront.map((locale) => locale.locale),
2882
- domains: [...domains(graphcommerceConfig), ...nextConfig.i18n?.domains ?? []]
2883
- },
2884
- images: {
2885
- ...nextConfig.images,
2886
- remotePatterns: [
2887
- "magentoEndpoint" in graphcommerceConfig ? {
2888
- hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname
2889
- } : void 0,
2890
- { hostname: "**.graphassets.com" },
2891
- { hostname: "*.graphcommerce.org" },
2892
- ...nextConfig.images?.remotePatterns ?? []
2893
- ].filter((v) => !!v)
2894
- },
2895
- rewrites: async () => {
2896
- let rewrites = await nextConfig.rewrites?.() ?? [];
2897
- if (Array.isArray(rewrites)) {
2898
- rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] };
2899
- }
2900
- if ("productRoute" in graphcommerceConfig && typeof graphcommerceConfig.productRoute === "string" && graphcommerceConfig.productRoute !== "/p/") {
2901
- rewrites.beforeFiles.push({
2902
- source: `${graphcommerceConfig.productRoute ?? "/p/"}:path*`,
2903
- destination: "/p/:path*"
2904
- });
2905
- }
2906
- return rewrites;
2907
- },
2908
- transpilePackages,
2909
- webpack: (config, options) => {
2910
- if (!config.module) config.module = { rules: [] };
2911
- config.module = {
2912
- ...config.module,
2913
- rules: [
2914
- ...config.module.rules ?? [],
2915
- // Allow importing yml/yaml files for graphql-mesh
2916
- { test: /\.ya?ml$/, use: "js-yaml-loader" },
2917
- // @lingui .po file support
2918
- { test: /\.po/, use: "@lingui/loader" }
2919
- ],
2920
- exprContextCritical: false
2921
- };
2922
- if (!config.plugins) config.plugins = [];
2923
- config.plugins.push(new webpack.DefinePlugin(importMetaPaths));
2924
- config.plugins.push(new webpack.DefinePlugin({ "globalThis.__DEV__": options.dev }));
2925
- if (!options.isServer) ;
2926
- config.snapshot = {
2927
- ...config.snapshot ?? {},
2928
- managedPaths: [
2929
- new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join("|")})`)
2930
- ]
2931
- };
2932
- config.watchOptions = {
2933
- ...config.watchOptions ?? {},
2934
- ignored: new RegExp(
2935
- `^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join(
2936
- "|"
2937
- )})))(/((?:[^/]*(?:/|$))*)(?:$|/))?`
2938
- )
2939
- };
2940
- if (!config.resolve) config.resolve = {};
2941
- if (!options.isServer && !options.dev) {
2942
- config.resolve.alias = {
2943
- ...config.resolve.alias,
2944
- "@mui/base": "@mui/base/modern",
2945
- "@mui/lab": "@mui/lab/modern",
2946
- "@mui/material": "@mui/material/modern",
2947
- "@mui/styled-engine": "@mui/styled-engine/modern",
2948
- "@mui/system": "@mui/system/modern"
945
+ const denormalized = fromRoot.replace(root, depCandidate);
946
+ let fromModule = !relative ? "." : `./${relative.split("/")[relative.split("/").length - 1]}`;
947
+ const sourcePathRelative = !sourcePath ? "." : `./${sourcePath.split("/")[sourcePath.split("/").length - 1]}`;
948
+ if (dependency.startsWith("./")) fromModule = `.${relative}`;
949
+ dependencyPaths = {
950
+ root,
951
+ dependency,
952
+ denormalized,
953
+ fromRoot,
954
+ fromModule,
955
+ source,
956
+ sourcePath,
957
+ sourcePathRelative
2949
958
  };
2950
959
  }
2951
- config.plugins.push(new InterceptorPlugin(graphcommerceConfig, !options.isServer));
2952
- return typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, options) : config;
2953
- }
2954
- };
2955
- }
2956
-
2957
- dotenv.config();
2958
- const packages = [...resolveDependenciesSync().values()].filter((p) => p !== ".");
2959
- const resolve = resolveDependency();
2960
- const schemaLocations = packages.map((p) => `${p}/**/Config.graphqls`);
2961
- async function generateConfig() {
2962
- const resolved = resolve("@graphcommerce/next-config");
2963
- if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
2964
- const targetTs = `${resolved.root}/src/generated/config.ts`;
2965
- const targetJs = `${resolved.root}/dist/generated/config.js`;
2966
- await generate({
2967
- silent: true,
2968
- schema: ["graphql/**/Config.graphqls", ...schemaLocations],
2969
- generates: {
2970
- [targetTs]: {
2971
- plugins: ["typescript", "typescript-validation-schema"],
2972
- config: {
2973
- // enumsAsTypes: true,
2974
- schema: "zod",
2975
- notAllowEmptyString: true,
2976
- strictScalars: true,
2977
- enumsAsTypes: true,
2978
- scalarSchemas: {
2979
- Domain: "z.string()",
2980
- DateTime: "z.date()",
2981
- RichTextAST: "z.object.json()"
2982
- }
2983
- }
2984
- },
2985
- ...findParentPath(process.cwd()) && {
2986
- "../../docs/framework/config.md": {
2987
- plugins: ["@graphcommerce/graphql-codegen-markdown-docs"]
2988
- }
2989
- }
2990
- }
2991
- });
2992
- writeFileSync(
2993
- targetTs,
2994
- await prettier.format(readFileSync(targetTs, "utf-8"), {
2995
- ...prettierConf,
2996
- parser: "typescript",
2997
- plugins: prettierConf.plugins?.filter(
2998
- (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
2999
- )
3000
- })
3001
- );
3002
- const result = transformFileSync(targetTs, {
3003
- module: { type: "nodenext" },
3004
- env: { targets: { node: "18" } }
3005
- });
3006
- writeFileSync(targetJs, result.code);
3007
- }
3008
-
3009
- const fmt = (value) => {
3010
- let formattedValue = value;
3011
- if (typeof formattedValue === "boolean") {
3012
- formattedValue = formattedValue ? "1" : "0";
3013
- }
3014
- if (typeof formattedValue === "object") {
3015
- formattedValue = JSON.stringify(formattedValue);
3016
- }
3017
- if (typeof formattedValue === "number") {
3018
- formattedValue = String(formattedValue);
960
+ });
961
+ return dependencyPaths;
3019
962
  }
3020
- return formattedValue;
963
+ return resolve;
3021
964
  };
3022
- function exportConfigToEnv(config) {
3023
- let env = "";
3024
- Object.entries(config).forEach(([key, value]) => {
3025
- if (Array.isArray(value)) {
3026
- value.forEach((val, idx) => {
3027
- env += `${toEnvStr([key, `${idx}`])}='${fmt(val)}'
3028
- `;
3029
- });
3030
- } else {
3031
- env += `${toEnvStr([key])}='${fmt(value)}'
3032
- `;
3033
- }
3034
- });
3035
- return env;
3036
- }
3037
965
 
3038
- dotenv.config();
3039
- async function exportConfig() {
3040
- const conf = loadConfig(process.cwd());
3041
- console.log(exportConfigToEnv(conf));
966
+ async function updatePackageExports(plugins, cwd = process.cwd()) {
967
+ const deps = resolveDependenciesSync();
968
+ const packages = [...deps.values()].filter((p) => p !== ".");
969
+ const roots = packageRoots(packages);
970
+ console.log(`\u{1F50D} Scanning ${roots.length} package roots for plugins...`);
971
+ const pluginsByPackage = /* @__PURE__ */ new Map();
972
+ for (const root of roots) {
973
+ const packageDirs = sync(`${root}/*/package.json`).map((pkgPath) => path$1.dirname(pkgPath));
974
+ for (const packagePath of packageDirs) {
975
+ const pluginFiles = sync(`${packagePath}/plugins/**/*.{ts,tsx}`);
976
+ if (pluginFiles.length > 0) {
977
+ const exportPaths = /* @__PURE__ */ new Set();
978
+ pluginFiles.forEach((file) => {
979
+ const relativePath = path$1.relative(packagePath, file);
980
+ const exportPath = `./${relativePath.replace(/\.(ts|tsx)$/, "")}`;
981
+ exportPaths.add(exportPath);
982
+ });
983
+ if (exportPaths.size > 0) {
984
+ const packageJsonPath = path$1.join(packagePath, "package.json");
985
+ try {
986
+ const packageJsonContent = await fs.readFile(packageJsonPath, "utf8");
987
+ const packageJson = JSON.parse(packageJsonContent);
988
+ const packageName = packageJson.name || path$1.basename(packagePath);
989
+ pluginsByPackage.set(packagePath, exportPaths);
990
+ } catch (error) {
991
+ console.warn(`\u26A0\uFE0F Could not read package.json for ${packagePath}:`, error);
992
+ }
993
+ }
994
+ }
995
+ }
996
+ }
997
+ console.log(`\u{1F4E6} Total packages with plugins: ${pluginsByPackage.size}`);
998
+ const updatePromises = Array.from(pluginsByPackage.entries()).map(
999
+ async ([packagePath, exportPaths]) => {
1000
+ const packageJsonPath = path$1.join(packagePath, "package.json");
1001
+ try {
1002
+ const packageJsonContent = await fs.readFile(packageJsonPath, "utf8");
1003
+ const packageJson = JSON.parse(packageJsonContent);
1004
+ if (!packageJson.exports) {
1005
+ packageJson.exports = { ".": "./index.ts" };
1006
+ }
1007
+ if (typeof packageJson.exports === "object" && !packageJson.exports["."]) {
1008
+ packageJson.exports["."] = "./index.ts";
1009
+ }
1010
+ let hasChanges = false;
1011
+ exportPaths.forEach((exportPath) => {
1012
+ const exportKey = exportPath.startsWith("./") ? exportPath : `./${exportPath}`;
1013
+ const filePath = `${exportPath}.tsx`;
1014
+ const tsFilePath = `${exportPath}.ts`;
1015
+ const targetFile = sync(path$1.join(packagePath, `${exportPath.slice(2)}.{ts,tsx}`))[0];
1016
+ if (targetFile) {
1017
+ const extension = targetFile.endsWith(".tsx") ? ".tsx" : ".ts";
1018
+ const targetPath = `${exportPath}${extension}`;
1019
+ if (packageJson.exports && !packageJson.exports[exportKey]) {
1020
+ packageJson.exports[exportKey] = targetPath;
1021
+ hasChanges = true;
1022
+ }
1023
+ }
1024
+ });
1025
+ if (hasChanges) {
1026
+ const sortedExports = {};
1027
+ if (packageJson.exports["."]) {
1028
+ sortedExports["."] = packageJson.exports["."];
1029
+ }
1030
+ Object.keys(packageJson.exports).filter((key) => key !== ".").sort().forEach((key) => {
1031
+ sortedExports[key] = packageJson.exports[key];
1032
+ });
1033
+ packageJson.exports = sortedExports;
1034
+ const updatedContent = JSON.stringify(packageJson, null, 2) + "\n";
1035
+ await fs.writeFile(packageJsonPath, updatedContent);
1036
+ console.log(`\u2705 Updated exports in ${packageJson.name}`);
1037
+ const newExports = Object.keys(packageJson.exports).filter((key) => key !== ".");
1038
+ if (newExports.length > 0) {
1039
+ console.log(` Added exports: ${newExports.join(", ")}`);
1040
+ }
1041
+ } else {
1042
+ }
1043
+ } catch (error) {
1044
+ console.error(`\u274C Failed to update package.json for ${packagePath}:`, error);
1045
+ }
1046
+ }
1047
+ );
1048
+ await Promise.all(updatePromises);
3042
1049
  }
3043
1050
 
3044
- dotenv.config();
1051
+ dotenv.config({ quiet: true });
3045
1052
  async function codegenInterceptors() {
3046
1053
  const conf = loadConfig(process.cwd());
3047
1054
  const [plugins] = findPlugins(conf);
1055
+ console.info("\u{1F504} Updating package.json exports for plugins...");
1056
+ await updatePackageExports();
3048
1057
  const generatedInterceptors = await generateInterceptors(
3049
1058
  plugins,
3050
1059
  resolveDependency(),
3051
- conf.debug,
3052
- true
3053
- );
1060
+ conf.debug);
3054
1061
  await writeInterceptors(generatedInterceptors);
1062
+ console.info("\u2705 Generated interceptors and moved original files");
3055
1063
  }
3056
1064
 
3057
1065
  const debug = (...args) => {
@@ -3068,7 +1076,7 @@ async function updateGitignore(managedFiles) {
3068
1076
  file.replace(/[*+?^${}()|[\]\\]/g, "\\$&")
3069
1077
  )
3070
1078
  ).sort();
3071
- const gitignorePath = path$1.join(process.cwd(), ".gitignore");
1079
+ const gitignorePath = path.join(process.cwd(), ".gitignore");
3072
1080
  let content;
3073
1081
  try {
3074
1082
  content = await fs$2.readFile(gitignorePath, "utf-8");
@@ -3138,7 +1146,7 @@ async function copyFiles() {
3138
1146
  const readStart = performance.now();
3139
1147
  await Promise.all(
3140
1148
  allFiles.map(async (file) => {
3141
- const filePath = path$1.join(cwd, file);
1149
+ const filePath = path.join(cwd, file);
3142
1150
  try {
3143
1151
  const content = await fs$2.readFile(filePath);
3144
1152
  if (getFileManagement(content) === "graphcommerce") {
@@ -3159,13 +1167,13 @@ async function copyFiles() {
3159
1167
  const collectStart = performance.now();
3160
1168
  await Promise.all(
3161
1169
  packages.map(async (pkg) => {
3162
- const copyDir = path$1.join(pkg, "copy");
1170
+ const copyDir = path.join(pkg, "copy");
3163
1171
  try {
3164
1172
  const files = await fg("**/*", { cwd: copyDir, dot: true, suppressErrors: true });
3165
1173
  if (files.length > 0) {
3166
1174
  debug(`Found files in ${pkg}:`, files);
3167
1175
  for (const file of files) {
3168
- const sourcePath = path$1.join(copyDir, file);
1176
+ const sourcePath = path.join(copyDir, file);
3169
1177
  const existing = fileMap.get(file);
3170
1178
  if (existing) {
3171
1179
  console.error(`Error: File conflict detected for '${file}'
@@ -3191,10 +1199,10 @@ Path: ${copyDir}`
3191
1199
  const copyStart = performance.now();
3192
1200
  await Promise.all(
3193
1201
  Array.from(fileMap.entries()).map(async ([file, { sourcePath }]) => {
3194
- const targetPath = path$1.join(cwd, file);
1202
+ const targetPath = path.join(cwd, file);
3195
1203
  debug(`Processing file: ${file}`);
3196
1204
  try {
3197
- await fs$2.mkdir(path$1.dirname(targetPath), { recursive: true });
1205
+ await fs$2.mkdir(path.dirname(targetPath), { recursive: true });
3198
1206
  const sourceContent = await fs$2.readFile(sourcePath);
3199
1207
  const contentWithComment = Buffer.concat([
3200
1208
  Buffer.from(
@@ -3264,7 +1272,7 @@ Source: ${sourcePath}`);
3264
1272
  if (dirContents.length === 0) {
3265
1273
  await fs$2.rmdir(currentDir);
3266
1274
  debug(`Removed empty directory: ${currentDir}`);
3267
- currentDir = path$1.dirname(currentDir);
1275
+ currentDir = path.dirname(currentDir);
3268
1276
  } else {
3269
1277
  break;
3270
1278
  }
@@ -3279,8 +1287,8 @@ Source: ${sourcePath}`);
3279
1287
  }
3280
1288
  await Promise.all(
3281
1289
  filesToRemove.map(async (file) => {
3282
- const filePath = path$1.join(cwd, file);
3283
- const dirPath = path$1.dirname(filePath);
1290
+ const filePath = path.join(cwd, file);
1291
+ const dirPath = path.dirname(filePath);
3284
1292
  try {
3285
1293
  await fs$2.readdir(dirPath);
3286
1294
  try {
@@ -3313,13 +1321,373 @@ Source: ${sourcePath}`);
3313
1321
  debug(`Total execution time: ${(performance.now() - startTime).toFixed(0)}ms`);
3314
1322
  }
3315
1323
 
3316
- async function codegen() {
3317
- console.info("\u{1F504} Copying files from packages to project...");
3318
- await copyFiles();
3319
- console.info("\u2699\uFE0F Generating GraphCommerce config types...");
3320
- await generateConfig();
3321
- console.info("\u{1F50C} Generating interceptors...");
3322
- await codegenInterceptors();
1324
+ const fmt = (value) => {
1325
+ let formattedValue = value;
1326
+ if (typeof formattedValue === "boolean") {
1327
+ formattedValue = formattedValue ? "1" : "0";
1328
+ }
1329
+ if (typeof formattedValue === "object") {
1330
+ formattedValue = JSON.stringify(formattedValue);
1331
+ }
1332
+ if (typeof formattedValue === "number") {
1333
+ formattedValue = String(formattedValue);
1334
+ }
1335
+ return formattedValue;
1336
+ };
1337
+ function exportConfigToEnv(config) {
1338
+ let env = "";
1339
+ Object.entries(config).forEach(([key, value]) => {
1340
+ if (Array.isArray(value)) {
1341
+ value.forEach((val, idx) => {
1342
+ env += `${toEnvStr([key, `${idx}`])}='${fmt(val)}'
1343
+ `;
1344
+ });
1345
+ } else {
1346
+ env += `${toEnvStr([key])}='${fmt(value)}'
1347
+ `;
1348
+ }
1349
+ });
1350
+ return env;
1351
+ }
1352
+
1353
+ dotenv.config({ quiet: true });
1354
+ async function exportConfig() {
1355
+ const conf = loadConfig(process.cwd());
1356
+ console.log(exportConfigToEnv(conf));
1357
+ }
1358
+
1359
+ const packages = [...resolveDependenciesSync().values()].filter((p) => p !== ".");
1360
+ const resolve$1 = resolveDependency();
1361
+ dotenv.config({ quiet: true });
1362
+ async function generateConfig() {
1363
+ const resolved = resolve$1("@graphcommerce/next-config");
1364
+ if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1365
+ const targetTs = `${resolved.root}/src/generated/config.ts`;
1366
+ const targetJs = `${resolved.root}/dist/generated/config.js`;
1367
+ const schemaLocations = [
1368
+ "graphql/Config.graphqls",
1369
+ ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
1370
+ ];
1371
+ await generate({
1372
+ silent: true,
1373
+ schema: schemaLocations,
1374
+ generates: {
1375
+ [targetTs]: {
1376
+ plugins: ["typescript", "typescript-validation-schema"],
1377
+ config: {
1378
+ // enumsAsTypes: true,
1379
+ schema: "zod",
1380
+ notAllowEmptyString: true,
1381
+ strictScalars: true,
1382
+ enumsAsTypes: true,
1383
+ scalarSchemas: {
1384
+ Domain: "z.string()",
1385
+ DateTime: "z.date()",
1386
+ RichTextAST: "z.object.json()"
1387
+ }
1388
+ }
1389
+ },
1390
+ ...findParentPath(process.cwd()) && {
1391
+ "../../docs/framework/config.md": {
1392
+ plugins: ["@graphcommerce/graphql-codegen-markdown-docs"]
1393
+ }
1394
+ }
1395
+ }
1396
+ });
1397
+ writeFileSync(
1398
+ targetTs,
1399
+ await prettier.format(readFileSync(targetTs, "utf-8"), {
1400
+ ...prettierConf,
1401
+ parser: "typescript",
1402
+ plugins: prettierConf.plugins?.filter(
1403
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1404
+ )
1405
+ })
1406
+ );
1407
+ const result = transformFileSync(targetTs, {
1408
+ module: { type: "nodenext" },
1409
+ env: { targets: { node: "20" } }
1410
+ });
1411
+ writeFileSync(targetJs, result.code);
1412
+ }
1413
+
1414
+ dotenv.config({ quiet: true });
1415
+ const resolve = resolveDependency();
1416
+ function toFileName(key) {
1417
+ return key;
1418
+ }
1419
+ function generateValueLiteral(value) {
1420
+ if (value === null) return "null";
1421
+ if (value === void 0) return "undefined";
1422
+ if (typeof value === "string") return JSON.stringify(value);
1423
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
1424
+ if (Array.isArray(value) || typeof value === "object" && value !== null) {
1425
+ return JSON.stringify(value, null, 2);
1426
+ }
1427
+ return JSON.stringify(value);
1428
+ }
1429
+ function shouldCreateFile(value) {
1430
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1431
+ }
1432
+ function getSectionSchemaKeys(configKey) {
1433
+ try {
1434
+ const mainSchema = GraphCommerceConfigSchema();
1435
+ const sectionSchema = mainSchema.shape[configKey];
1436
+ if (!sectionSchema) return [];
1437
+ let unwrappedSchema = sectionSchema;
1438
+ while (true) {
1439
+ if (!unwrappedSchema || typeof unwrappedSchema !== "object") break;
1440
+ if (!("_def" in unwrappedSchema)) break;
1441
+ const def = unwrappedSchema._def;
1442
+ const typeName = def?.typeName;
1443
+ if (typeName === "ZodLazy" && def.getter) {
1444
+ unwrappedSchema = def.getter();
1445
+ continue;
1446
+ }
1447
+ if (def.innerType) {
1448
+ unwrappedSchema = def.innerType;
1449
+ continue;
1450
+ }
1451
+ if (typeName === "ZodObject" && def.shape) {
1452
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
1453
+ return Object.keys(shape || {});
1454
+ }
1455
+ break;
1456
+ }
1457
+ if (unwrappedSchema && "shape" in unwrappedSchema) {
1458
+ const shape = typeof unwrappedSchema.shape === "function" ? unwrappedSchema.shape() : unwrappedSchema.shape;
1459
+ return Object.keys(shape || {});
1460
+ }
1461
+ } catch {
1462
+ }
1463
+ return [];
1464
+ }
1465
+ async function createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey) {
1466
+ const fileName = `${toFileName(sectionName)}.ts`;
1467
+ const filePath = path.join(targetDir, fileName);
1468
+ const distFileName = `${toFileName(sectionName)}.js`;
1469
+ const distFilePath = path.join(targetDistDir, distFileName);
1470
+ const schemaKeys = getSectionSchemaKeys(configKey);
1471
+ const completeSectionValue = {};
1472
+ for (const key of schemaKeys) {
1473
+ completeSectionValue[key] = sectionValue[key];
1474
+ }
1475
+ const exports$1 = Object.entries(completeSectionValue).map(([key, value]) => {
1476
+ const valueStr = generateValueLiteral(value);
1477
+ const propertyPath = `'${sectionName}.${key}'`;
1478
+ const typeAnnotation = `: Get<GraphCommerceConfig, ${propertyPath}>`;
1479
+ return `export const ${key}${typeAnnotation} = ${valueStr}`;
1480
+ }).join("\n\n");
1481
+ const imports = `import type { GraphCommerceConfig } from '../config'
1482
+ import type { Get } from 'type-fest'` ;
1483
+ const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1484
+ ${imports}
1485
+
1486
+ ${exports$1}
1487
+ `;
1488
+ const formattedContent = await prettier.format(content, {
1489
+ ...prettierConf,
1490
+ parser: "typescript",
1491
+ plugins: prettierConf.plugins?.filter(
1492
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1493
+ )
1494
+ });
1495
+ writeFileSync(filePath, formattedContent);
1496
+ const result = transformFileSync(filePath, {
1497
+ module: { type: "nodenext" },
1498
+ env: { targets: { node: "18" } }
1499
+ });
1500
+ writeFileSync(distFilePath, result.code);
1501
+ }
1502
+ async function generateConfigValues() {
1503
+ const resolved = resolve("@graphcommerce/next-config");
1504
+ if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1505
+ const config = loadConfig(process.cwd());
1506
+ const targetDir = `${resolved.root}/src/generated/configValues`;
1507
+ const targetDistDir = `${resolved.root}/dist/generated/configValues`;
1508
+ if (existsSync(targetDir)) {
1509
+ rmSync(targetDir, { recursive: true, force: true });
1510
+ }
1511
+ if (existsSync(targetDistDir)) {
1512
+ rmSync(targetDistDir, { recursive: true, force: true });
1513
+ }
1514
+ mkdirSync(targetDir, { recursive: true });
1515
+ mkdirSync(targetDistDir, { recursive: true });
1516
+ const schema = GraphCommerceConfigSchema();
1517
+ const schemaKeys = Object.keys(schema.shape);
1518
+ const completeConfig = {};
1519
+ for (const key of schemaKeys) {
1520
+ completeConfig[key] = config[key];
1521
+ }
1522
+ const configEntries = Object.entries(completeConfig);
1523
+ const nestedObjects = [];
1524
+ const rootExports = [];
1525
+ for (const [key, value] of configEntries) {
1526
+ if (shouldCreateFile(value)) {
1527
+ nestedObjects.push([key, value, key]);
1528
+ rootExports.push(`export * as ${key} from './${toFileName(key)}'`);
1529
+ } else {
1530
+ const valueStr = generateValueLiteral(value);
1531
+ const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`;
1532
+ rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`);
1533
+ }
1534
+ }
1535
+ await Promise.all(
1536
+ nestedObjects.map(
1537
+ ([sectionName, sectionValue, configKey]) => createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey)
1538
+ )
1539
+ );
1540
+ const rootImports = `import type { GraphCommerceConfig } from '../config'
1541
+ import type { Get } from 'type-fest'` ;
1542
+ const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1543
+ ${rootImports}
1544
+
1545
+ ${rootExports.join("\n")}
1546
+ `;
1547
+ const formattedIndexContent = await prettier.format(indexContent, {
1548
+ ...prettierConf,
1549
+ parser: "typescript",
1550
+ plugins: prettierConf.plugins?.filter(
1551
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1552
+ )
1553
+ });
1554
+ const indexPath = path.join(targetDir, "index.ts");
1555
+ const distIndexPath = path.join(targetDistDir, "index.js");
1556
+ writeFileSync(indexPath, formattedIndexContent);
1557
+ const indexResult = transformFileSync(indexPath, {
1558
+ module: { type: "nodenext" },
1559
+ env: { targets: { node: "20" } }
1560
+ });
1561
+ writeFileSync(distIndexPath, indexResult.code);
1562
+ console.log(`\u2705 Generated config values in ${targetDir} and ${targetDistDir}`);
1563
+ console.log(`\u{1F4C1} Created ${nestedObjects.length} nested object files + index.ts/.js`);
1564
+ console.log(`\u{1F4DD} Root exports: ${configEntries.length - nestedObjects.length}`);
1565
+ }
1566
+
1567
+ let graphcommerceConfig;
1568
+ function domains(config) {
1569
+ return Object.values(
1570
+ config.storefront.reduce(
1571
+ (acc, loc) => {
1572
+ if (!loc.domain) return acc;
1573
+ acc[loc.domain] = {
1574
+ defaultLocale: loc.locale,
1575
+ locales: [...acc[loc.domain]?.locales ?? [], loc.locale],
1576
+ domain: loc.domain,
1577
+ http: process.env.NODE_ENV === "development" || void 0
1578
+ };
1579
+ return acc;
1580
+ },
1581
+ {}
1582
+ )
1583
+ );
1584
+ }
1585
+ function withGraphCommerce(nextConfig, cwd = process.cwd()) {
1586
+ graphcommerceConfig ??= loadConfig(cwd);
1587
+ const { storefront } = graphcommerceConfig;
1588
+ const transpilePackages = [
1589
+ ...[...resolveDependenciesSync().keys()].slice(1),
1590
+ ...nextConfig.transpilePackages ?? []
1591
+ ];
1592
+ return {
1593
+ ...nextConfig,
1594
+ bundlePagesRouterDependencies: true,
1595
+ serverExternalPackages: [
1596
+ // All @whatwg-node packages to prevent private class field bundling issues
1597
+ // https://github.com/ardatan/whatwg-node/tree/master/packages
1598
+ "@whatwg-node/cookie-store",
1599
+ "@whatwg-node/disposablestack",
1600
+ "@whatwg-node/events",
1601
+ "@whatwg-node/fetch",
1602
+ "@whatwg-node/node-fetch",
1603
+ "@whatwg-node/promise-helpers",
1604
+ "@whatwg-node/server",
1605
+ "@whatwg-node/server-plugin-cookies",
1606
+ ...nextConfig.serverExternalPackages ?? []
1607
+ ],
1608
+ turbopack: {
1609
+ ...nextConfig.turbopack ?? {},
1610
+ rules: {
1611
+ ...nextConfig.turbopack?.rules ?? {},
1612
+ "*.yaml": { loaders: [{ loader: "js-yaml-loader", options: {} }], as: "*.js" },
1613
+ "*.yml": { loaders: [{ loader: "js-yaml-loader", options: {} }], as: "*.js" },
1614
+ "*.po": { loaders: [{ loader: "@lingui/loader", options: {} }], as: "*.js" }
1615
+ }
1616
+ },
1617
+ experimental: {
1618
+ ...nextConfig.experimental,
1619
+ scrollRestoration: true,
1620
+ swcPlugins: [...nextConfig.experimental?.swcPlugins ?? [], ["@lingui/swc-plugin", {}]],
1621
+ optimizePackageImports: [
1622
+ ...transpilePackages,
1623
+ ...nextConfig.experimental?.optimizePackageImports ?? []
1624
+ ]
1625
+ },
1626
+ i18n: {
1627
+ ...nextConfig.i18n,
1628
+ defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale,
1629
+ locales: storefront.map((locale) => locale.locale),
1630
+ domains: [...domains(graphcommerceConfig), ...nextConfig.i18n?.domains ?? []]
1631
+ },
1632
+ images: {
1633
+ ...nextConfig.images,
1634
+ // GraphCommerce uses quality 52 by default for optimized image delivery
1635
+ qualities: [52, 75, ...nextConfig.images?.qualities ?? []],
1636
+ remotePatterns: [
1637
+ "magentoEndpoint" in graphcommerceConfig ? {
1638
+ hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname
1639
+ } : void 0,
1640
+ { hostname: "**.graphassets.com" },
1641
+ { hostname: "*.graphcommerce.org" },
1642
+ ...nextConfig.images?.remotePatterns ?? []
1643
+ ].filter((v) => !!v)
1644
+ },
1645
+ rewrites: async () => {
1646
+ let rewrites = await nextConfig.rewrites?.() ?? [];
1647
+ if (Array.isArray(rewrites)) {
1648
+ rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] };
1649
+ }
1650
+ if ("productRoute" in graphcommerceConfig && typeof graphcommerceConfig.productRoute === "string" && graphcommerceConfig.productRoute !== "/p/") {
1651
+ rewrites.beforeFiles?.push({
1652
+ source: `${graphcommerceConfig.productRoute ?? "/p/"}:path*`,
1653
+ destination: "/p/:path*"
1654
+ });
1655
+ }
1656
+ return rewrites;
1657
+ },
1658
+ transpilePackages,
1659
+ webpack: (config, options) => {
1660
+ if (!config.module) config.module = { rules: [] };
1661
+ config.module = {
1662
+ ...config.module,
1663
+ rules: [
1664
+ ...config.module.rules ?? [],
1665
+ // Allow importing yml/yaml files for graphql-mesh
1666
+ { test: /\.ya?ml$/, use: "js-yaml-loader" },
1667
+ // @lingui .po file support
1668
+ { test: /\.po/, use: "@lingui/loader" }
1669
+ ],
1670
+ exprContextCritical: false
1671
+ };
1672
+ if (!config.plugins) config.plugins = [];
1673
+ config.snapshot = {
1674
+ ...config.snapshot ?? {},
1675
+ managedPaths: [
1676
+ new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join("|")})`)
1677
+ ]
1678
+ };
1679
+ config.watchOptions = {
1680
+ ...config.watchOptions ?? {},
1681
+ ignored: new RegExp(
1682
+ `^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join(
1683
+ "|"
1684
+ )})))(/((?:[^/]*(?:/|$))*)(?:$|/))?`
1685
+ )
1686
+ };
1687
+ if (!config.resolve) config.resolve = {};
1688
+ return typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, options) : config;
1689
+ }
1690
+ };
3323
1691
  }
3324
1692
 
3325
- export { GraphCommerceConfigSchema, codegen, codegenInterceptors, configToImportMeta, copyFiles, exportConfig, findParentPath, g, generateConfig, loadConfig, packageRoots, replaceConfigInString, resolveDependenciesSync, sig, sortDependencies, withGraphCommerce };
1693
+ export { GraphCommerceConfigSchema, PackagesSort, TopologicalSort, cleanupInterceptors, codegen, codegenInterceptors, copyFiles, exportConfig, findParentPath, g, generateConfig, generateConfigValues, loadConfig, packageRoots, resolveDependenciesSync, resolveDependency, sig, sortDependencies, withGraphCommerce };