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

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