@mercurjs/dashboard-sdk 2.2.0-canary.5 → 2.2.0-canary.50

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.
package/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,900 +15,36 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
33
- generatePluginEntryModule: () => generatePluginEntryModule,
34
- mercurDashboardPlugin: () => mercurDashboardPlugin
23
+ defineCustomFieldsConfig: () => defineCustomFieldsConfig,
24
+ defineNavigationConfig: () => defineNavigationConfig,
25
+ defineWidgetConfig: () => defineWidgetConfig
35
26
  });
36
27
  module.exports = __toCommonJS(index_exports);
37
28
 
38
- // src/plugin.ts
39
- var import_path5 = __toESM(require("path"), 1);
40
- var import_fs4 = __toESM(require("fs"), 1);
41
-
42
- // src/babel.ts
43
- var import_parser = require("@babel/parser");
44
- var import_traverse = __toESM(require("@babel/traverse"), 1);
45
- var import_types = require("@babel/types");
46
- var traverse;
47
- if (typeof import_traverse.default === "function") {
48
- traverse = import_traverse.default;
49
- } else {
50
- traverse = import_traverse.default.default;
51
- }
52
-
53
- // src/utils.ts
54
- function normalizePath(filePath) {
55
- return filePath.replace(/\\/g, "/");
56
- }
57
- function getParserOptions(file) {
58
- const options = {
59
- sourceType: "module",
60
- plugins: ["jsx"]
61
- };
62
- if (file.endsWith(".ts") || file.endsWith(".tsx")) {
63
- options.plugins.push("typescript");
64
- }
65
- return options;
66
- }
67
- function resolveExports(moduleExports) {
68
- if ("default" in moduleExports && moduleExports.default && "default" in moduleExports.default) {
69
- return resolveExports(moduleExports.default);
70
- }
71
- return moduleExports;
72
- }
73
- async function getFileExports(path7) {
74
- const { unregister } = await safeRegister();
75
- const module2 = require(path7);
76
- unregister();
77
- return resolveExports(module2);
78
- }
79
- var safeRegister = async () => {
80
- const { register } = await import("esbuild-register/dist/node");
81
- let res;
82
- try {
83
- res = register({
84
- format: "cjs",
85
- loader: "ts"
86
- });
87
- } catch {
88
- res = {
89
- unregister: () => {
90
- }
91
- };
92
- }
93
- return res;
94
- };
95
- function hasDefaultExport(ast) {
96
- let found = false;
97
- traverse(ast, {
98
- ExportDefaultDeclaration() {
99
- found = true;
100
- },
101
- AssignmentExpression(path7) {
102
- if (path7.node.left.type === "MemberExpression" && path7.node.left.object.type === "Identifier" && path7.node.left.object.name === "exports" && path7.node.left.property.type === "Identifier" && path7.node.left.property.name === "default") {
103
- found = true;
104
- }
105
- },
106
- ExportNamedDeclaration(path7) {
107
- const specifiers = path7.node.specifiers;
108
- if (specifiers?.some(
109
- (s) => s.type === "ExportSpecifier" && s.exported.type === "Identifier" && s.exported.name === "default"
110
- )) {
111
- found = true;
112
- }
113
- }
114
- });
115
- return found;
116
- }
117
-
118
- // src/constants.ts
119
- var VALID_FILE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
120
- var CONFIG_VIRTUAL_MODULE = "virtual:mercur/config";
121
- var ROUTES_VIRTUAL_MODULE = "virtual:mercur/routes";
122
- var COMPONENTS_VIRTUAL_MODULE = "virtual:mercur/components";
123
- var MENU_ITEMS_VIRTUAL_MODULE = "virtual:mercur/menu-items";
124
- var I18N_VIRTUAL_MODULE = "virtual:mercur/i18n";
125
- var RESOLVED_CONFIG_MODULE = "\0" + CONFIG_VIRTUAL_MODULE;
126
- var RESOLVED_ROUTES_MODULE = "\0" + ROUTES_VIRTUAL_MODULE;
127
- var RESOLVED_COMPONENTS_MODULE = "\0" + COMPONENTS_VIRTUAL_MODULE;
128
- var RESOLVED_MENU_ITEMS_MODULE = "\0" + MENU_ITEMS_VIRTUAL_MODULE;
129
- var RESOLVED_I18N_MODULE = "\0" + I18N_VIRTUAL_MODULE;
130
- var VIRTUAL_MODULES = [
131
- CONFIG_VIRTUAL_MODULE,
132
- ROUTES_VIRTUAL_MODULE,
133
- COMPONENTS_VIRTUAL_MODULE,
134
- MENU_ITEMS_VIRTUAL_MODULE,
135
- I18N_VIRTUAL_MODULE
136
- ];
137
-
138
- // src/virtual-modules.ts
139
- var import_path4 = __toESM(require("path"), 1);
140
-
141
- // src/routes.ts
142
- var import_fs = __toESM(require("fs"), 1);
143
- var import_path = __toESM(require("path"), 1);
144
- function getRoute(file, routesDir) {
145
- const importPath = normalizePath(file);
146
- const normalizedRoutesDir = normalizePath(routesDir);
147
- return importPath.replace(normalizedRoutesDir, "").replace(/\[\[\*\]\]/g, "*?").replace(/\[\*\]/g, "*").replace(/\(([^[\])]+)\)/g, "$1?").replace(/\[\[([^\]]+)\]\]/g, ":$1?").replace(/\[([^\]]+)\]/g, ":$1").replace(
148
- new RegExp(
149
- `/page\\.(${VALID_FILE_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})$`
150
- ),
151
- ""
152
- ) || "/";
153
- }
154
- function crawlRoutes(dir, pattern = "page") {
155
- const files = [];
156
- if (!import_fs.default.existsSync(dir)) {
157
- return files;
158
- }
159
- const entries = import_fs.default.readdirSync(dir, { withFileTypes: true });
160
- for (const entry of entries) {
161
- const fullPath = import_path.default.join(dir, entry.name);
162
- if (entry.isDirectory()) {
163
- files.push(...crawlRoutes(fullPath, pattern));
164
- } else if (entry.isFile()) {
165
- const ext = import_path.default.extname(entry.name);
166
- const baseName = import_path.default.basename(entry.name, ext);
167
- if (baseName === pattern && VALID_FILE_EXTENSIONS.includes(ext)) {
168
- files.push(fullPath);
169
- }
170
- }
171
- }
172
- return files;
173
- }
174
- function hasConfigPublic(ast) {
175
- let found = false;
176
- traverse(ast, {
177
- ExportNamedDeclaration(path7) {
178
- const declaration = path7.node.declaration;
179
- if (!(0, import_types.isVariableDeclaration)(declaration)) return;
180
- for (const decl of declaration.declarations) {
181
- if ((0, import_types.isVariableDeclarator)(decl) && (0, import_types.isIdentifier)(decl.id, { name: "config" }) && decl.init?.type === "ObjectExpression") {
182
- const publicProp = decl.init.properties.find(
183
- (prop) => (0, import_types.isObjectProperty)(prop) && (0, import_types.isIdentifier)(prop.key, { name: "public" }) && (0, import_types.isBooleanLiteral)(prop.value, { value: true })
184
- );
185
- if (publicProp) {
186
- found = true;
187
- }
188
- }
189
- }
190
- }
191
- });
192
- return found;
193
- }
194
- function getNamedExports(ast) {
195
- let hasHandle = false;
196
- let hasLoader = false;
197
- traverse(ast, {
198
- ExportNamedDeclaration(path7) {
199
- const declaration = path7.node.declaration;
200
- if (declaration?.type === "VariableDeclaration") {
201
- declaration.declarations.forEach((decl) => {
202
- if (decl.id.type === "Identifier" && decl.id.name === "handle") {
203
- hasHandle = true;
204
- }
205
- if (decl.id.type === "Identifier" && decl.id.name === "loader") {
206
- hasLoader = true;
207
- }
208
- });
209
- }
210
- if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === "loader") {
211
- hasLoader = true;
212
- }
213
- if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === "handle") {
214
- hasHandle = true;
215
- }
216
- }
217
- });
218
- return { hasHandle, hasLoader };
219
- }
220
- function generateRouteComponentName(index) {
221
- return `RouteComponent${index}`;
222
- }
223
- function generateHandleName(index) {
224
- return `RouteHandle${index}`;
225
- }
226
- function generateLoaderName(index) {
227
- return `RouteLoader${index}`;
228
- }
229
- function generateImports(file, index, hasHandle, hasLoader) {
230
- const imports = [];
231
- const componentName = generateRouteComponentName(index);
232
- const importPath = normalizePath(file);
233
- if (!hasHandle && !hasLoader) {
234
- imports.push(`import ${componentName} from "${importPath}"`);
235
- } else {
236
- const namedImports = [
237
- hasHandle && `handle as ${generateHandleName(index)}`,
238
- hasLoader && `loader as ${generateLoaderName(index)}`
239
- ].filter(Boolean).join(", ");
240
- imports.push(`import ${componentName}, { ${namedImports} } from "${importPath}"`);
241
- }
242
- return imports;
243
- }
244
- function generateRouteObject(routePath, index, hasHandle, hasLoader, isPublic) {
29
+ // src/config/utils.ts
30
+ function createConfigHelper(config) {
245
31
  return {
246
- Component: generateRouteComponentName(index),
247
- path: routePath,
248
- handle: hasHandle ? generateHandleName(index) : void 0,
249
- loader: hasLoader ? generateLoaderName(index) : void 0,
250
- isPublic
32
+ ...config,
33
+ $$typeof: /* @__PURE__ */ Symbol.for("react.memo")
251
34
  };
252
35
  }
253
- function formatRoute(route, indent = " ") {
254
- let result = `${indent}{
255
- `;
256
- result += `${indent} Component: ${route.Component},
257
- `;
258
- result += `${indent} path: "${route.path}"`;
259
- if (route.handle) {
260
- result += `,
261
- ${indent} handle: ${route.handle}`;
262
- }
263
- if (route.loader) {
264
- result += `,
265
- ${indent} loader: ${route.loader}`;
266
- }
267
- if (route.isPublic) {
268
- result += `,
269
- ${indent} isPublic: true`;
270
- }
271
- if (route.children?.length) {
272
- result += `,
273
- ${indent} children: [
274
- `;
275
- result += route.children.map((child) => formatRoute(child, indent + " ")).join(",\n");
276
- result += `
277
- ${indent} ]`;
278
- }
279
- result += `
280
- ${indent}}`;
281
- return result;
282
- }
283
- function parseFile(file, routesDir, index) {
284
- try {
285
- const code = import_fs.default.readFileSync(file, "utf-8");
286
- const ast = (0, import_parser.parse)(code, getParserOptions(file));
287
- if (!hasDefaultExport(ast)) {
288
- return null;
289
- }
290
- const { hasHandle, hasLoader } = getNamedExports(ast);
291
- const isPublic = hasConfigPublic(ast);
292
- const routePath = getRoute(file, routesDir);
293
- const imports = generateImports(file, index, hasHandle, hasLoader);
294
- const route = generateRouteObject(routePath, index, hasHandle, hasLoader, isPublic);
295
- return {
296
- imports,
297
- route
298
- };
299
- } catch {
300
- return null;
301
- }
302
- }
303
- function buildRouteTree(results) {
304
- const routeMap = /* @__PURE__ */ new Map();
305
- const sortedResults = [...results].sort(
306
- (a, b) => a.route.path.split("/").length - b.route.path.split("/").length
307
- );
308
- for (const result of sortedResults) {
309
- const routePath = result.route.path;
310
- const isParallel = routePath.includes("/@");
311
- if (isParallel) {
312
- const parentPath = routePath.split("/@")[0];
313
- const parent = routeMap.get(parentPath);
314
- if (parent) {
315
- parent.route.children = parent.route.children ?? [];
316
- parent.route.children.push({
317
- ...result.route,
318
- path: result.route.path.replace("/@", "/")
319
- });
320
- parent.imports.push(...result.imports);
321
- } else {
322
- routeMap.set(routePath, result);
323
- }
324
- } else {
325
- routeMap.set(routePath, result);
326
- }
327
- }
328
- return Array.from(routeMap.values());
329
- }
330
- function generateRoutes({ srcDir, pluginExtensions }) {
331
- const routesDir = import_path.default.join(srcDir, "routes");
332
- let index = 0;
333
- const results = [];
334
- for (const file of crawlRoutes(routesDir)) {
335
- const result = parseFile(file, routesDir, index);
336
- if (result) {
337
- results.push(result);
338
- index++;
339
- }
340
- }
341
- const pluginDeclarations = pluginExtensions.map(
342
- (ext, i) => `const __plugin${i} = (await import("${normalizePath(ext)}")).default`
343
- );
344
- const pluginSpreads = pluginExtensions.map(
345
- (_, i) => ` ...(__plugin${i}.routeModule?.routes ?? [])`
346
- );
347
- const routeTree = buildRouteTree(results);
348
- const appImports = routeTree.flatMap((r) => r.imports);
349
- const appRoutes = routeTree.map((r) => formatRoute(r.route));
350
- const allImports = [...appImports];
351
- const allRoutes = [...appRoutes, ...pluginSpreads];
352
- if (allImports.length === 0 && pluginDeclarations.length === 0 && allRoutes.length === 0) {
353
- return `export const customRoutes = []`;
354
- }
355
- return `${allImports.join("\n")}
356
-
357
- ${pluginDeclarations.join("\n")}
358
-
359
- export const customRoutes = [
360
- ${allRoutes.join(",\n")}
361
- ]`;
362
- }
363
-
364
- // src/menu-items.ts
365
- var import_fs2 = __toESM(require("fs"), 1);
366
- var import_path2 = __toESM(require("path"), 1);
367
- function crawlRoutes2(dir, pattern = "page") {
368
- const files = [];
369
- if (!import_fs2.default.existsSync(dir)) {
370
- return files;
371
- }
372
- const entries = import_fs2.default.readdirSync(dir, { withFileTypes: true });
373
- for (const entry of entries) {
374
- const fullPath = import_path2.default.join(dir, entry.name);
375
- if (entry.isDirectory()) {
376
- files.push(...crawlRoutes2(fullPath, pattern));
377
- } else if (entry.isFile()) {
378
- const ext = import_path2.default.extname(entry.name);
379
- const baseName = import_path2.default.basename(entry.name, ext);
380
- if (baseName === pattern && VALID_FILE_EXTENSIONS.includes(ext)) {
381
- files.push(fullPath);
382
- }
383
- }
384
- }
385
- return files;
386
- }
387
- function getRoute2(file, routesDir) {
388
- const importPath = normalizePath(file);
389
- const normalizedRoutesDir = normalizePath(routesDir);
390
- return importPath.replace(normalizedRoutesDir, "").replace(/\[\[\*\]\]/g, "*?").replace(/\[\*\]/g, "*").replace(/\(([^[\])]+)\)/g, "$1?").replace(/\[\[([^\]]+)\]\]/g, ":$1?").replace(/\[([^\]]+)\]/g, ":$1").replace(
391
- new RegExp(
392
- `/page\\.(${VALID_FILE_EXTENSIONS.map((ext) => ext.slice(1)).join("|")})$`
393
- ),
394
- ""
395
- ) || "/";
36
+ function defineWidgetConfig(config) {
37
+ return createConfigHelper(config);
396
38
  }
