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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/Config.graphqls +3 -3
  3. package/__tests__/config/utils/__snapshots__/mergeEnvIntoConfig.ts.snap +1 -1
  4. package/__tests__/interceptors/generateInterceptors.ts +133 -150
  5. package/dist/config/loadConfig.js +7 -0
  6. package/dist/generated/config.js +9 -9
  7. package/dist/index.js +807 -2442
  8. package/dist/loadConfig-nJiCKeL1.js +311 -0
  9. package/dist/utils/findParentPath.js +36 -0
  10. package/package.json +41 -20
  11. package/src/commands/cleanupInterceptors.ts +26 -0
  12. package/src/commands/codegen.ts +13 -15
  13. package/src/commands/codegenInterceptors.ts +31 -0
  14. package/src/{config/commands → commands}/exportConfig.ts +3 -3
  15. package/src/{config/commands → commands}/generateConfig.ts +12 -9
  16. package/src/commands/generateConfigValues.ts +265 -0
  17. package/src/commands/index.ts +7 -0
  18. package/src/config/index.ts +0 -9
  19. package/src/config/loadConfig.ts +0 -1
  20. package/src/config/utils/mergeEnvIntoConfig.ts +27 -4
  21. package/src/generated/config.ts +13 -14
  22. package/src/index.ts +7 -39
  23. package/src/interceptors/generateInterceptor.ts +192 -157
  24. package/src/interceptors/generateInterceptors.ts +11 -4
  25. package/src/interceptors/updatePackageExports.ts +147 -0
  26. package/src/interceptors/writeInterceptors.ts +91 -36
  27. package/src/types.ts +26 -0
  28. package/src/utils/{isMonorepo.ts → findParentPath.ts} +2 -2
  29. package/src/utils/index.ts +7 -0
  30. package/src/utils/resolveDependenciesSync.ts +7 -9
  31. package/src/utils/resolveDependency.ts +1 -1
  32. package/src/withGraphCommerce.ts +30 -49
  33. package/tsconfig.json +3 -1
  34. package/__tests__/config/utils/configToImportMeta.ts +0 -121
  35. package/src/interceptors/InterceptorPlugin.ts +0 -141
  36. package/src/interceptors/commands/codegenInterceptors.ts +0 -27
package/dist/index.js CHANGED
@@ -1,56 +1,135 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
1
+ import dotenv from 'dotenv';
2
+ import fs from '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, { writeFileSync, readFileSync, existsSync, rmSync, mkdirSync } from 'fs';
3
11
  import assert from 'assert';
4
12
  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
13
  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';
14
+ import { z } from 'zod';
16
15
  import prettierConf from '@graphcommerce/prettier-config-pwa';
17
16
  import prettier from 'prettier';
18
- import { writeFileSync, readFileSync } from 'fs';
19
- import { generate } from '@graphql-codegen/cli';
20
- import dotenv from 'dotenv';
21
- import fs$2 from 'fs/promises';
22
17
  import fg from 'fast-glob';