397
- function getConfigObjectProperties(path7) {
398
- if ((0, import_types.isVariableDeclarator)(path7.node)) {
399
- const decl = (0, import_types.isIdentifier)(path7.node.id, { name: "config" }) ? path7.node : null;
400
- if (!decl) return null;
401
- if ((0, import_types.isCallExpression)(decl.init) && decl.init.arguments.length > 0 && (0, import_types.isObjectExpression)(decl.init.arguments[0])) {
402
- return decl.init.arguments[0].properties;
403
- }
404
- if ((0, import_types.isObjectExpression)(decl.init)) {
405
- return decl.init.properties;
406
- }
407
- return null;
408
- }
409
- const declaration = path7.node.declaration;
410
- if ((0, import_types.isVariableDeclaration)(declaration)) {
411
- const configDecl = declaration.declarations.find(
412
- (d) => (0, import_types.isVariableDeclarator)(d) && (0, import_types.isIdentifier)(d.id, { name: "config" })
413
- );
414
- if (configDecl && (0, import_types.isCallExpression)(configDecl.init) && configDecl.init.arguments.length > 0 && (0, import_types.isObjectExpression)(configDecl.init.arguments[0])) {
415
- return configDecl.init.arguments[0].properties;
416
- }
417
- const directDecl = declaration.declarations.find(
418
- (d) => (0, import_types.isVariableDeclarator)(d) && (0, import_types.isIdentifier)(d.id, { name: "config" })
419
- );
420
- if (directDecl && (0, import_types.isObjectExpression)(directDecl.init)) {
421
- return directDecl.init.properties;
422
- }
423
- }
424
- return null;
425
- }
426
- function processConfigProperties(properties) {
427
- const hasProperty = (name) => properties.some(
428
- (prop) => (0, import_types.isObjectProperty)(prop) && (0, import_types.isIdentifier)(prop.key, { name })
429
- );
430
- const hasLabel = hasProperty("label");
431
- if (!hasLabel) {
432
- return null;
433
- }
434
- const hasIcon = hasProperty("icon");
435
- const nested = properties.find(
436
- (prop) => (0, import_types.isObjectProperty)(prop) && (0, import_types.isIdentifier)(prop.key, { name: "nested" })
437
- );
438
- let nestedValue;
439
- if (nested && (0, import_types.isObjectProperty)(nested) && (0, import_types.isStringLiteral)(nested.value)) {
440
- nestedValue = nested.value.value;
441
- }
442
- const translationNs = properties.find(
443
- (prop) => (0, import_types.isObjectProperty)(prop) && (0, import_types.isIdentifier)(prop.key, { name: "translationNs" })
444
- );
445
- let translationNsValue;
446
- if (translationNs && (0, import_types.isObjectProperty)(translationNs) && (0, import_types.isStringLiteral)(translationNs.value)) {
447
- translationNsValue = translationNs.value.value;
448
- }
449
- const rank = properties.find(
450
- (prop) => (0, import_types.isObjectProperty)(prop) && (0, import_types.isIdentifier)(prop.key, { name: "rank" })
451
- );
452
- let rankValue;
453
- if (rank && (0, import_types.isObjectProperty)(rank) && (0, import_types.isNumericLiteral)(rank.value)) {
454
- rankValue = rank.value.value;
455
- }
456
- return { label: hasLabel, icon: hasIcon, rank: rankValue, nested: nestedValue, translationNs: translationNsValue };
457
- }
458
- function getRouteConfig(file) {
459
- try {
460
- const code = import_fs2.default.readFileSync(file, "utf-8");
461
- const ast = (0, import_parser.parse)(code, getParserOptions(file));
462
- let config = null;
463
- let configFound = false;
464
- traverse(ast, {
465
- VariableDeclarator(path7) {
466
- if (configFound) return;
467
- const properties = getConfigObjectProperties(path7);
468
- if (!properties) return;
469
- config = processConfigProperties(properties);
470
- if (config) configFound = true;
471
- },
472
- ExportNamedDeclaration(path7) {
473
- if (configFound) return;
474
- const properties = getConfigObjectProperties(path7);
475
- if (!properties) return;
476
- config = processConfigProperties(properties);
477
- if (config) configFound = true;
478
- }
479
- });
480
- return config;
481
- } catch {
482
- return null;
483
- }
484
- }
485
- function generateRouteConfigName(index) {
486
- return `RouteConfig${index}`;
487
- }
488
- function generateImport(file, index) {
489
- const importPath = normalizePath(file);
490
- return `import { config as ${generateRouteConfigName(index)} } from "${importPath}"`;
491
- }
492
- function generateMenuItem(config, file, routesDir, index) {
493
- const configName = generateRouteConfigName(index);
494
- return {
495
- label: `${configName}.label`,
496
- icon: config.icon ? `${configName}.icon` : void 0,
497
- path: getRoute2(file, routesDir),
498
- rank: config.rank,
499
- nested: config.nested,
500
- translationNs: config.translationNs ? `${configName}.translationNs` : void 0
501
- };
39
+ function defineNavigationConfig(config) {
40
+ return createConfigHelper(config);
502
41
  }
503
- function formatMenuItem(menuItem) {
504
- const parts = [
505
- ` label: ${menuItem.label}`,
506
- ` icon: ${menuItem.icon || "undefined"}`,
507
- ` path: "${menuItem.path}"`,
508
- ` rank: ${menuItem.rank !== void 0 ? menuItem.rank : "undefined"}`,
509
- ` nested: ${menuItem.nested ? `"${menuItem.nested}"` : "undefined"}`,
510
- ` translationNs: ${menuItem.translationNs || "undefined"}`
511
- ];
512
- return ` {
513
- ${parts.join(",\n")}
514
- }`;
515
- }
516
- function parseMenuItemFile(file, routesDir, index) {
517
- const config = getRouteConfig(file);
518
- if (!config) {
519
- return null;
520
- }
521
- return {
522
- import: generateImport(file, index),
523
- menuItem: generateMenuItem(config, file, routesDir, index)
524
- };
525
- }
526
- function generateMenuItems({ srcDir, pluginExtensions }) {
527
- const routesDir = import_path2.default.join(srcDir, "routes");
528
- let index = 0;
529
- const results = [];
530
- for (const file of crawlRoutes2(routesDir)) {
531
- const result = parseMenuItemFile(file, routesDir, index);
532
- if (result) {
533
- results.push(result);
534
- index++;
535
- }
536
- }
537
- const pluginDeclarations = pluginExtensions.map(
538
- (ext, i) => `const __plugin${i} = (await import("${normalizePath(ext)}")).default`
539
- );
540
- const pluginSpreads = pluginExtensions.map(
541
- (_, i) => ` ...(__plugin${i}.menuItemModule?.menuItems ?? [])`
542
- );
543
- const appImports = results.map((r) => r.import);
544
- const appMenuItems = results.map((r) => formatMenuItem(r.menuItem));
545
- const allImports = [...appImports];
546
- const allMenuItems = [...appMenuItems, ...pluginSpreads];
547
- if (allImports.length === 0 && pluginDeclarations.length === 0 && allMenuItems.length === 0) {
548
- return `export default { menuItems: [] }`;
549
- }
550
- return `${allImports.join("\n")}
551
-
552
- ${pluginDeclarations.join("\n")}
553
-
554
- export default {
555
- menuItems: [
556
- ${allMenuItems.join(",\n")}
557
- ]
558
- }`;
559
- }
560
-
561
- // src/i18n.ts
562
- var import_fs3 = __toESM(require("fs"), 1);
563
- var import_path3 = __toESM(require("path"), 1);
564
- function findI18nIndex(srcDir) {
565
- const i18nDir = import_path3.default.join(srcDir, "i18n");
566
- if (!import_fs3.default.existsSync(i18nDir)) {
567
- return null;
568
- }
569
- for (const ext of VALID_FILE_EXTENSIONS) {
570
- const filePath = import_path3.default.join(i18nDir, `index${ext}`);
571
- if (import_fs3.default.existsSync(filePath)) {
572
- return filePath;
573
- }
574
- }
575
- return null;
576
- }
577
- function generateI18n({ srcDir }) {
578
- const indexFile = findI18nIndex(srcDir);
579
- if (!indexFile) {
580
- return `export default {}`;
581
- }
582
- const importPath = normalizePath(indexFile);
583
- return `import i18nResources from "${importPath}"
584
- export default i18nResources`;
585
- }
586
-
587
- // src/virtual-modules.ts
588
- function isVirtualModule(id) {
589
- return VIRTUAL_MODULES.includes(id);
590
- }
591
- function resolveVirtualModule(id) {
592
- return "\0" + id;
593
- }
594
- function loadVirtualModule({
595
- cwd,
596
- id,
597
- mercurConfig
598
- }) {
599
- if (id === RESOLVED_CONFIG_MODULE) {
600
- return loadConfigModule(mercurConfig);
601
- }
602
- if (id === RESOLVED_COMPONENTS_MODULE) {
603
- return loadComponentsModule(mercurConfig, cwd);
604
- }
605
- if (id === RESOLVED_ROUTES_MODULE) {
606
- return loadRoutesModule(mercurConfig);
607
- }
608
- if (id === RESOLVED_MENU_ITEMS_MODULE) {
609
- return loadMenuItemsModule(mercurConfig);
610
- }
611
- if (id === RESOLVED_I18N_MODULE) {
612
- return loadI18nModule(mercurConfig);
613
- }
614
- return null;
615
- }
616
- function loadConfigModule(mercurConfig) {
617
- const { ...configWithoutComponents } = mercurConfig;
618
- return `export default ${JSON.stringify(configWithoutComponents)}`;
619
- }
620
- function loadComponentsModule(mercurConfig, cwd) {
621
- const components = mercurConfig.components ?? {};
622
- const imports = [];
623
- const exports2 = [];
624
- Object.entries(components).forEach(([name, componentPath]) => {
625
- const resolvedPath = import_path4.default.resolve(cwd, "src", componentPath);
626
- imports.push(`import _${name} from "${JSON.stringify(resolvedPath)}"`);
627
- exports2.push(`${name}: _${name}`);
628
- });
629
- return `
630
- ${imports.join("\n")}
631
-
632
- export default {
633
- ${exports2.join(",\n ")}
634
- }
635
- `;
636
- }
637
- function loadRoutesModule(mercurConfig) {
638
- return generateRoutes(mercurConfig);
639
- }
640
- function loadMenuItemsModule(mercurConfig) {
641
- return generateMenuItems(mercurConfig);
642
- }
643
- function loadI18nModule(mercurConfig) {
644
- return generateI18n(mercurConfig);
645
- }
646
-
647
- // src/plugin.ts
648
- function isRouteFile(file) {
649
- const basename = import_path5.default.basename(file, import_path5.default.extname(file));
650
- return basename === "page";
651
- }
652
- var UI_MODULE_KEYS = ["admin_ui", "vendor_ui"];
653
- function findNodeModulesRoot(configDir) {
654
- let dir = configDir;
655
- while (dir !== import_path5.default.dirname(dir)) {
656
- const candidate = import_path5.default.join(dir, "node_modules");
657
- if (import_fs4.default.existsSync(candidate) && import_fs4.default.statSync(candidate).isDirectory()) {
658
- return candidate;
659
- }
660
- dir = import_path5.default.dirname(dir);
661
- }
662
- return import_path5.default.join(configDir, "node_modules");
663
- }
664
- function resolvePluginRoot(resolve, configDir, nodeModulesRoot) {
665
- try {
666
- if (resolve.startsWith(".")) {
667
- const resolved = import_path5.default.resolve(configDir, resolve);
668
- if (import_fs4.default.existsSync(resolved)) {
669
- return import_fs4.default.realpathSync(resolved);
670
- }
671
- return null;
672
- }
673
- const packagePath = import_path5.default.join(nodeModulesRoot, resolve);
674
- if (!import_fs4.default.existsSync(packagePath)) {
675
- return null;
676
- }
677
- return import_fs4.default.realpathSync(packagePath);
678
- } catch {
679
- return null;
680
- }
681
- }
682
- function resolvePluginExtensions(plugins, configDir, appType) {
683
- const nodeModulesRoot = findNodeModulesRoot(configDir);
684
- const extensions = [];
685
- for (const plugin of plugins) {
686
- const resolve = typeof plugin === "string" ? plugin : plugin?.resolve;
687
- if (!resolve || typeof resolve !== "string") continue;
688
- const pluginRoot = resolvePluginRoot(resolve, configDir, nodeModulesRoot);
689
- if (!pluginRoot) continue;
690
- const extFile = import_path5.default.join(
691
- pluginRoot,
692
- ".medusa/server/src",
693
- appType,
694
- "index.mjs"
695
- );
696
- if (import_fs4.default.existsSync(extFile)) {
697
- extensions.push(extFile);
698
- }
699
- }
700
- return extensions;
701
- }
702
- function trimTrailingSlashes(value) {
703
- let end = value.length;
704
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
705
- end -= 1;
706
- }
707
- return end === value.length ? value : value.slice(0, end);
708
- }
709
- async function loadMedusaConfig(medusaConfigPath, root, options) {
710
- try {
711
- const mod = await getFileExports(medusaConfigPath);
712
- const medusaConfig = mod.default ?? mod;
713
- const modules = medusaConfig?.modules ?? {};
714
- const configDir = import_path5.default.dirname(medusaConfigPath);
715
- let base;
716
- let appType = "admin";
717
- let vendorAppUrl;
718
- const vendorModule = modules.vendor_ui;
719
- const vendorPath = vendorModule?.options?.path ?? "/seller";
720
- if (options.vendorUrl) {
721
- vendorAppUrl = trimTrailingSlashes(options.vendorUrl);
722
- } else if (options.isDevelopment) {
723
- const vendorHost = vendorModule?.options?.viteDevServerHost ?? "localhost";
724
- const vendorPort = vendorModule?.options?.viteDevServerPort ?? 7001;
725
- vendorAppUrl = `http://${vendorHost}:${vendorPort}${vendorPath}`;
726
- } else {
727
- vendorAppUrl = vendorPath;
728
- }
729
- for (const key of UI_MODULE_KEYS) {
730
- const value = modules[key];
731
- if (!value || typeof value !== "object" || !value.options?.appDir)
732
- continue;
733
- const appDir = import_path5.default.resolve(configDir, value.options.appDir);
734
- if (appDir === root) {
735
- base = value.options.path;
736
- appType = key === "vendor_ui" ? "vendor" : "admin";
737
- break;
738
- }
739
- }
740
- const plugins = medusaConfig?.plugins?.filter(
741
- (plugin) => plugin.resolve !== "@medusajs/draft-order"
742
- ) ?? [];
743
- const pluginExtensions = resolvePluginExtensions(plugins, configDir, appType);
744
- return { base, pluginExtensions, vendorAppUrl };
745
- } catch {
746
- return { pluginExtensions: [] };
747
- }
748
- }
749
- function mercurDashboardPlugin(pluginConfig) {
750
- let root;
751
- let config;
752
- return {
753
- name: "@mercurjs/dashboard-sdk",
754
- async config(viteConfig) {
755
- root = viteConfig.root || process.cwd();
756
- const isDevelopment = (viteConfig.mode || process.env.NODE_ENV || "development") !== "production";
757
- const medusaConfigPath = import_path5.default.resolve(
758
- root,
759
- pluginConfig.medusaConfigPath
760
- );
761
- const { base, pluginExtensions, vendorAppUrl } = await loadMedusaConfig(
762
- medusaConfigPath,
763
- root,
764
- {
765
- isDevelopment,
766
- vendorUrl: pluginConfig.vendorUrl
767
- }
768
- );
769
- const srcDir = import_path5.default.join(root, "src");
770
- const backendUrl = pluginConfig.backendUrl ?? "http://localhost:9000";
771
- const imageLimit = pluginConfig.imageLimit ?? 2 * 1024 * 1024;
772
- config = {
773
- ...pluginConfig,
774
- backendUrl,
775
- base,
776
- root,
777
- srcDir,
778
- pluginExtensions,
779
- imageLimit
780
- };
781
- return {
782
- base: config.base,
783
- define: {
784
- __BACKEND_URL__: JSON.stringify(config.backendUrl),
785
- __BASE__: JSON.stringify(config.base || "/"),
786
- __VENDOR_URL__: JSON.stringify(vendorAppUrl || "")
787
- },
788
- resolve: {
789
- dedupe: ["i18next", "react-i18next", "react", "react-dom"]
790
- },
791
- optimizeDeps: {
792
- exclude: [
793
- "virtual:mercur/config",
794
- "virtual:mercur/routes",
795
- "virtual:mercur/components",
796
- "virtual:mercur/menu-items",
797
- "virtual:mercur/i18n"
798
- ],
799
- include: [
800
- "react",
801
- "react/jsx-runtime",
802
- "react-dom/client",
803
- "react-router-dom",
804
- "react-i18next",
805
- "i18next",
806
- "@medusajs/ui",
807
- "@medusajs/dashboard",
808
- "@mercurjs/client",
809
- "@tanstack/react-query"
810
- ]
811
- }
812
- };
813
- },
814
- configResolved(resolvedConfig) {
815
- root = resolvedConfig.root;
816
- },
817
- resolveId(id) {
818
- if (isVirtualModule(id)) {
819
- return resolveVirtualModule(id);
820
- }
821
- return null;
822
- },
823
- load(id) {
824
- return loadVirtualModule({ cwd: root, id, mercurConfig: config });
825
- },
826
- configureServer(server) {
827
- const handleRouteChange = (file) => {
828
- if (!isRouteFile(file)) return;
829
- const mod = server.moduleGraph.getModuleById(RESOLVED_ROUTES_MODULE);
830
- if (mod) {
831
- server.moduleGraph.invalidateModule(mod);
832
- server.ws.send({ type: "full-reload" });
833
- }
834
- };
835
- server.watcher.on("add", handleRouteChange);
836
- server.watcher.on("unlink", handleRouteChange);
837
- },
838
- handleHotUpdate({ file, server }) {
839
- if (isRouteFile(file)) {
840
- const mod = server.moduleGraph.getModuleById(RESOLVED_ROUTES_MODULE);
841
- if (mod) {
842
- server.moduleGraph.invalidateModule(mod);
843
- }
844
- }
845
- }
846
- };
847
- }
848
-
849
- // src/generate-plugin-entry.ts
850
- var import_path6 = __toESM(require("path"), 1);
851
- var import_fs5 = __toESM(require("fs"), 1);
852
- function findI18nIndex2(srcDir) {
853
- const i18nDir = import_path6.default.join(srcDir, "i18n");
854
- if (!import_fs5.default.existsSync(i18nDir)) return null;
855
- for (const ext of VALID_FILE_EXTENSIONS) {
856
- const filePath = import_path6.default.join(i18nDir, `index${ext}`);
857
- if (import_fs5.default.existsSync(filePath)) return filePath;
858
- }
859
- return null;
860
- }
861
- function generatePluginEntryModule(srcDir) {
862
- const routesDir = import_path6.default.join(srcDir, "routes");
863
- const files = crawlRoutes(routesDir);
864
- let index = 0;
865
- const routeResults = [];
866
- const menuItemResults = [];
867
- for (const file of files) {
868
- const route = parseFile(file, routesDir, index);
869
- if (route) {
870
- routeResults.push(route);
871
- }
872
- const menuItem = parseMenuItemFile(file, routesDir, index);
873
- if (menuItem) {
874
- menuItemResults.push(menuItem);
875
- }
876
- index++;
877
- }
878
- const routeTree = buildRouteTree(routeResults.filter(Boolean));
879
- const routeImports = routeTree.flatMap((r) => r.imports);
880
- const routes = routeTree.map((r) => formatRoute(r.route));
881
- const menuItemImports = menuItemResults.filter(Boolean).map((r) => r.import);
882
- const menuItems = menuItemResults.filter(Boolean).map((r) => formatMenuItem(r.menuItem));
883
- const i18nFile = findI18nIndex2(srcDir);
884
- const i18nImport = i18nFile ? `import i18nResources from "${normalizePath(i18nFile)}"` : "";
885
- const i18nValue = i18nFile ? "i18nResources" : "{}";
886
- const allImports = [...routeImports, ...menuItemImports];
887
- if (i18nImport) allImports.push(i18nImport);
888
- return `// Auto-generated plugin extensions entry
889
- ${allImports.join("\n")}
890
-
891
- const routeModule = {
892
- routes: [
893
- ${routes.join(",\n")}
894
- ]
895
- }
896
-
897
- const menuItemModule = {
898
- menuItems: [
899
- ${menuItems.join(",\n")}
900
- ]
901
- }
902
-
903
- const plugin = {
904
- routeModule,
905
- menuItemModule,
906
- i18nModule: ${i18nValue},
907
- }
908
-
909
- export default plugin
910
- `;
42
+ function defineCustomFieldsConfig(config) {
43
+ return createConfigHelper(config);
911
44
  }
912
45
  // Annotate the CommonJS export names for ESM import in node:
913
46
  0 && (module.exports = {
914
- generatePluginEntryModule,
915
- mercurDashboardPlugin
47
+ defineCustomFieldsConfig,
48
+ defineNavigationConfig,
49
+ defineWidgetConfig
916
50
  });