18
+ import { generate } from '@graphql-codegen/cli';
19
+ import { GraphCommerceConfigSchema } from './generated/config.js';
20
+ export { GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
21
+ import 'cosmiconfig';
22
+ import '@apollo/client/utilities/index.js';
23
+ import 'chalk';
23
24
 
24
- const debug$1 = process.env.DEBUG === "1";
25
- const log = (message) => debug$1 && console.log(`isMonorepo: ${message}`);
26
- function findPackageJson$1(directory) {
25
+ async function fsExists(file) {
27
26
  try {
28
- const packageJsonPath = path.join(directory, "package.json");
29
- const content = fs.readFileSync(packageJsonPath, "utf8");
30
- return JSON.parse(content);
27
+ await fs.access(file, fs.constants.F_OK);
28
+ return true;
31
29
  } catch {
32
- return null;
30
+ return false;
31
+ }
32
+ }
33
+ async function fsRealpath(file) {
34
+ return await fsExists(file) ? fs.realpath(file) : file;
35
+ }
36
+ async function restoreOriginalFile(fileWithOriginalInTheName) {
37
+ const restoredPath = fileWithOriginalInTheName.replace(/\.original\.(tsx?)$/, ".$1");
38
+ if (await fsExists(fileWithOriginalInTheName)) {
39
+ if (await fsExists(restoredPath)) {
40
+ await fs.unlink(restoredPath);
41
+ }
42
+ await fs.rename(fileWithOriginalInTheName, restoredPath);
43
+ return true;
33
44
  }
45
+ return false;
34
46
  }
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;
47
+ async function findDotOriginalFiles(cwd) {
48
+ let parentPath = findParentPath(process.cwd());
49
+ while (parentPath) {
50
+ const p = findParentPath(parentPath);
51
+ if (p) parentPath = p;
52
+ else break;
53
+ }
54
+ return Promise.all(
55
+ (await glob([`${parentPath}/**/*.original.tsx`, `${parentPath}/**/*.original.ts`], { cwd })).map((file) => fs.realpath(file))
56
+ );
57
+ }
58
+ async function writeInterceptors(interceptors, cwd = process.cwd()) {
59
+ const processedFiles = [];
60
+ const existingDotOriginalFiles = findDotOriginalFiles(cwd);
61
+ const written = Object.entries(interceptors).map(async ([, plugin]) => {
62
+ const extension = plugin.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
63
+ const targetFileName = `${plugin.fromRoot}${extension}`;
64
+ const fileNameDotOriginal = `${plugin.fromRoot}.original${extension}`;
65
+ const targetFilePath = await fsRealpath(path.resolve(cwd, targetFileName));
66
+ const dotOriginalPath = await fsRealpath(path.resolve(cwd, fileNameDotOriginal));
67
+ processedFiles.push(dotOriginalPath);
68
+ const targetSource = await fsExists(targetFilePath) ? await fs.readFile(targetFilePath, "utf8") : null;
69
+ const dotOriginalSource = await fsExists(dotOriginalPath) ? await fs.readFile(dotOriginalPath, "utf8") : null;
70
+ const isPreviouslyApplied = dotOriginalSource !== null && targetSource?.includes("/* hash:");
71
+ let status = "";
72
+ if (isPreviouslyApplied) {
73
+ if (targetSource === plugin.template) {
74
+ status = "\u2705 Unchanged interceptor";
75
+ } else {
76
+ status = "\u{1F504} Updating interceptor";
77
+ await fs.writeFile(targetFilePath, plugin.template);
48
78
  }
79
+ } else {
80
+ status = "\u{1F195} Creating interceptor";
81
+ await fs.rename(targetFilePath, dotOriginalPath);
82
+ await fs.writeFile(targetFilePath, plugin.template);
83
+ }
84
+ console.log(`${status} ${plugin.dependency}`);
85
+ Object.entries(plugin.targetExports).forEach(([target, plugins]) => {
86
+ plugins.forEach((plugin2) => {
87
+ console.log(` \u{1F50C} ${target} <- ${plugin2.sourceModule}`);
88
+ });
89
+ });
90
+ });
91
+ await Promise.all(written);
92
+ const toRestore = (await existingDotOriginalFiles).filter(
93
+ (file) => !processedFiles.includes(file)
94
+ );
95
+ await Promise.all(
96
+ toRestore.map((file) => {
97
+ console.log(`\u21A9 Removing old interceptor ${file}`);
98
+ return restoreOriginalFile(file);
99
+ })
100
+ );
101
+ }
102
+
103
+ dotenv.config({ quiet: true });
104
+ async function cleanupInterceptors(cwd = process.cwd()) {
105
+ console.info("\u{1F9F9} Starting interceptor cleanup...");
106
+ let restoredCount = 0;
107
+ let removedCount = 0;
108
+ const originalFiles = await findDotOriginalFiles(cwd);
109
+ console.info(`\u{1F4C2} Found ${originalFiles.length} .original files to restore`);
110
+ for (const originalFile of originalFiles) {
111
+ try {
112
+ await restoreOriginalFile(originalFile);
113
+ removedCount++;
114
+ } catch (error) {
115
+ console.error(`\u274C Failed to restore ${originalFile}:`, error);
49
116
  }
50
- currentDir = path.dirname(currentDir);
51
117
  }
52
- log("No parent @graphcommerce package found");
53
- return null;
118
+ console.info("\u2705 Interceptor cleanup completed!");
119
+ console.info(`\u{1F4CA} ${restoredCount} files restored from .original`);
120
+ }
121
+
122
+ function run(cmd) {
123
+ return new Promise((resolve, reject) => {
124
+ const child = spawn(cmd, { stdio: "inherit", cwd: process.cwd(), shell: true });
125
+ child.on("close", (code) => code === 0 ? resolve() : reject(new Error(`${cmd} failed`)));
126
+ });
127
+ }
128
+ async function codegen() {
129
+ await run("graphcommerce copy-files");
130
+ await run("graphcommerce codegen-config");
131
+ await run("graphcommerce codegen-config-values");
132
+ await run("graphcommerce codegen-interceptors");
54
133
  }
55
134
 
56
135
  class TopologicalSort {
@@ -169,9 +248,10 @@ function sig() {
169
248
 
170
249
  const resolveCache = /* @__PURE__ */ new Map();
171
250
  function findPackageJson(id, root) {
172
- let dir = id.startsWith("/") ? id : require.resolve(id);
251
+ let dir = id.startsWith("/") ? id : import.meta.resolve(id);
252
+ if (dir.startsWith("file://")) dir = new URL(dir).pathname;
173
253
  let packageJsonLocation = path.join(dir, "package.json");
174
- while (!fs.existsSync(packageJsonLocation)) {
254
+ while (!fs$1.existsSync(packageJsonLocation)) {
175
255
  dir = path.dirname(dir);
176
256
  if (dir === root) throw Error(`Can't find package.json for ${id}`);
177
257
  packageJsonLocation = path.join(dir, "package.json");
@@ -180,14 +260,9 @@ function findPackageJson(id, root) {
180
260
  }
181
261
  function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, additionalDependencies = []) {
182
262
  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
- }
263
+ const fileName = findPackageJson(dependencyPath, root);
189
264
  if (!fileName) throw Error(`Can't find package.json for ${dependencyPath}`);
190
- const packageJsonFile = fs.readFileSync(fileName, "utf-8").toString();
265
+ const packageJsonFile = fs$1.readFileSync(fileName, "utf-8").toString();
191
266
  const packageJson = JSON.parse(packageJsonFile);
192
267
  const e = [atob("QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=")].filter(
193
268
  (n) => !globalThis.gcl ? true : !globalThis.gcl.includes(n)
@@ -256,514 +331,6 @@ function resolveDependenciesSync(root = process.cwd()) {
256
331
  return sorted;
257
332
  }
258
333
 
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
334
  function isIdentifier(node) {
768
335
  return node.type === "Identifier";
769
336
  }
@@ -860,7 +427,7 @@ function extractValue(node, path, optional = false) {
860
427
  }
861
428
  }
862
429
  function extractExports(module) {
863
- const exports = {};
430
+ const exports$1 = {};
864
431
  const errors = [];
865
432
  for (const moduleItem of module.body) {
866
433
  switch (moduleItem.type) {
@@ -874,19 +441,19 @@ function extractExports(module) {
874
441
  switch (moduleItem.declaration.type) {
875
442
  case "ClassDeclaration":
876
443
  case "FunctionDeclaration":
877
- exports[moduleItem.declaration.identifier.value] = RUNTIME_VALUE;
444
+ exports$1[moduleItem.declaration.identifier.value] = RUNTIME_VALUE;
878
445
  break;
879
446
  case "VariableDeclaration":
880
447
  moduleItem.declaration.declarations.forEach((decl) => {
881
448
  if (isIdentifier(decl.id) && decl.init) {
882
- exports[decl.id.value] = extractValue(decl.init, void 0, true);
449
+ exports$1[decl.id.value] = extractValue(decl.init, void 0, true);
883
450
  }
884
451
  });
885
452
  break;
886
453
  }
887
454
  }
888
455
  }
889
- return [exports, errors];
456
+ return [exports$1, errors];
890
457
  }
891
458
 
892
459
  const pluginConfigParsed = z.object({
@@ -900,7 +467,7 @@ function nonNullable(value) {
900
467
  }
901
468
  const isObject = (input) => typeof input === "object" && input !== null && !Array.isArray(input);
902
469
  function parseStructure(ast, gcConfig, sourceModule) {
903
- const [exports, errors] = extractExports(ast);
470
+ const [exports$1, errors] = extractExports(ast);
904
471
  if (errors.length) console.error("Plugin error for", errors.join("\n"));
905
472
  const {
906
473
  config: moduleConfig,
@@ -911,7 +478,7 @@ function parseStructure(ast, gcConfig, sourceModule) {
911
478
  plugin,
912
479
  Plugin,
913
480
  ...rest
914
- } = exports;
481
+ } = exports$1;
915
482
  const exportVals = Object.keys(rest);
916
483
  if (component && !moduleConfig) exportVals.push("Plugin");
917
484
  if (func && !moduleConfig) exportVals.push("plugin");
@@ -945,7 +512,7 @@ function parseStructure(ast, gcConfig, sourceModule) {
945
512
  }
946
513
  }
947
514
  const val = {
948
- targetExport: exports.component || exports.func || parsed.data.export,
515
+ targetExport: exports$1.component || exports$1.func || parsed.data.export,
949
516
  sourceModule,
950
517
  sourceExport: parsed.data.export,
951
518
  targetModule: parsed.data.module,
@@ -1023,9 +590,6 @@ function parseSync(src) {
1023
590
  comments: true
1024
591
  });
1025
592
  }
1026
- function printSync(m) {
1027
- return printSync$1(m);
1028
- }
1029
593
 
1030
594
  function parseAndFindExport(resolved, findExport, resolve) {
1031
595
  if (!resolved?.source) return void 0;
@@ -1058,16 +622,16 @@ function parseAndFindExport(resolved, findExport, resolve) {
1058
622
  }
1059
623
  }
1060
624
  }
1061
- const exports = ast.body.filter((node) => node.type === "ExportAllDeclaration").sort((a, b) => {
625
+ const exports$1 = ast.body.filter((node) => node.type === "ExportAllDeclaration").sort((a, b) => {
1062
626
  const probablyA = a.source.value.includes(findExport);
1063
627
  const probablyB = b.source.value.includes(findExport);
1064
628
  return probablyA === probablyB ? 0 : probablyA ? -1 : 1;
1065
629
  });
1066
- for (const node of exports) {
630
+ for (const node of exports$1) {
1067
631
  const isRelative = node.source.value.startsWith(".");
1068
632
  if (isRelative) {
1069
633
  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);
634
+ const newPath = path.join(d, node.source.value);
1071
635
  const resolveResult = resolve(newPath, { includeSources: true });
1072
636
  if (!resolveResult) continue;
1073
637
  const newResolved = parseAndFindExport(resolveResult, findExport, resolve);
@@ -1094,1443 +658,12 @@ function findOriginalSource(plug, resolved, resolve) {
1094
658
  return { resolved: newResolved, error: void 0 };
1095
659
  }
1096
660
 
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
661
  function isPluginBaseConfig(plugin) {
2506
662
  return typeof plugin.type === "string" && typeof plugin.sourceModule === "string" && typeof plugin.enabled === "boolean" && typeof plugin.targetExport === "string";
2507
663
  }
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
664
  function isPluginConfig(plugin) {
2521
665
  return isPluginBaseConfig(plugin);
2522
666
  }
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
667
  function moveRelativeDown(plugins) {
2535
668
  return [...plugins].sort((a, b) => {
2536
669
  if (a.sourceModule.startsWith(".") && !b.sourceModule.startsWith(".")) return 1;
@@ -2538,23 +671,33 @@ function moveRelativeDown(plugins) {
2538
671
  return 0;
2539
672
  });
2540
673
  }
674
+ const originalSuffix = "Original";
675
+ const interceptorSuffix = "Interceptor";
676
+ const name = (plugin) => `${plugin.sourceExport}${plugin.sourceModule.split("/")[plugin.sourceModule.split("/").length - 1].replace(/[^a-zA-Z0-9]/g, "")}`;
677
+ const sourceName = (n) => `${n}`;
2541
678
  const generateIdentifyer = (s) => Math.abs(
2542
679
  s.split("").reduce((a, b) => {
2543
- a = (a << 5) - a + b.charCodeAt(0);
2544
- return a & a;
680
+ const value = (a << 5) - a + b.charCodeAt(0) & 4294967295;
681
+ return value < 0 ? value * -2 : value;
2545
682
  }, 0)
2546
683
  ).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
- }
684
+ const stableStringify = (obj) => {
685
+ if (obj === null || obj === void 0) return String(obj);
686
+ if (typeof obj !== "object") return String(obj);
687
+ if (Array.isArray(obj)) return `[${obj.map(stableStringify).join(",")}]`;
688
+ const keys = Object.keys(obj).sort();
689
+ const pairs = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`);
690
+ return `{${pairs.join(",")}}`;
691
+ };
2553
692
  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 };
693
+ const hashInput = {
694
+ dependency: interceptor.dependency,
695
+ targetExports: interceptor.targetExports,
696
+ // Only include config properties that affect the output
697
+ debugConfig: config.pluginStatus ? { pluginStatus: config.pluginStatus } : {}
698
+ };
699
+ const identifer = generateIdentifyer(stableStringify(hashInput));
700
+ const { dependency, targetExports } = interceptor;
2558
701
  const pluginConfigs = [...Object.entries(targetExports)].map(([, plugins]) => plugins).flat();
2559
702
  const duplicateImports = /* @__PURE__ */ new Set();
2560
703
  const pluginImports = moveRelativeDown(
@@ -2565,92 +708,103 @@ async function generateInterceptor(interceptor, config, oldInterceptorSource) {
2565
708
  if (duplicateImports.has(str)) return false;
2566
709
  duplicateImports.add(str);
2567
710
  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))}>`);
711
+ }).join("\n ");
712
+ const originalImports = [...Object.entries(targetExports)].filter(([targetExport, plugins]) => {
713
+ return !plugins.some((p) => p.type === "replace");
714
+ }).map(([targetExport]) => {
715
+ interceptor.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
716
+ const importPath = `./${interceptor.target.split("/").pop()}.original`;
717
+ return `import { ${targetExport} as ${targetExport}${originalSuffix} } from '${importPath}'`;
718
+ }).join("\n ");
719
+ let logOnce = "";
720
+ const pluginExports = [...Object.entries(targetExports)].map(([targetExport, plugins]) => {
721
+ if (plugins.some((p) => p.type === "component")) {
722
+ const componentPlugins = plugins.filter((p) => p.type === "component");
723
+ const replacePlugin = plugins.find((p) => p.type === "replace");
724
+ let carry = replacePlugin ? sourceName(name(replacePlugin)) : `${targetExport}${originalSuffix}`;
725
+ const pluginSee = [];
726
+ if (replacePlugin) {
2592
727
  pluginSee.push(
2593
- `@see {${sourceName(name(p))}} for replacement of the original source (original source not used)`
728
+ `@see {${sourceName(name(replacePlugin))}} for source of replaced component`
2594
729
  );
730
+ } else {
731
+ pluginSee.push(`@see {@link file://./${targetExport}.tsx} for original source file`);
2595
732
  }
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}/>\`)` : ""}
733
+ const pluginInterceptors = componentPlugins.reverse().map((plugin) => {
734
+ const pluginName = sourceName(name(plugin));
735
+ const interceptorName2 = `${pluginName}${interceptorSuffix}`;
736
+ const propsName = `${pluginName}Props`;
737
+ pluginSee.push(`@see {${pluginName}} for source of applied plugin`);
738
+ const result = `type ${propsName} = OmitPrev<
739
+ React.ComponentProps<typeof ${pluginName}>,
740
+ 'Prev'
741
+ >
742
+
743
+ const ${interceptorName2} = (
744
+ props: ${propsName},
745
+ ) => (
746
+ <${pluginName}
747
+ {...props}
748
+ Prev={${carry}}
749
+ />
750
+ )`;
751
+ carry = interceptorName2;
752
+ return result;
753
+ }).join("\n\n");
754
+ const seeString = `/**
755
+ * Here you see the 'interceptor' that is applying all the configured plugins.
756
+ *
757
+ * This file is NOT meant to be modified directly and is auto-generated if the plugins or the
758
+ * original source changes.
759
+ *
760
+ ${pluginSee.map((s) => ` * ${s}`).join("\n")}
761
+ */`;
762
+ return `${pluginInterceptors}
2603
763
 
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`);
764
+ ${seeString}
765
+ export const ${targetExport} = ${carry}`;
766
+ } else if (plugins.some((p) => p.type === "function")) {
767
+ const functionPlugins = plugins.filter((p) => p.type === "function");
768
+ const replacePlugin = plugins.find((p) => p.type === "replace");
769
+ let carry = replacePlugin ? sourceName(name(replacePlugin)) : `${targetExport}${originalSuffix}`;
770
+ const pluginSee = [];
771
+ if (replacePlugin) {
772
+ pluginSee.push(
773
+ `@see {${sourceName(name(replacePlugin))}} for source of replaced function`
774
+ );
775
+ } else {
776
+ pluginSee.push(`@see {@link file://./${targetExport}.ts} for original source file`);
2610
777
  }
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`);
778
+ const pluginInterceptors = functionPlugins.reverse().map((plugin) => {
779
+ const pluginName = sourceName(name(plugin));
780
+ const interceptorName2 = `${pluginName}${interceptorSuffix}`;
781
+ pluginSee.push(`@see {${pluginName}} for source of applied plugin`);
782
+ const result = `const ${interceptorName2}: typeof ${carry} = (...args) => {
783
+ return ${pluginName}(${carry}, ...args)
784
+ }`;
785
+ carry = interceptorName2;
786
+ return result;
787
+ }).join("\n");
788
+ const seeString = `/**
789
+ * Here you see the 'interceptor' that is applying all the configured plugins.
790
+ *
791
+ * This file is NOT meant to be modified directly and is auto-generated if the plugins or the
792
+ * original source changes.
793
+ *
794
+ ${pluginSee.map((s) => ` * ${s}`).join("\n")}
795
+ */`;
796
+ return `${pluginInterceptors}
797
+
798
+ ${seeString}
799
+ export const ${targetExport} = ${carry}`;
800
+ } else if (plugins.some((p) => p.type === "replace")) {
801
+ const replacePlugin = plugins.find((p) => p.type === "replace");
802
+ if (replacePlugin) {
803
+ return `export { ${replacePlugin.sourceExport} as ${targetExport} } from '${replacePlugin.sourceModule}'`;
2617
804
  }
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
805
  }
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
- ` : "";
806
+ return "";
807
+ }).filter(Boolean).join("\n\n ");
2654
808
  const template = `/* hash:${identifer} */
2655
809
  /* eslint-disable */
2656
810
  /* This file is automatically generated for ${dependency} */
@@ -2658,20 +812,18 @@ async function generateInterceptor(interceptor, config, oldInterceptorSource) {
2658
812
 
2659
813
  ${pluginImports}
2660
814
 
2661
- /** @see {@link file://${interceptor.sourcePathRelative}} for source of original */
2662
- ${SOURCE_START}
2663
- ${printSync(ast).code}
2664
- ${SOURCE_END}
815
+ ${originalImports}
816
+
817
+ // Re-export everything from the original file except the intercepted exports
818
+ export * from './${interceptor.target.split("/").pop()}.original'
819
+
2665
820
  ${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 };
821
+ `;
822
+ const formatted = await prettier.format(template, {
823
+ ...prettierConf,
824
+ parser: "typescript"
825
+ });
826
+ return { ...interceptor, template: formatted };
2675
827
  }
2676
828
 
2677
829
  async function generateInterceptors(plugins, resolve, config, force) {
@@ -2698,7 +850,7 @@ async function generateInterceptors(plugins, resolve, config, force) {
2698
850
  if (!acc[resolved.fromRoot]) {
2699
851
  acc[resolved.fromRoot] = {
2700
852
  ...resolved,
2701
- target: `${resolved.fromRoot}.interceptor`,
853
+ target: resolved.fromRoot,
2702
854
  targetExports: {}
2703
855
  };
2704
856
  }
@@ -2712,346 +864,199 @@ async function generateInterceptors(plugins, resolve, config, force) {
2712
864
  return Object.fromEntries(
2713
865
  await Promise.all(
2714
866
  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;
867
+ `${interceptor.fromRoot}.tsx`;
868
+ `${interceptor.fromRoot}.ts`;
869
+ const extension = interceptor.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts";
870
+ `${interceptor.fromRoot}${extension}`;
2717
871
  return [
2718
872
  target,
2719
- await generateInterceptor(interceptor, config ?? {}, originalSource)
873
+ await generateInterceptor(interceptor, config ?? {})
2720
874
  ];
2721
875
  })
2722
876
  )
2723
877
  );
2724
878
  }
2725
879
 
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);
880
+ const packageRoots = (packagePaths) => {
881
+ const pathMap = {};
882
+ packagePaths.forEach((singlePath) => {
883
+ const parts = singlePath.split("/");
884
+ for (let i = 1; i < parts.length; i++) {
885
+ const subPath = parts.slice(0, i + 1).join("/");
886
+ if (pathMap[subPath]) {
887
+ pathMap[subPath].count += 1;
888
+ } else {
889
+ pathMap[subPath] = { path: subPath, count: 1 };
890
+ }
2744
891
  }
2745
- if (existing.has(`./${relativeFile}`)) {
2746
- existing.delete(`./${relativeFile}`);
892
+ });
893
+ const roots = [];
894
+ Object.values(pathMap).forEach(({ path, count }) => {
895
+ if (count > 1) {
896
+ roots.push(path);
2747
897
  }
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
898
  });
2752
- const cleaned = [...existing].map(
2753
- async (file) => await checkFileExists(file) && await fs$1.unlink(file)
899
+ return roots.filter(
900
+ (root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1
2754
901
  );
2755
- await Promise.all(written);
2756
- await Promise.all(cleaned);
2757
- }
902
+ };
2758
903
 
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)
904
+ const resolveDependency = (cwd = process.cwd()) => {
905
+ const dependencies = resolveDependenciesSync(cwd);
906
+ function resolve(dependency, options = {}) {
907
+ const { includeSources = false } = options;
908
+ let dependencyPaths = {
909
+ root: ".",
910
+ source: "",
911
+ sourcePath: "",
912
+ sourcePathRelative: "",
913
+ dependency,
914
+ fromRoot: dependency,
915
+ fromModule: dependency,
916
+ denormalized: dependency
917
+ };
918
+ dependencies.forEach((root, depCandidate) => {
919
+ if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) {
920
+ const relative = dependency.replace(depCandidate, "");
921
+ const rootCandidate = dependency.replace(depCandidate, root);
922
+ let source = "";
923
+ let sourcePath = "";
924
+ const fromRoot = [
925
+ `${rootCandidate}`,
926
+ `${rootCandidate}/index`,
927
+ `${rootCandidate}/src/index`
928
+ ].find(
929
+ (location) => ["ts", "tsx"].find((extension) => {
930
+ const candidatePath = `${location}.${extension}`;
931
+ const exists = fs$1.existsSync(candidatePath);
932
+ if (includeSources && exists) {
933
+ source = fs$1.readFileSync(candidatePath, "utf-8");
934
+ sourcePath = candidatePath;
935
+ }
936
+ return exists;
937
+ })
2814
938
  );
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}`);
939
+ if (!fromRoot) {
2825
940
  return;
2826
941
  }
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"
942
+ const denormalized = fromRoot.replace(root, depCandidate);
943
+ let fromModule = !relative ? "." : `./${relative.split("/")[relative.split("/").length - 1]}`;
944
+ const sourcePathRelative = !sourcePath ? "." : `./${sourcePath.split("/")[sourcePath.split("/").length - 1]}`;
945
+ if (dependency.startsWith("./")) fromModule = `.${relative}`;
946
+ dependencyPaths = {
947
+ root,
948
+ dependency,
949
+ denormalized,
950
+ fromRoot,
951
+ fromModule,
952
+ source,
953
+ sourcePath,
954
+ sourcePathRelative
2949
955
  };
2950
956
  }
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);
957
+ });
958
+ return dependencyPaths;
3019
959
  }
3020
- return formattedValue;
960
+ return resolve;
3021
961
  };
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
962
 
3038
- dotenv.config();
3039
- async function exportConfig() {
3040
- const conf = loadConfig(process.cwd());
3041
- console.log(exportConfigToEnv(conf));
963
+ async function updatePackageExports(plugins, cwd = process.cwd()) {
964
+ const deps = resolveDependenciesSync();
965
+ const packages = [...deps.values()].filter((p) => p !== ".");
966
+ const roots = packageRoots(packages);
967
+ console.log(`\u{1F50D} Scanning ${roots.length} package roots for plugins...`);
968
+ const pluginsByPackage = /* @__PURE__ */ new Map();
969
+ for (const root of roots) {
970
+ const packageDirs = sync(`${root}/*/package.json`).map((pkgPath) => path.dirname(pkgPath));
971
+ for (const packagePath of packageDirs) {
972
+ const pluginFiles = sync(`${packagePath}/plugins/**/*.{ts,tsx}`);
973
+ if (pluginFiles.length > 0) {
974
+ const exportPaths = /* @__PURE__ */ new Set();
975
+ pluginFiles.forEach((file) => {
976
+ const relativePath = path.relative(packagePath, file);
977
+ const exportPath = `./${relativePath.replace(/\.(ts|tsx)$/, "")}`;
978
+ exportPaths.add(exportPath);
979
+ });
980
+ if (exportPaths.size > 0) {
981
+ const packageJsonPath = path.join(packagePath, "package.json");
982
+ try {
983
+ const packageJsonContent = await fs.readFile(packageJsonPath, "utf8");
984
+ const packageJson = JSON.parse(packageJsonContent);
985
+ const packageName = packageJson.name || path.basename(packagePath);
986
+ pluginsByPackage.set(packagePath, exportPaths);
987
+ } catch (error) {
988
+ console.warn(`\u26A0\uFE0F Could not read package.json for ${packagePath}:`, error);
989
+ }
990
+ }
991
+ }
992
+ }
993
+ }
994
+ console.log(`\u{1F4E6} Total packages with plugins: ${pluginsByPackage.size}`);
995
+ const updatePromises = Array.from(pluginsByPackage.entries()).map(
996
+ async ([packagePath, exportPaths]) => {
997
+ const packageJsonPath = path.join(packagePath, "package.json");
998
+ try {
999
+ const packageJsonContent = await fs.readFile(packageJsonPath, "utf8");
1000
+ const packageJson = JSON.parse(packageJsonContent);
1001
+ if (!packageJson.exports) {
1002
+ packageJson.exports = { ".": "./index.ts" };
1003
+ }
1004
+ if (typeof packageJson.exports === "object" && !packageJson.exports["."]) {
1005
+ packageJson.exports["."] = "./index.ts";
1006
+ }
1007
+ let hasChanges = false;
1008
+ exportPaths.forEach((exportPath) => {
1009
+ const exportKey = exportPath.startsWith("./") ? exportPath : `./${exportPath}`;
1010
+ const filePath = `${exportPath}.tsx`;
1011
+ const tsFilePath = `${exportPath}.ts`;
1012
+ const targetFile = sync(path.join(packagePath, `${exportPath.slice(2)}.{ts,tsx}`))[0];
1013
+ if (targetFile) {
1014
+ const extension = targetFile.endsWith(".tsx") ? ".tsx" : ".ts";
1015
+ const targetPath = `${exportPath}${extension}`;
1016
+ if (packageJson.exports && !packageJson.exports[exportKey]) {
1017
+ packageJson.exports[exportKey] = targetPath;
1018
+ hasChanges = true;
1019
+ }
1020
+ }
1021
+ });
1022
+ if (hasChanges) {
1023
+ const sortedExports = {};
1024
+ if (packageJson.exports["."]) {
1025
+ sortedExports["."] = packageJson.exports["."];
1026
+ }
1027
+ Object.keys(packageJson.exports).filter((key) => key !== ".").sort().forEach((key) => {
1028
+ sortedExports[key] = packageJson.exports[key];
1029
+ });
1030
+ packageJson.exports = sortedExports;
1031
+ const updatedContent = JSON.stringify(packageJson, null, 2) + "\n";
1032
+ await fs.writeFile(packageJsonPath, updatedContent);
1033
+ console.log(`\u2705 Updated exports in ${packageJson.name}`);
1034
+ const newExports = Object.keys(packageJson.exports).filter((key) => key !== ".");
1035
+ if (newExports.length > 0) {
1036
+ console.log(` Added exports: ${newExports.join(", ")}`);
1037
+ }
1038
+ } else {
1039
+ }
1040
+ } catch (error) {
1041
+ console.error(`\u274C Failed to update package.json for ${packagePath}:`, error);
1042
+ }
1043
+ }
1044
+ );
1045
+ await Promise.all(updatePromises);
3042
1046
  }
3043
1047
 
3044
- dotenv.config();
1048
+ dotenv.config({ quiet: true });
3045
1049
  async function codegenInterceptors() {
3046
1050
  const conf = loadConfig(process.cwd());
3047
1051
  const [plugins] = findPlugins(conf);
1052
+ console.info("\u{1F504} Updating package.json exports for plugins...");
1053
+ await updatePackageExports();
3048
1054
  const generatedInterceptors = await generateInterceptors(
3049
1055
  plugins,
3050
1056
  resolveDependency(),
3051
- conf.debug,
3052
- true
3053
- );
1057
+ conf.debug);
3054
1058
  await writeInterceptors(generatedInterceptors);
1059
+ console.info("\u2705 Generated interceptors and moved original files");
3055
1060
  }
3056
1061
 
3057
1062
  const debug = (...args) => {
@@ -3068,10 +1073,10 @@ async function updateGitignore(managedFiles) {
3068
1073
  file.replace(/[*+?^${}()|[\]\\]/g, "\\$&")
3069
1074
  )
3070
1075
  ).sort();
3071
- const gitignorePath = path$1.join(process.cwd(), ".gitignore");
1076
+ const gitignorePath = path.join(process.cwd(), ".gitignore");
3072
1077
  let content;
3073
1078
  try {
3074
- content = await fs$2.readFile(gitignorePath, "utf-8");
1079
+ content = await fs.readFile(gitignorePath, "utf-8");
3075
1080
  debug("Reading existing .gitignore");
3076
1081
  } catch (err) {
3077
1082
  debug(".gitignore not found, creating new file");
@@ -3099,7 +1104,7 @@ ${newSection}`;
3099
1104
  `;
3100
1105
  debug("Cleaned up .gitignore managed section");
3101
1106
  }
3102
- await fs$2.writeFile(gitignorePath, content);
1107
+ await fs.writeFile(gitignorePath, content);
3103
1108
  }
3104
1109
  function getFileManagement(content) {
3105
1110
  if (!content) return "graphcommerce";
@@ -3138,9 +1143,9 @@ async function copyFiles() {
3138
1143
  const readStart = performance.now();
3139
1144
  await Promise.all(
3140
1145
  allFiles.map(async (file) => {
3141
- const filePath = path$1.join(cwd, file);
1146
+ const filePath = path.join(cwd, file);
3142
1147
  try {
3143
- const content = await fs$2.readFile(filePath);
1148
+ const content = await fs.readFile(filePath);
3144
1149
  if (getFileManagement(content) === "graphcommerce") {
3145
1150
  existingManagedFiles.add(file);
3146
1151
  debug(`Found existing managed file: ${file}`);
@@ -3159,13 +1164,13 @@ async function copyFiles() {
3159
1164
  const collectStart = performance.now();
3160
1165
  await Promise.all(
3161
1166
  packages.map(async (pkg) => {
3162
- const copyDir = path$1.join(pkg, "copy");
1167
+ const copyDir = path.join(pkg, "copy");
3163
1168
  try {
3164
1169
  const files = await fg("**/*", { cwd: copyDir, dot: true, suppressErrors: true });
3165
1170
  if (files.length > 0) {
3166
1171
  debug(`Found files in ${pkg}:`, files);
3167
1172
  for (const file of files) {
3168
- const sourcePath = path$1.join(copyDir, file);
1173
+ const sourcePath = path.join(copyDir, file);
3169
1174
  const existing = fileMap.get(file);
3170
1175
  if (existing) {
3171
1176
  console.error(`Error: File conflict detected for '${file}'
@@ -3191,11 +1196,11 @@ Path: ${copyDir}`
3191
1196
  const copyStart = performance.now();
3192
1197
  await Promise.all(
3193
1198
  Array.from(fileMap.entries()).map(async ([file, { sourcePath }]) => {
3194
- const targetPath = path$1.join(cwd, file);
1199
+ const targetPath = path.join(cwd, file);
3195
1200
  debug(`Processing file: ${file}`);
3196
1201
  try {
3197
- await fs$2.mkdir(path$1.dirname(targetPath), { recursive: true });
3198
- const sourceContent = await fs$2.readFile(sourcePath);
1202
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
1203
+ const sourceContent = await fs.readFile(sourcePath);
3199
1204
  const contentWithComment = Buffer.concat([
3200
1205
  Buffer.from(
3201
1206
  `${MANAGED_BY_GC}
@@ -3207,7 +1212,7 @@ Path: ${copyDir}`
3207
1212
  ]);
3208
1213
  let targetContent;
3209
1214
  try {
3210
- targetContent = await fs$2.readFile(targetPath);
1215
+ targetContent = await fs.readFile(targetPath);
3211
1216
  const management = getFileManagement(targetContent);
3212
1217
  if (management === "local") {
3213
1218
  debug(`File ${file} is managed locally, skipping`);
@@ -3236,7 +1241,7 @@ Source: ${sourcePath}`);
3236
1241
  managedFiles.add(file);
3237
1242
  return;
3238
1243
  }
3239
- await fs$2.writeFile(targetPath, contentWithComment);
1244
+ await fs.writeFile(targetPath, contentWithComment);
3240
1245
  if (targetContent) {
3241
1246
  console.info(`Updated managed file: ${file}`);
3242
1247
  debug(`Overwrote existing file: ${file}`);
@@ -3260,11 +1265,11 @@ Source: ${sourcePath}`);
3260
1265
  let currentDir = startPath;
3261
1266
  while (currentDir !== cwd) {
3262
1267
  try {
3263
- const dirContents = await fs$2.readdir(currentDir);
1268
+ const dirContents = await fs.readdir(currentDir);
3264
1269
  if (dirContents.length === 0) {
3265
- await fs$2.rmdir(currentDir);
1270
+ await fs.rmdir(currentDir);
3266
1271
  debug(`Removed empty directory: ${currentDir}`);
3267
- currentDir = path$1.dirname(currentDir);
1272
+ currentDir = path.dirname(currentDir);
3268
1273
  } else {
3269
1274
  break;
3270
1275
  }
@@ -3279,12 +1284,12 @@ Source: ${sourcePath}`);
3279
1284
  }
3280
1285
  await Promise.all(
3281
1286
  filesToRemove.map(async (file) => {
3282
- const filePath = path$1.join(cwd, file);
3283
- const dirPath = path$1.dirname(filePath);
1287
+ const filePath = path.join(cwd, file);
1288
+ const dirPath = path.dirname(filePath);
3284
1289
  try {
3285
- await fs$2.readdir(dirPath);
1290
+ await fs.readdir(dirPath);
3286
1291
  try {
3287
- await fs$2.unlink(filePath);
1292
+ await fs.unlink(filePath);
3288
1293
  console.info(`Removed managed file: ${file}`);
3289
1294
  debug(`Removed file: ${file}`);
3290
1295
  } catch (err) {
@@ -3313,13 +1318,373 @@ Source: ${sourcePath}`);
3313
1318
  debug(`Total execution time: ${(performance.now() - startTime).toFixed(0)}ms`);
3314
1319
  }
3315
1320
 
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();
1321
+ const fmt = (value) => {
1322
+ let formattedValue = value;
1323
+ if (typeof formattedValue === "boolean") {
1324
+ formattedValue = formattedValue ? "1" : "0";
1325
+ }
1326
+ if (typeof formattedValue === "object") {
1327
+ formattedValue = JSON.stringify(formattedValue);
1328
+ }
1329
+ if (typeof formattedValue === "number") {
1330
+ formattedValue = String(formattedValue);
1331
+ }
1332
+ return formattedValue;
1333
+ };
1334
+ function exportConfigToEnv(config) {
1335
+ let env = "";
1336
+ Object.entries(config).forEach(([key, value]) => {
1337
+ if (Array.isArray(value)) {
1338
+ value.forEach((val, idx) => {
1339
+ env += `${toEnvStr([key, `${idx}`])}='${fmt(val)}'
1340
+ `;
1341
+ });
1342
+ } else {
1343
+ env += `${toEnvStr([key])}='${fmt(value)}'
1344
+ `;
1345
+ }
1346
+ });
1347
+ return env;
1348
+ }
1349
+
1350
+ dotenv.config({ quiet: true });
1351
+ async function exportConfig() {
1352
+ const conf = loadConfig(process.cwd());
1353
+ console.log(exportConfigToEnv(conf));
1354
+ }
1355
+
1356
+ const packages = [...resolveDependenciesSync().values()].filter((p) => p !== ".");
1357
+ const resolve$1 = resolveDependency();
1358
+ dotenv.config({ quiet: true });
1359
+ async function generateConfig() {
1360
+ const resolved = resolve$1("@graphcommerce/next-config");
1361
+ if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1362
+ const targetTs = `${resolved.root}/src/generated/config.ts`;
1363
+ const targetJs = `${resolved.root}/dist/generated/config.js`;
1364
+ const schemaLocations = [
1365
+ "graphql/Config.graphqls",
1366
+ ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
1367
+ ];
1368
+ await generate({
1369
+ silent: true,
1370
+ schema: schemaLocations,
1371
+ generates: {
1372
+ [targetTs]: {
1373
+ plugins: ["typescript", "typescript-validation-schema"],
1374
+ config: {
1375
+ // enumsAsTypes: true,
1376
+ schema: "zod",
1377
+ notAllowEmptyString: true,
1378
+ strictScalars: true,
1379
+ enumsAsTypes: true,
1380
+ scalarSchemas: {
1381
+ Domain: "z.string()",
1382
+ DateTime: "z.date()",
1383
+ RichTextAST: "z.object.json()"
1384
+ }
1385
+ }
1386
+ },
1387
+ ...findParentPath(process.cwd()) && {
1388
+ "../../docs/framework/config.md": {
1389
+ plugins: ["@graphcommerce/graphql-codegen-markdown-docs"]
1390
+ }
1391
+ }
1392
+ }
1393
+ });
1394
+ writeFileSync(
1395
+ targetTs,
1396
+ await prettier.format(readFileSync(targetTs, "utf-8"), {
1397
+ ...prettierConf,
1398
+ parser: "typescript",
1399
+ plugins: prettierConf.plugins?.filter(
1400
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1401
+ )
1402
+ })
1403
+ );
1404
+ const result = transformFileSync(targetTs, {
1405
+ module: { type: "nodenext" },
1406
+ env: { targets: { node: "20" } }
1407
+ });
1408
+ writeFileSync(targetJs, result.code);
1409
+ }
1410
+
1411
+ dotenv.config({ quiet: true });
1412
+ const resolve = resolveDependency();
1413
+ function toFileName(key) {
1414
+ return key;
1415
+ }
1416
+ function generateValueLiteral(value) {
1417
+ if (value === null) return "null";
1418
+ if (value === void 0) return "undefined";
1419
+ if (typeof value === "string") return JSON.stringify(value);
1420
+ if (typeof value === "boolean" || typeof value === "number") return String(value);
1421
+ if (Array.isArray(value) || typeof value === "object" && value !== null) {
1422
+ return JSON.stringify(value, null, 2);
1423
+ }
1424
+ return JSON.stringify(value);
1425
+ }
1426
+ function shouldCreateFile(value) {
1427
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1428
+ }
1429
+ function getSectionSchemaKeys(configKey) {
1430
+ try {
1431
+ const mainSchema = GraphCommerceConfigSchema();
1432
+ const sectionSchema = mainSchema.shape[configKey];
1433
+ if (!sectionSchema) return [];
1434
+ let unwrappedSchema = sectionSchema;
1435
+ while (true) {
1436
+ if (!unwrappedSchema || typeof unwrappedSchema !== "object") break;
1437
+ if (!("_def" in unwrappedSchema)) break;
1438
+ const def = unwrappedSchema._def;
1439
+ const typeName = def?.typeName;
1440
+ if (typeName === "ZodLazy" && def.getter) {
1441
+ unwrappedSchema = def.getter();
1442
+ continue;
1443
+ }
1444
+ if (def.innerType) {
1445
+ unwrappedSchema = def.innerType;
1446
+ continue;
1447
+ }
1448
+ if (typeName === "ZodObject" && def.shape) {
1449
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
1450
+ return Object.keys(shape || {});
1451
+ }
1452
+ break;
1453
+ }
1454
+ if (unwrappedSchema && "shape" in unwrappedSchema) {
1455
+ const shape = typeof unwrappedSchema.shape === "function" ? unwrappedSchema.shape() : unwrappedSchema.shape;
1456
+ return Object.keys(shape || {});
1457
+ }
1458
+ } catch {
1459
+ }
1460
+ return [];
1461
+ }
1462
+ async function createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey) {
1463
+ const fileName = `${toFileName(sectionName)}.ts`;
1464
+ const filePath = path.join(targetDir, fileName);
1465
+ const distFileName = `${toFileName(sectionName)}.js`;
1466
+ const distFilePath = path.join(targetDistDir, distFileName);
1467
+ const schemaKeys = getSectionSchemaKeys(configKey);
1468
+ const completeSectionValue = {};
1469
+ for (const key of schemaKeys) {
1470
+ completeSectionValue[key] = sectionValue[key];
1471
+ }
1472
+ const exports$1 = Object.entries(completeSectionValue).map(([key, value]) => {
1473
+ const valueStr = generateValueLiteral(value);
1474
+ const propertyPath = `'${sectionName}.${key}'`;
1475
+ const typeAnnotation = `: Get<GraphCommerceConfig, ${propertyPath}>`;
1476
+ return `export const ${key}${typeAnnotation} = ${valueStr}`;
1477
+ }).join("\n\n");
1478
+ const imports = `import type { GraphCommerceConfig } from '../config'
1479
+ import type { Get } from 'type-fest'` ;
1480
+ const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1481
+ ${imports}
1482
+
1483
+ ${exports$1}
1484
+ `;
1485
+ const formattedContent = await prettier.format(content, {
1486
+ ...prettierConf,
1487
+ parser: "typescript",
1488
+ plugins: prettierConf.plugins?.filter(
1489
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1490
+ )
1491
+ });
1492
+ writeFileSync(filePath, formattedContent);
1493
+ const result = transformFileSync(filePath, {
1494
+ module: { type: "nodenext" },
1495
+ env: { targets: { node: "18" } }
1496
+ });
1497
+ writeFileSync(distFilePath, result.code);
1498
+ }
1499
+ async function generateConfigValues() {
1500
+ const resolved = resolve("@graphcommerce/next-config");
1501
+ if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1502
+ const config = loadConfig(process.cwd());
1503
+ const targetDir = `${resolved.root}/src/generated/configValues`;
1504
+ const targetDistDir = `${resolved.root}/dist/generated/configValues`;
1505
+ if (existsSync(targetDir)) {
1506
+ rmSync(targetDir, { recursive: true, force: true });
1507
+ }
1508
+ if (existsSync(targetDistDir)) {
1509
+ rmSync(targetDistDir, { recursive: true, force: true });
1510
+ }
1511
+ mkdirSync(targetDir, { recursive: true });
1512
+ mkdirSync(targetDistDir, { recursive: true });
1513
+ const schema = GraphCommerceConfigSchema();
1514
+ const schemaKeys = Object.keys(schema.shape);
1515
+ const completeConfig = {};
1516
+ for (const key of schemaKeys) {
1517
+ completeConfig[key] = config[key];
1518
+ }
1519
+ const configEntries = Object.entries(completeConfig);
1520
+ const nestedObjects = [];
1521
+ const rootExports = [];
1522
+ for (const [key, value] of configEntries) {
1523
+ if (shouldCreateFile(value)) {
1524
+ nestedObjects.push([key, value, key]);
1525
+ rootExports.push(`export * as ${key} from './${toFileName(key)}'`);
1526
+ } else {
1527
+ const valueStr = generateValueLiteral(value);
1528
+ const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`;
1529
+ rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`);
1530
+ }
1531
+ }
1532
+ await Promise.all(
1533
+ nestedObjects.map(
1534
+ ([sectionName, sectionValue, configKey]) => createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey)
1535
+ )
1536
+ );
1537
+ const rootImports = `import type { GraphCommerceConfig } from '../config'
1538
+ import type { Get } from 'type-fest'` ;
1539
+ const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1540
+ ${rootImports}
1541
+
1542
+ ${rootExports.join("\n")}
1543
+ `;
1544
+ const formattedIndexContent = await prettier.format(indexContent, {
1545
+ ...prettierConf,
1546
+ parser: "typescript",
1547
+ plugins: prettierConf.plugins?.filter(
1548
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1549
+ )
1550
+ });
1551
+ const indexPath = path.join(targetDir, "index.ts");
1552
+ const distIndexPath = path.join(targetDistDir, "index.js");
1553
+ writeFileSync(indexPath, formattedIndexContent);
1554
+ const indexResult = transformFileSync(indexPath, {
1555
+ module: { type: "nodenext" },
1556
+ env: { targets: { node: "20" } }
1557
+ });
1558
+ writeFileSync(distIndexPath, indexResult.code);
1559
+ console.log(`\u2705 Generated config values in ${targetDir} and ${targetDistDir}`);
1560
+ console.log(`\u{1F4C1} Created ${nestedObjects.length} nested object files + index.ts/.js`);
1561
+ console.log(`\u{1F4DD} Root exports: ${configEntries.length - nestedObjects.length}`);
1562
+ }
1563
+
1564
+ let graphcommerceConfig;
1565
+ function domains(config) {
1566
+ return Object.values(
1567
+ config.storefront.reduce(
1568
+ (acc, loc) => {
1569
+ if (!loc.domain) return acc;
1570
+ acc[loc.domain] = {
1571
+ defaultLocale: loc.locale,
1572
+ locales: [...acc[loc.domain]?.locales ?? [], loc.locale],
1573
+ domain: loc.domain,
1574
+ http: process.env.NODE_ENV === "development" || void 0
1575
+ };
1576
+ return acc;
1577
+ },
1578
+ {}
1579
+ )
1580
+ );
1581
+ }
1582
+ function withGraphCommerce(nextConfig, cwd = process.cwd()) {
1583
+ graphcommerceConfig ??= loadConfig(cwd);
1584
+ const { storefront } = graphcommerceConfig;
1585
+ const transpilePackages = [
1586
+ ...[...resolveDependenciesSync().keys()].slice(1),
1587
+ ...nextConfig.transpilePackages ?? []
1588
+ ];
1589
+ return {
1590
+ ...nextConfig,
1591
+ bundlePagesRouterDependencies: true,
1592
+ serverExternalPackages: [
1593
+ // All @whatwg-node packages to prevent private class field bundling issues
1594
+ // https://github.com/ardatan/whatwg-node/tree/master/packages
1595
+ "@whatwg-node/cookie-store",
1596
+ "@whatwg-node/disposablestack",
1597
+ "@whatwg-node/events",
1598
+ "@whatwg-node/fetch",
1599
+ "@whatwg-node/node-fetch",
1600
+ "@whatwg-node/promise-helpers",
1601
+ "@whatwg-node/server",
1602
+ "@whatwg-node/server-plugin-cookies",
1603
+ ...nextConfig.serverExternalPackages ?? []
1604
+ ],
1605
+ turbopack: {
1606
+ ...nextConfig.turbopack ?? {},
1607
+ rules: {
1608
+ ...nextConfig.turbopack?.rules ?? {},
1609
+ "*.yaml": { loaders: [{ loader: "js-yaml-loader", options: {} }], as: "*.js" },
1610
+ "*.yml": { loaders: [{ loader: "js-yaml-loader", options: {} }], as: "*.js" },
1611
+ "*.po": { loaders: [{ loader: "@lingui/loader", options: {} }], as: "*.js" }
1612
+ }
1613
+ },
1614
+ experimental: {
1615
+ ...nextConfig.experimental,
1616
+ scrollRestoration: true,
1617
+ swcPlugins: [...nextConfig.experimental?.swcPlugins ?? [], ["@lingui/swc-plugin", {}]],
1618
+ optimizePackageImports: [
1619
+ ...transpilePackages,
1620
+ ...nextConfig.experimental?.optimizePackageImports ?? []
1621
+ ]
1622
+ },
1623
+ i18n: {
1624
+ ...nextConfig.i18n,
1625
+ defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale,
1626
+ locales: storefront.map((locale) => locale.locale),
1627
+ domains: [...domains(graphcommerceConfig), ...nextConfig.i18n?.domains ?? []]
1628
+ },
1629
+ images: {
1630
+ ...nextConfig.images,
1631
+ // GraphCommerce uses quality 52 by default for optimized image delivery
1632
+ qualities: [52, 75, ...nextConfig.images?.qualities ?? []],
1633
+ remotePatterns: [
1634
+ "magentoEndpoint" in graphcommerceConfig ? {
1635
+ hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname
1636
+ } : void 0,
1637
+ { hostname: "**.graphassets.com" },
1638
+ { hostname: "*.graphcommerce.org" },
1639
+ ...nextConfig.images?.remotePatterns ?? []
1640
+ ].filter((v) => !!v)
1641
+ },
1642
+ rewrites: async () => {
1643
+ let rewrites = await nextConfig.rewrites?.() ?? [];
1644
+ if (Array.isArray(rewrites)) {
1645
+ rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] };
1646
+ }
1647
+ if ("productRoute" in graphcommerceConfig && typeof graphcommerceConfig.productRoute === "string" && graphcommerceConfig.productRoute !== "/p/") {
1648
+ rewrites.beforeFiles?.push({
1649
+ source: `${graphcommerceConfig.productRoute ?? "/p/"}:path*`,
1650
+ destination: "/p/:path*"
1651
+ });
1652
+ }
1653
+ return rewrites;
1654
+ },
1655
+ transpilePackages,
1656
+ webpack: (config, options) => {
1657
+ if (!config.module) config.module = { rules: [] };
1658
+ config.module = {
1659
+ ...config.module,
1660
+ rules: [
1661
+ ...config.module.rules ?? [],
1662
+ // Allow importing yml/yaml files for graphql-mesh
1663
+ { test: /\.ya?ml$/, use: "js-yaml-loader" },
1664
+ // @lingui .po file support
1665
+ { test: /\.po/, use: "@lingui/loader" }
1666
+ ],
1667
+ exprContextCritical: false
1668
+ };
1669
+ if (!config.plugins) config.plugins = [];
1670
+ config.snapshot = {
1671
+ ...config.snapshot ?? {},
1672
+ managedPaths: [
1673
+ new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join("|")})`)
1674
+ ]
1675
+ };
1676
+ config.watchOptions = {
1677
+ ...config.watchOptions ?? {},
1678
+ ignored: new RegExp(
1679
+ `^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join(
1680
+ "|"
1681
+ )})))(/((?:[^/]*(?:/|$))*)(?:$|/))?`
1682
+ )
1683
+ };
1684
+ if (!config.resolve) config.resolve = {};
1685
+ return typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, options) : config;
1686
+ }
1687
+ };
3323
1688
  }
3324
1689
 
3325
- export { GraphCommerceConfigSchema, codegen, codegenInterceptors, configToImportMeta, copyFiles, exportConfig, findParentPath, g, generateConfig, loadConfig, packageRoots, replaceConfigInString, resolveDependenciesSync, sig, sortDependencies, withGraphCommerce };
1690
+ export { GraphCommerceConfigSchema, PackagesSort, TopologicalSort, cleanupInterceptors, codegen, codegenInterceptors, copyFiles, exportConfig, findParentPath, g, generateConfig, generateConfigValues, loadConfig, packageRoots, resolveDependenciesSync, resolveDependency, sig, sortDependencies, withGraphCommerce };