@vercel/microfrontends 1.0.1-canary.0 → 1.0.1-canary.1

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.
@@ -0,0 +1,1745 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
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
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/vite/index.ts
31
+ var vite_exports = {};
32
+ __export(vite_exports, {
33
+ microfrontends: () => microfrontends
34
+ });
35
+ module.exports = __toCommonJS(vite_exports);
36
+ var import_node_fs9 = require("fs");
37
+ var import_node_path9 = require("path");
38
+ var import_node_process = require("process");
39
+
40
+ // src/config/microfrontends/server/index.ts
41
+ var import_node_fs7 = __toESM(require("fs"), 1);
42
+ var import_node_path8 = require("path");
43
+
44
+ // src/config/overrides/constants.ts
45
+ var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
46
+ var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
47
+
48
+ // src/config/overrides/is-override-cookie.ts
49
+ function isOverrideCookie(cookie) {
50
+ return Boolean(cookie.name?.startsWith(OVERRIDES_COOKIE_PREFIX));
51
+ }
52
+
53
+ // src/config/overrides/get-override-from-cookie.ts
54
+ function getOverrideFromCookie(cookie) {
55
+ if (!isOverrideCookie(cookie) || !cookie.value)
56
+ return;
57
+ return {
58
+ application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
59
+ host: cookie.value
60
+ };
61
+ }
62
+
63
+ // src/config/overrides/parse-overrides.ts
64
+ function parseOverrides(cookies) {
65
+ const overridesConfig = { applications: {} };
66
+ cookies.forEach((cookie) => {
67
+ const override = getOverrideFromCookie(cookie);
68
+ if (!override)
69
+ return;
70
+ overridesConfig.applications[override.application] = {
71
+ environment: { host: override.host }
72
+ };
73
+ });
74
+ return overridesConfig;
75
+ }
76
+
77
+ // src/config/errors.ts
78
+ var MicrofrontendError = class extends Error {
79
+ constructor(message, opts) {
80
+ super(message, { cause: opts?.cause });
81
+ this.name = "MicrofrontendsError";
82
+ this.source = opts?.source ?? "@vercel/microfrontends";
83
+ this.type = opts?.type ?? "unknown";
84
+ this.subtype = opts?.subtype;
85
+ Error.captureStackTrace(this, MicrofrontendError);
86
+ }
87
+ isKnown() {
88
+ return this.type !== "unknown";
89
+ }
90
+ isUnknown() {
91
+ return !this.isKnown();
92
+ }
93
+ /**
94
+ * Converts an error to a MicrofrontendsError.
95
+ * @param original - The original error to convert.
96
+ * @returns The converted MicrofrontendsError.
97
+ */
98
+ static convert(original, opts) {
99
+ if (opts?.fileName) {
100
+ const err = MicrofrontendError.convertFSError(original, opts.fileName);
101
+ if (err) {
102
+ return err;
103
+ }
104
+ }
105
+ if (original.message.includes(
106
+ "Code generation from strings disallowed for this context"
107
+ )) {
108
+ return new MicrofrontendError(original.message, {
109
+ type: "config",
110
+ subtype: "unsupported_validation_env",
111
+ source: "ajv"
112
+ });
113
+ }
114
+ return new MicrofrontendError(original.message);
115
+ }
116
+ static convertFSError(original, fileName) {
117
+ if (original instanceof Error && "code" in original) {
118
+ if (original.code === "ENOENT") {
119
+ return new MicrofrontendError(`Could not find "${fileName}"`, {
120
+ type: "config",
121
+ subtype: "unable_to_read_file",
122
+ source: "fs"
123
+ });
124
+ }
125
+ if (original.code === "EACCES") {
126
+ return new MicrofrontendError(
127
+ `Permission denied while accessing "${fileName}"`,
128
+ {
129
+ type: "config",
130
+ subtype: "invalid_permissions",
131
+ source: "fs"
132
+ }
133
+ );
134
+ }
135
+ }
136
+ if (original instanceof SyntaxError) {
137
+ return new MicrofrontendError(
138
+ `Failed to parse "${fileName}": Invalid JSON format.`,
139
+ {
140
+ type: "config",
141
+ subtype: "invalid_syntax",
142
+ source: "fs"
143
+ }
144
+ );
145
+ }
146
+ return null;
147
+ }
148
+ /**
149
+ * Handles an unknown error and returns a MicrofrontendsError instance.
150
+ * @param err - The error to handle.
151
+ * @returns A MicrofrontendsError instance.
152
+ */
153
+ static handle(err, opts) {
154
+ if (err instanceof MicrofrontendError) {
155
+ return err;
156
+ }
157
+ if (err instanceof Error) {
158
+ return MicrofrontendError.convert(err, opts);
159
+ }
160
+ if (typeof err === "object" && err !== null) {
161
+ if ("message" in err && typeof err.message === "string") {
162
+ return MicrofrontendError.convert(new Error(err.message), opts);
163
+ }
164
+ }
165
+ return new MicrofrontendError("An unknown error occurred");
166
+ }
167
+ };
168
+
169
+ // src/config/microfrontends-config/utils/get-config-from-env.ts
170
+ function getConfigStringFromEnv() {
171
+ const config = process.env.MFE_CONFIG;
172
+ if (!config) {
173
+ throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
174
+ type: "config",
175
+ subtype: "not_found_in_env"
176
+ });
177
+ }
178
+ return config;
179
+ }
180
+
181
+ // src/config/microfrontends-config/isomorphic/index.ts
182
+ var import_jsonc_parser = require("jsonc-parser");
183
+
184
+ // src/config/schema/utils/is-main-config.ts
185
+ function isMainConfig(c) {
186
+ return !("partOf" in c);
187
+ }
188
+
189
+ // src/config/schema/utils/is-default-app.ts
190
+ function isDefaultApp(a) {
191
+ return !("routing" in a);
192
+ }
193
+
194
+ // src/config/microfrontends-config/client/index.ts
195
+ var import_path_to_regexp = require("path-to-regexp");
196
+ var MicrofrontendConfigClient = class {
197
+ constructor(config, opts) {
198
+ this.pathCache = {};
199
+ this.serialized = config;
200
+ if (opts?.removeFlaggedPaths) {
201
+ for (const app of Object.values(config.applications)) {
202
+ if (app.routing) {
203
+ app.routing = app.routing.filter((match) => !match.flag);
204
+ }
205
+ }
206
+ }
207
+ this.applications = config.applications;
208
+ }
209
+ /**
210
+ * Create a new `MicrofrontendConfigClient` from a JSON string.
211
+ * Config must be passed in to remain framework agnostic
212
+ */
213
+ static fromEnv(config, opts) {
214
+ if (!config) {
215
+ throw new Error("No microfrontends configuration found");
216
+ }
217
+ return new MicrofrontendConfigClient(
218
+ JSON.parse(config),
219
+ opts
220
+ );
221
+ }
222
+ isEqual(other) {
223
+ return JSON.stringify(this.applications) === JSON.stringify(other.applications);
224
+ }
225
+ getApplicationNameForPath(path5) {
226
+ if (!path5.startsWith("/")) {
227
+ throw new Error(`Path must start with a /`);
228
+ }
229
+ if (this.pathCache[path5]) {
230
+ return this.pathCache[path5];
231
+ }
232
+ const pathname = new URL(path5, "https://example.com").pathname;
233
+ for (const [name, application] of Object.entries(this.applications)) {
234
+ if (application.routing) {
235
+ for (const group of application.routing) {
236
+ for (const childPath of group.paths) {
237
+ const regexp = (0, import_path_to_regexp.pathToRegexp)(childPath);
238
+ if (regexp.test(pathname)) {
239
+ this.pathCache[path5] = name;
240
+ return name;
241
+ }
242
+ }
243
+ }
244
+ }
245
+ }
246
+ const defaultApplication = Object.entries(this.applications).find(
247
+ ([, application]) => application.default
248
+ );
249
+ if (!defaultApplication) {
250
+ return null;
251
+ }
252
+ this.pathCache[path5] = defaultApplication[0];
253
+ return defaultApplication[0];
254
+ }
255
+ serialize() {
256
+ return this.serialized;
257
+ }
258
+ };
259
+
260
+ // src/config/microfrontends-config/isomorphic/validation.ts
261
+ var import_path_to_regexp2 = require("path-to-regexp");
262
+ var validateConfigPaths = (applicationConfigsById) => {
263
+ if (!applicationConfigsById) {
264
+ return;
265
+ }
266
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
267
+ const errors = [];
268
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
269
+ if (isDefaultApp(app)) {
270
+ continue;
271
+ }
272
+ const childApp = app;
273
+ for (const pathMatch of childApp.routing) {
274
+ for (const path5 of pathMatch.paths) {
275
+ const maybeError = validatePathExpression(path5);
276
+ if (maybeError) {
277
+ errors.push(maybeError);
278
+ }
279
+ const existing = pathsByApplicationId.get(path5);
280
+ if (existing) {
281
+ existing.applications.push(id);
282
+ } else {
283
+ pathsByApplicationId.set(path5, {
284
+ applications: [id],
285
+ matcher: (0, import_path_to_regexp2.pathToRegexp)(path5),
286
+ applicationId: id
287
+ });
288
+ }
289
+ }
290
+ }
291
+ }
292
+ const entries = Array.from(pathsByApplicationId.entries());
293
+ for (const [path5, { applications: ids, matcher, applicationId }] of entries) {
294
+ if (ids.length > 1) {
295
+ errors.push(
296
+ `Duplicate path "${path5}" for applications "${ids.join(", ")}"`
297
+ );
298
+ }
299
+ for (const [
300
+ matchPath,
301
+ { applications: matchIds, applicationId: matchApplicationId }
302
+ ] of entries) {
303
+ if (path5 === matchPath) {
304
+ continue;
305
+ }
306
+ if (applicationId === matchApplicationId) {
307
+ continue;
308
+ }
309
+ if (matcher.test(matchPath)) {
310
+ const source = `"${path5}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
311
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
312
+ errors.push(
313
+ `Overlapping path detected between ${source} and ${destination}`
314
+ );
315
+ }
316
+ }
317
+ }
318
+ if (errors.length) {
319
+ throw new MicrofrontendError(`Invalid paths: ${errors.join(", ")}`, {
320
+ type: "config",
321
+ subtype: "conflicting_paths"
322
+ });
323
+ }
324
+ };
325
+ var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?";
326
+ function validatePathExpression(path5) {
327
+ const tokens = (0, import_path_to_regexp2.parse)(path5);
328
+ for (let i = 0; i < tokens.length; i++) {
329
+ const token = tokens[i];
330
+ if (token === void 0) {
331
+ return `token ${i} in ${path5} is undefined, this shouldn't happen`;
332
+ }
333
+ if (typeof token !== "string") {
334
+ if (token.pattern !== PATH_DEFAULT_PATTERN) {
335
+ return `Path ${path5} cannot use a regular expression wildcard`;
336
+ }
337
+ if (token.prefix !== "/") {
338
+ return `Wildcard :${token.name} must be immediately after a / in ${path5}`;
339
+ }
340
+ if (token.suffix) {
341
+ return `Wildcard suffix on :${token.name} is not allowed. Suffixes are not supported`;
342
+ }
343
+ if (token.modifier && i !== tokens.length - 1) {
344
+ return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path5}. Modifiers are only allowed in the last path component`;
345
+ }
346
+ }
347
+ }
348
+ return void 0;
349
+ }
350
+ var validateAppPaths = (name, app) => {
351
+ for (const group of app.routing) {
352
+ for (const p of group.paths) {
353
+ if (p === "/") {
354
+ continue;
355
+ }
356
+ if (p.endsWith("/")) {
357
+ throw new MicrofrontendError(
358
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
359
+ { type: "application", subtype: "invalid_path" }
360
+ );
361
+ }
362
+ if (!p.startsWith("/")) {
363
+ throw new MicrofrontendError(
364
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
365
+ { type: "application", subtype: "invalid_path" }
366
+ );
367
+ }
368
+ }
369
+ }
370
+ };
371
+ var validateConfigDefaultApplication = (applicationConfigsById) => {
372
+ if (!applicationConfigsById) {
373
+ return;
374
+ }
375
+ const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
376
+ ([, app]) => !isDefaultApp(app)
377
+ );
378
+ const applicationsWithRoutingNames = applicationsWithRouting.map(
379
+ ([key]) => key
380
+ );
381
+ const numApplications = Object.keys(applicationConfigsById).length;
382
+ const numApplicationsWithRouting = applicationsWithRoutingNames.length;
383
+ const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
384
+ if (numApplicationsWithoutRouting === 0) {
385
+ throw new MicrofrontendError(
386
+ "No default application found. At least one application needs to be the default by omitting routing.",
387
+ { type: "config", subtype: "no_default_application" }
388
+ );
389
+ }
390
+ if (numApplicationsWithoutRouting > 1) {
391
+ throw new MicrofrontendError(
392
+ `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
393
+ { type: "config", subtype: "multiple_default_applications" }
394
+ );
395
+ }
396
+ };
397
+ var validateDeprecatedFields = (config) => {
398
+ const errors = [];
399
+ if (config.options?.vercel) {
400
+ errors.push(
401
+ `Configuration cannot contain deprecated field 'options.vercel'. Use 'options.disableOverrides' instead.`
402
+ );
403
+ }
404
+ if (config.options?.localProxy) {
405
+ errors.push(
406
+ `Configuration cannot contain deprecated field 'options.localProxy'. Use 'options.localProxyPort' instead.`
407
+ );
408
+ }
409
+ for (const [applicationId, application] of Object.entries(
410
+ config.applications
411
+ )) {
412
+ if (application.vercel) {
413
+ errors.push(
414
+ `Application '${applicationId}' cannot contain deprecated field 'vercel'. Use 'projectId' instead.`
415
+ );
416
+ }
417
+ if (application.production) {
418
+ errors.push(
419
+ `Application '${applicationId}' cannot contain deprecated field 'production'. Use 'development.fallback' instead.`
420
+ );
421
+ }
422
+ if (application.development?.local) {
423
+ errors.push(
424
+ `Application '${applicationId}' cannot contain deprecated field 'development.local'. Use 'developement.localPort' instead.`
425
+ );
426
+ }
427
+ }
428
+ if (errors.length) {
429
+ throw new MicrofrontendError(
430
+ `Microfrontends configuration file errors:
431
+ - ${errors.join("\n- ")}`,
432
+ {
433
+ type: "config",
434
+ subtype: "depcrecated_field"
435
+ }
436
+ );
437
+ }
438
+ };
439
+
440
+ // src/config/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
441
+ var PREFIX = "vc-ap";
442
+ function generateAssetPrefixFromName({
443
+ name
444
+ }) {
445
+ if (!name) {
446
+ throw new Error("Name is required to generate an asset prefix");
447
+ }
448
+ return `${PREFIX}-${name}`;
449
+ }
450
+
451
+ // src/config/microfrontends-config/isomorphic/utils/generate-port.ts
452
+ function generatePortFromName({
453
+ name,
454
+ minPort = 3e3,
455
+ maxPort = 8e3
456
+ }) {
457
+ if (!name) {
458
+ throw new Error("Name is required to generate a port");
459
+ }
460
+ let hash = 0;
461
+ for (let i = 0; i < name.length; i++) {
462
+ hash = (hash << 5) - hash + name.charCodeAt(i);
463
+ hash |= 0;
464
+ }
465
+ hash = Math.abs(hash);
466
+ const range = maxPort - minPort;
467
+ const port = minPort + hash % range;
468
+ return port;
469
+ }
470
+
471
+ // src/config/microfrontends-config/isomorphic/host.ts
472
+ var Host = class {
473
+ constructor(hostConfig, options) {
474
+ if (typeof hostConfig === "string") {
475
+ ({
476
+ protocol: this.protocol,
477
+ host: this.host,
478
+ port: this.port
479
+ } = Host.parseUrl(hostConfig));
480
+ } else {
481
+ const { protocol = "https", host, port } = hostConfig;
482
+ this.protocol = protocol;
483
+ this.host = host;
484
+ this.port = port;
485
+ }
486
+ this.local = options?.isLocal;
487
+ }
488
+ static parseUrl(url) {
489
+ let hostToParse = url;
490
+ if (!/^https?:\/\//.exec(hostToParse)) {
491
+ hostToParse = `https://${hostToParse}`;
492
+ }
493
+ const parsed = new URL(hostToParse);
494
+ if (!parsed.hostname) {
495
+ throw new Error(Host.getMicrofrontendsError(url, "requires a host"));
496
+ }
497
+ if (parsed.hash) {
498
+ throw new Error(
499
+ Host.getMicrofrontendsError(url, "cannot have a fragment")
500
+ );
501
+ }
502
+ if (parsed.username || parsed.password) {
503
+ throw new Error(
504
+ Host.getMicrofrontendsError(
505
+ url,
506
+ "cannot have authentication credentials (username and/or password)"
507
+ )
508
+ );
509
+ }
510
+ if (parsed.pathname !== "/") {
511
+ throw new Error(Host.getMicrofrontendsError(url, "cannot have a path"));
512
+ }
513
+ if (parsed.search) {
514
+ throw new Error(
515
+ Host.getMicrofrontendsError(url, "cannot have query parameters")
516
+ );
517
+ }
518
+ const protocol = parsed.protocol.slice(0, -1);
519
+ return {
520
+ protocol,
521
+ host: parsed.hostname,
522
+ port: parsed.port ? Number.parseInt(parsed.port) : void 0
523
+ };
524
+ }
525
+ static getMicrofrontendsError(url, message) {
526
+ return `Microfrontends configuration error: the URL ${url} in your microfrontends.json ${message}.`;
527
+ }
528
+ isLocal() {
529
+ return this.local || this.host === "localhost" || this.host === "127.0.0.1";
530
+ }
531
+ toString() {
532
+ const url = this.toUrl();
533
+ return url.toString().replace(/\/$/, "");
534
+ }
535
+ toUrl() {
536
+ const url = `${this.protocol}://${this.host}${this.port ? `:${this.port}` : ""}`;
537
+ return new URL(url);
538
+ }
539
+ };
540
+ var LocalHost = class extends Host {
541
+ constructor({
542
+ appName,
543
+ localPort,
544
+ ...hostConfig
545
+ }) {
546
+ const host = hostConfig.host ?? "localhost";
547
+ const port = localPort ?? hostConfig.port ?? generatePortFromName({ name: appName });
548
+ const protocol = hostConfig.protocol ?? "http";
549
+ super({ protocol, host, port });
550
+ }
551
+ };
552
+
553
+ // src/config/microfrontends-config/isomorphic/application.ts
554
+ var Application = class {
555
+ constructor(name, {
556
+ app,
557
+ overrides,
558
+ isDefault
559
+ }) {
560
+ this.name = name;
561
+ this.development = {
562
+ local: new LocalHost({
563
+ appName: name,
564
+ localPort: app.development?.localPort,
565
+ ...app.development?.local
566
+ }),
567
+ fallback: app.development?.fallback ? new Host(app.development.fallback) : void 0
568
+ };
569
+ if (app.development?.fallback) {
570
+ this.fallback = new Host(app.development.fallback);
571
+ } else if (app.production) {
572
+ this.fallback = new Host(app.production);
573
+ }
574
+ this.projectId = app.projectId ?? app.vercel?.projectId;
575
+ this.overrides = overrides?.environment ? {
576
+ environment: new Host(overrides.environment)
577
+ } : void 0;
578
+ this.default = isDefault ?? false;
579
+ this.serialized = app;
580
+ }
581
+ isDefault() {
582
+ return this.default;
583
+ }
584
+ getAssetPrefix() {
585
+ return generateAssetPrefixFromName({ name: this.name });
586
+ }
587
+ serialize() {
588
+ return this.serialized;
589
+ }
590
+ };
591
+ var DefaultApplication = class extends Application {
592
+ constructor(name, {
593
+ app,
594
+ overrides
595
+ }) {
596
+ super(name, {
597
+ app,
598
+ overrides,
599
+ isDefault: true
600
+ });
601
+ this.default = true;
602
+ const fallbackHost = app.development?.fallback ?? app.production;
603
+ if (fallbackHost === void 0) {
604
+ throw new Error(
605
+ "`app.production` or `app.development.fallback` must be set in the default application in microfrontends.json."
606
+ );
607
+ }
608
+ this.fallback = new Host(fallbackHost);
609
+ if (app.production) {
610
+ this.production = new Host(app.production);
611
+ }
612
+ }
613
+ getAssetPrefix() {
614
+ return "";
615
+ }
616
+ };
617
+ var ChildApplication = class extends Application {
618
+ constructor(name, {
619
+ app,
620
+ overrides
621
+ }) {
622
+ ChildApplication.validate(name, app);
623
+ super(name, {
624
+ app,
625
+ overrides,
626
+ isDefault: false
627
+ });
628
+ this.default = false;
629
+ this.routing = app.routing;
630
+ }
631
+ static validate(name, app) {
632
+ validateAppPaths(name, app);
633
+ }
634
+ };
635
+
636
+ // src/config/microfrontends-config/isomorphic/constants.ts
637
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
638
+
639
+ // src/config/microfrontends-config/isomorphic/index.ts
640
+ var MicrofrontendConfigIsomorphic = class {
641
+ constructor({
642
+ config,
643
+ overrides,
644
+ meta,
645
+ opts
646
+ }) {
647
+ this.childApplications = {};
648
+ MicrofrontendConfigIsomorphic.validate(config, opts);
649
+ const disableOverrides = config.options?.disableOverrides ?? config.options?.vercel?.disableOverrides ?? false;
650
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
651
+ this.isMainConfig = isMainConfig(config);
652
+ if (isMainConfig(config)) {
653
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
654
+ const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0;
655
+ if (isDefaultApp(appConfig)) {
656
+ this.defaultApplication = new DefaultApplication(appId, {
657
+ app: appConfig,
658
+ overrides: appOverrides
659
+ });
660
+ } else {
661
+ this.childApplications[appId] = new ChildApplication(appId, {
662
+ app: appConfig,
663
+ overrides: appOverrides
664
+ });
665
+ }
666
+ }
667
+ } else {
668
+ this.partOf = config.partOf;
669
+ const appOverrides = !disableOverrides ? this.overrides?.applications[meta.fromApp] : void 0;
670
+ this.childApplications[meta.fromApp] = new ChildApplication(
671
+ meta.fromApp,
672
+ {
673
+ // we don't know routing because we're not in the main config
674
+ app: { routing: [] },
675
+ overrides: appOverrides
676
+ }
677
+ );
678
+ }
679
+ if (isMainConfig(config) && !this.defaultApplication) {
680
+ throw new MicrofrontendError(
681
+ "Could not find default application in microfrontends configuration",
682
+ {
683
+ type: "application",
684
+ subtype: "not_found"
685
+ }
686
+ );
687
+ }
688
+ this.config = config;
689
+ this.options = config.options;
690
+ this.serialized = {
691
+ config,
692
+ overrides,
693
+ meta
694
+ };
695
+ }
696
+ static validate(config, opts) {
697
+ const skipValidation = opts?.skipValidation ?? [];
698
+ const c = typeof config === "string" ? (0, import_jsonc_parser.parse)(config) : config;
699
+ if (isMainConfig(c)) {
700
+ if (!skipValidation.includes("paths")) {
701
+ validateConfigPaths(c.applications);
702
+ }
703
+ if (!skipValidation.includes("defaultApplication")) {
704
+ validateConfigDefaultApplication(c.applications);
705
+ }
706
+ if (!skipValidation.includes("deprecatedFields")) {
707
+ validateDeprecatedFields(c);
708
+ }
709
+ }
710
+ return c;
711
+ }
712
+ static fromEnv({
713
+ meta,
714
+ cookies
715
+ }) {
716
+ return new MicrofrontendConfigIsomorphic({
717
+ config: (0, import_jsonc_parser.parse)(getConfigStringFromEnv()),
718
+ overrides: parseOverrides(cookies ?? []),
719
+ meta
720
+ });
721
+ }
722
+ isOverridesDisabled() {
723
+ return this.options?.vercel?.disableOverrides ?? false;
724
+ }
725
+ getConfig() {
726
+ return this.config;
727
+ }
728
+ getApplicationsByType() {
729
+ return {
730
+ defaultApplication: this.defaultApplication,
731
+ applications: Object.values(this.childApplications)
732
+ };
733
+ }
734
+ getChildApplications() {
735
+ return Object.values(this.childApplications);
736
+ }
737
+ getAllApplications() {
738
+ return [
739
+ this.defaultApplication,
740
+ ...Object.values(this.childApplications)
741
+ ].filter(Boolean);
742
+ }
743
+ getApplication(name) {
744
+ if (this.defaultApplication?.name === name) {
745
+ return this.defaultApplication;
746
+ }
747
+ const app = this.childApplications[name];
748
+ if (!app) {
749
+ throw new MicrofrontendError(
750
+ `Could not find microfrontends configuration for application "${name}"`,
751
+ {
752
+ type: "application",
753
+ subtype: "not_found"
754
+ }
755
+ );
756
+ }
757
+ return app;
758
+ }
759
+ getApplicationByProjectId(projectId) {
760
+ if (this.defaultApplication?.projectId === projectId) {
761
+ return this.defaultApplication;
762
+ }
763
+ return Object.values(this.childApplications).find(
764
+ (app) => app.projectId === projectId
765
+ );
766
+ }
767
+ /**
768
+ * Returns the default application. This can throw if the default application
769
+ * is undefined ( )
770
+ */
771
+ getDefaultApplication() {
772
+ if (!this.defaultApplication) {
773
+ throw new MicrofrontendError(
774
+ "Could not find default application in microfrontends configuration",
775
+ {
776
+ type: "application",
777
+ subtype: "not_found"
778
+ }
779
+ );
780
+ }
781
+ return this.defaultApplication;
782
+ }
783
+ /**
784
+ * Returns the configured port for the local proxy
785
+ */
786
+ getLocalProxyPort() {
787
+ return this.config.options?.localProxyPort ?? this.config.options?.localProxy?.port ?? DEFAULT_LOCAL_PROXY_PORT;
788
+ }
789
+ /**
790
+ * Serializes the class back to the Schema type.
791
+ *
792
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
793
+ */
794
+ toSchemaJson() {
795
+ return this.serialized.config;
796
+ }
797
+ toClientConfig() {
798
+ const applications = Object.fromEntries(
799
+ Object.entries(this.childApplications).map(([name, application]) => [
800
+ name,
801
+ {
802
+ default: false,
803
+ routing: application.routing
804
+ }
805
+ ])
806
+ );
807
+ if (this.defaultApplication) {
808
+ applications[this.defaultApplication.name] = {
809
+ default: true
810
+ };
811
+ }
812
+ return new MicrofrontendConfigClient({
813
+ applications
814
+ });
815
+ }
816
+ serialize() {
817
+ return this.serialized;
818
+ }
819
+ };
820
+
821
+ // src/config/microfrontends-config/isomorphic/child.ts
822
+ var MicrofrontendChildConfig = class extends MicrofrontendConfigIsomorphic {
823
+ constructor({
824
+ config,
825
+ overrides,
826
+ meta
827
+ }) {
828
+ super({ config, overrides, meta });
829
+ this.isMainConfig = false;
830
+ this.partOf = config.partOf;
831
+ }
832
+ };
833
+
834
+ // src/config/microfrontends-config/isomorphic/main.ts
835
+ var MicrofrontendMainConfig = class extends MicrofrontendConfigIsomorphic {
836
+ constructor({
837
+ config,
838
+ overrides,
839
+ meta
840
+ }) {
841
+ super({ config, overrides, meta });
842
+ this.isMainConfig = true;
843
+ const disableOverrides = config.options?.disableOverrides ?? config.options?.vercel?.disableOverrides ?? false;
844
+ let defaultApplication;
845
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
846
+ const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0;
847
+ if (isDefaultApp(appConfig)) {
848
+ defaultApplication = new DefaultApplication(appId, {
849
+ app: appConfig,
850
+ overrides: appOverrides
851
+ });
852
+ } else {
853
+ this.childApplications[appId] = new ChildApplication(appId, {
854
+ app: appConfig,
855
+ overrides: appOverrides
856
+ });
857
+ }
858
+ }
859
+ if (!defaultApplication) {
860
+ throw new MicrofrontendError(
861
+ "Could not find default application in microfrontends configuration",
862
+ {
863
+ type: "application",
864
+ subtype: "not_found"
865
+ }
866
+ );
867
+ }
868
+ this.defaultApplication = defaultApplication;
869
+ }
870
+ };
871
+
872
+ // src/config/microfrontends/isomorphic/index.ts
873
+ var Microfrontends = class {
874
+ constructor({
875
+ config,
876
+ overrides,
877
+ meta
878
+ }) {
879
+ if (isMainConfig(config)) {
880
+ this.config = new MicrofrontendMainConfig({ config, overrides, meta });
881
+ } else {
882
+ this.config = new MicrofrontendChildConfig({ config, overrides, meta });
883
+ }
884
+ }
885
+ isChildConfig() {
886
+ return this.config instanceof MicrofrontendChildConfig;
887
+ }
888
+ static fromEnv({
889
+ cookies,
890
+ meta
891
+ }) {
892
+ const config = MicrofrontendConfigIsomorphic.fromEnv({
893
+ cookies,
894
+ meta
895
+ });
896
+ return new Microfrontends(config.serialize());
897
+ }
898
+ };
899
+
900
+ // src/config/microfrontends/utils/find-repository-root.ts
901
+ var import_node_fs = __toESM(require("fs"), 1);
902
+ var import_node_path = __toESM(require("path"), 1);
903
+ var GIT_DIRECTORY = ".git";
904
+ function findRepositoryRoot(startDir) {
905
+ let currentDir = startDir || process.cwd();
906
+ while (currentDir !== import_node_path.default.parse(currentDir).root) {
907
+ const gitPath = import_node_path.default.join(currentDir, GIT_DIRECTORY);
908
+ if (import_node_fs.default.existsSync(gitPath) && import_node_fs.default.statSync(gitPath).isDirectory()) {
909
+ return currentDir;
910
+ }
911
+ currentDir = import_node_path.default.dirname(currentDir);
912
+ }
913
+ throw new Error(
914
+ "Repository root not found. Specify the root of the repository with the `repository.root` option."
915
+ );
916
+ }
917
+
918
+ // src/config/microfrontends/utils/find-package-path.ts
919
+ var import_node_path2 = require("path");
920
+ var import_node_fs2 = require("fs");
921
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
922
+ var configCache = {};
923
+ function findPackagePathWithGlob({
924
+ repositoryRoot,
925
+ name
926
+ }) {
927
+ try {
928
+ const packageJsonPaths = import_fast_glob.default.globSync("**/package.json", {
929
+ cwd: repositoryRoot,
930
+ absolute: true,
931
+ onlyFiles: true,
932
+ followSymbolicLinks: false,
933
+ ignore: ["**/node_modules/**", "**/.git/**"]
934
+ });
935
+ const matchingPaths = [];
936
+ for (const packageJsonPath2 of packageJsonPaths) {
937
+ const packageJsonContent = (0, import_node_fs2.readFileSync)(packageJsonPath2, "utf-8");
938
+ const packageJson = JSON.parse(packageJsonContent);
939
+ if (packageJson.name === name) {
940
+ matchingPaths.push(packageJsonPath2);
941
+ }
942
+ }
943
+ if (matchingPaths.length > 1) {
944
+ throw new Error(
945
+ `Found multiple packages with the name "${name}" in the repository: ${matchingPaths.join(", ")}`
946
+ );
947
+ }
948
+ if (matchingPaths.length === 0) {
949
+ throw new Error(
950
+ `Could not find package with the name "${name}" in the repository`
951
+ );
952
+ }
953
+ const [packageJsonPath] = matchingPaths;
954
+ return (0, import_node_path2.dirname)(packageJsonPath);
955
+ } catch (error) {
956
+ return null;
957
+ }
958
+ }
959
+ function findPackagePath(opts) {
960
+ const cacheKey = `${opts.repositoryRoot}-${opts.name}`;
961
+ if (configCache[cacheKey]) {
962
+ return configCache[cacheKey];
963
+ }
964
+ const result = findPackagePathWithGlob(opts);
965
+ if (!result) {
966
+ throw new Error(
967
+ `Could not find package with the name "${opts.name}" in the repository`
968
+ );
969
+ }
970
+ configCache[cacheKey] = result;
971
+ return result;
972
+ }
973
+
974
+ // src/config/microfrontends/utils/find-default-package.ts
975
+ var import_node_path3 = require("path");
976
+ var import_node_fs3 = require("fs");
977
+ var import_jsonc_parser2 = require("jsonc-parser");
978
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
979
+
980
+ // src/config/constants.ts
981
+ var CONFIGURATION_FILENAMES = [
982
+ "microfrontends.jsonc",
983
+ "microfrontends.json"
984
+ ];
985
+
986
+ // src/config/microfrontends/utils/find-default-package.ts
987
+ var configCache2 = {};
988
+ function findDefaultMicrofrontendsPackages({
989
+ repositoryRoot,
990
+ applicationName
991
+ }) {
992
+ try {
993
+ const microfrontendsJsonPaths = import_fast_glob2.default.globSync(
994
+ `**/{${CONFIGURATION_FILENAMES.join(",")}}`,
995
+ {
996
+ cwd: repositoryRoot,
997
+ absolute: true,
998
+ onlyFiles: true,
999
+ followSymbolicLinks: false,
1000
+ ignore: ["**/node_modules/**", "**/.git/**"]
1001
+ }
1002
+ );
1003
+ const matchingPaths = [];
1004
+ for (const microfrontendsJsonPath of microfrontendsJsonPaths) {
1005
+ try {
1006
+ const microfrontendsJsonContent = (0, import_node_fs3.readFileSync)(
1007
+ microfrontendsJsonPath,
1008
+ "utf-8"
1009
+ );
1010
+ const microfrontendsJson = (0, import_jsonc_parser2.parse)(microfrontendsJsonContent);
1011
+ if (isMainConfig(microfrontendsJson) && microfrontendsJson.applications[applicationName]) {
1012
+ matchingPaths.push(microfrontendsJsonPath);
1013
+ }
1014
+ } catch (error) {
1015
+ }
1016
+ }
1017
+ if (matchingPaths.length > 1) {
1018
+ throw new Error(
1019
+ `Found multiple default applications referencing "${applicationName}" in the repository, this is not yet supported.
1020
+ ${matchingPaths.join("\n \u2022 ")}`
1021
+ );
1022
+ }
1023
+ if (matchingPaths.length === 0) {
1024
+ throw new Error(
1025
+ `Could not find default application with "applications.${applicationName}"`
1026
+ );
1027
+ }
1028
+ const [packageJsonPath] = matchingPaths;
1029
+ return (0, import_node_path3.dirname)(packageJsonPath);
1030
+ } catch (error) {
1031
+ return null;
1032
+ }
1033
+ }
1034
+ function findDefaultMicrofrontendsPackage(opts) {
1035
+ const cacheKey = `${opts.repositoryRoot}-${opts.applicationName}`;
1036
+ if (configCache2[cacheKey]) {
1037
+ return configCache2[cacheKey];
1038
+ }
1039
+ const result = findDefaultMicrofrontendsPackages(opts);
1040
+ if (!result) {
1041
+ throw new Error(
1042
+ "Error trying to resolve the main microfrontends configuration"
1043
+ );
1044
+ }
1045
+ configCache2[cacheKey] = result;
1046
+ return result;
1047
+ }
1048
+
1049
+ // src/config/microfrontends/utils/is-monorepo.ts
1050
+ var import_node_fs4 = __toESM(require("fs"), 1);
1051
+ var import_node_path4 = __toESM(require("path"), 1);
1052
+ function isMonorepo({
1053
+ repositoryRoot
1054
+ }) {
1055
+ try {
1056
+ if (import_node_fs4.default.existsSync(import_node_path4.default.join(repositoryRoot, "pnpm-workspace.yaml"))) {
1057
+ return true;
1058
+ }
1059
+ if (import_node_fs4.default.existsSync(import_node_path4.default.join(repositoryRoot, "vlt-workspaces.json"))) {
1060
+ return true;
1061
+ }
1062
+ const packageJsonPath = import_node_path4.default.join(repositoryRoot, "package.json");
1063
+ if (!import_node_fs4.default.existsSync(packageJsonPath)) {
1064
+ return false;
1065
+ }
1066
+ const packageJson = JSON.parse(
1067
+ import_node_fs4.default.readFileSync(packageJsonPath, "utf-8")
1068
+ );
1069
+ return packageJson.workspaces !== void 0;
1070
+ } catch (error) {
1071
+ console.error("Error determining if repository is a monorepo", error);
1072
+ return false;
1073
+ }
1074
+ }
1075
+
1076
+ // src/config/microfrontends/utils/find-package-root.ts
1077
+ var import_node_fs5 = __toESM(require("fs"), 1);
1078
+ var import_node_path5 = __toESM(require("path"), 1);
1079
+ var PACKAGE_JSON = "package.json";
1080
+ function findPackageRoot(startDir) {
1081
+ let currentDir = startDir || process.cwd();
1082
+ while (currentDir !== import_node_path5.default.parse(currentDir).root) {
1083
+ const pkgJsonPath = import_node_path5.default.join(currentDir, PACKAGE_JSON);
1084
+ if (import_node_fs5.default.existsSync(pkgJsonPath)) {
1085
+ return currentDir;
1086
+ }
1087
+ currentDir = import_node_path5.default.dirname(currentDir);
1088
+ }
1089
+ throw new Error(
1090
+ "Package root not found. Specify the root of the package with the `package.root` option."
1091
+ );
1092
+ }
1093
+
1094
+ // src/config/microfrontends/utils/find-config.ts
1095
+ var import_node_fs6 = __toESM(require("fs"), 1);
1096
+ var import_node_path6 = require("path");
1097
+ function findConfig({ dir }) {
1098
+ for (const filename of CONFIGURATION_FILENAMES) {
1099
+ const maybeConfig = (0, import_node_path6.join)(dir, filename);
1100
+ if (import_node_fs6.default.existsSync(maybeConfig)) {
1101
+ return maybeConfig;
1102
+ }
1103
+ }
1104
+ return null;
1105
+ }
1106
+
1107
+ // src/config/microfrontends/server/utils/get-output-file-path.ts
1108
+ var import_node_path7 = __toESM(require("path"), 1);
1109
+
1110
+ // src/config/microfrontends/server/constants.ts
1111
+ var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
1112
+ var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
1113
+
1114
+ // src/config/microfrontends/server/utils/get-output-file-path.ts
1115
+ function getOutputFilePath() {
1116
+ return import_node_path7.default.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
1117
+ }
1118
+
1119
+ // src/config/microfrontends/server/validation.ts
1120
+ var import_jsonc_parser3 = require("jsonc-parser");
1121
+ var import_ajv = require("ajv");
1122
+
1123
+ // schema/schema.json
1124
+ var schema_default = {
1125
+ $schema: "http://json-schema.org/draft-07/schema#",
1126
+ $ref: "#/definitions/Config",
1127
+ definitions: {
1128
+ Config: {
1129
+ anyOf: [
1130
+ {
1131
+ $ref: "#/definitions/MainConfig"
1132
+ },
1133
+ {
1134
+ $ref: "#/definitions/ChildConfig"
1135
+ }
1136
+ ]
1137
+ },
1138
+ MainConfig: {
1139
+ type: "object",
1140
+ properties: {
1141
+ $schema: {
1142
+ type: "string"
1143
+ },
1144
+ version: {
1145
+ type: "string",
1146
+ const: "1"
1147
+ },
1148
+ options: {
1149
+ $ref: "#/definitions/Options"
1150
+ },
1151
+ applications: {
1152
+ $ref: "#/definitions/ApplicationRouting",
1153
+ description: "Mapping of application names to the routes that they host. Only needs to be defined in the application that owns the primary microfrontend domain"
1154
+ }
1155
+ },
1156
+ required: [
1157
+ "applications"
1158
+ ],
1159
+ additionalProperties: false
1160
+ },
1161
+ Options: {
1162
+ type: "object",
1163
+ properties: {
1164
+ vercel: {
1165
+ $ref: "#/definitions/VercelOptions",
1166
+ description: "Microfrontends wide options for Vercel.",
1167
+ deprecated: "This is being replaced by the `disableOverrides` field below."
1168
+ },
1169
+ disableOverrides: {
1170
+ type: "boolean",
1171
+ description: "If you want to disable the overrides for the site. For example, if you are managing rewrites between applications externally, you may wish to disable the overrides on the toolbar as they will have no effect."
1172
+ },
1173
+ localProxy: {
1174
+ $ref: "#/definitions/LocalProxyOptions",
1175
+ description: "Options for local proxy.",
1176
+ deprecated: "This is being replaced by the `localProxyPort` field below."
1177
+ },
1178
+ localProxyPort: {
1179
+ type: "number",
1180
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1181
+ }
1182
+ },
1183
+ additionalProperties: false
1184
+ },
1185
+ VercelOptions: {
1186
+ type: "object",
1187
+ properties: {
1188
+ disableOverrides: {
1189
+ type: "boolean",
1190
+ description: "If you want to disable the overrides for the site. For example, if you are managing rewrites between applications externally, you may wish to disable the overrides on the toolbar as they will have no effect."
1191
+ }
1192
+ },
1193
+ additionalProperties: false
1194
+ },
1195
+ LocalProxyOptions: {
1196
+ type: "object",
1197
+ properties: {
1198
+ port: {
1199
+ type: "number",
1200
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1201
+ }
1202
+ },
1203
+ additionalProperties: false
1204
+ },
1205
+ ApplicationRouting: {
1206
+ type: "object",
1207
+ additionalProperties: {
1208
+ $ref: "#/definitions/Application"
1209
+ },
1210
+ propertyNames: {
1211
+ description: "The unique identifier for a Microfrontend Application. Must match the `name` field of the application's `package.json`."
1212
+ }
1213
+ },
1214
+ Application: {
1215
+ anyOf: [
1216
+ {
1217
+ $ref: "#/definitions/DefaultApplication"
1218
+ },
1219
+ {
1220
+ $ref: "#/definitions/ChildApplication"
1221
+ }
1222
+ ]
1223
+ },
1224
+ DefaultApplication: {
1225
+ type: "object",
1226
+ properties: {
1227
+ vercel: {
1228
+ $ref: "#/definitions/Vercel",
1229
+ deprecated: "This is being replaced by the `projectId` field below."
1230
+ },
1231
+ projectId: {
1232
+ type: "string",
1233
+ description: "Vercel project ID"
1234
+ },
1235
+ production: {
1236
+ $ref: "#/definitions/HostConfig",
1237
+ deprecated: "This is a duplicate of the `development.fallback` field and this will be removed soon."
1238
+ },
1239
+ development: {
1240
+ $ref: "#/definitions/Development"
1241
+ }
1242
+ },
1243
+ additionalProperties: false
1244
+ },
1245
+ Vercel: {
1246
+ type: "object",
1247
+ properties: {
1248
+ projectId: {
1249
+ type: "string",
1250
+ description: "Vercel project ID"
1251
+ }
1252
+ },
1253
+ required: [
1254
+ "projectId"
1255
+ ],
1256
+ additionalProperties: false
1257
+ },
1258
+ HostConfig: {
1259
+ type: "object",
1260
+ properties: {
1261
+ protocol: {
1262
+ type: "string",
1263
+ enum: [
1264
+ "http",
1265
+ "https"
1266
+ ],
1267
+ description: "The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n*"
1268
+ },
1269
+ host: {
1270
+ type: "string",
1271
+ description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1272
+ },
1273
+ port: {
1274
+ type: "number",
1275
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1276
+ }
1277
+ },
1278
+ required: [
1279
+ "host"
1280
+ ],
1281
+ additionalProperties: false
1282
+ },
1283
+ Development: {
1284
+ type: "object",
1285
+ properties: {
1286
+ local: {
1287
+ $ref: "#/definitions/LocalHostConfig",
1288
+ deprecated: "This is being replaced by the `localPort` field below."
1289
+ },
1290
+ localPort: {
1291
+ type: "number",
1292
+ description: "The local port number that this application runs on when it is running locally. Common values include `80` for HTTP and `443` for HTTPS."
1293
+ },
1294
+ fallback: {
1295
+ anyOf: [
1296
+ {
1297
+ $ref: "#/definitions/HostConfig"
1298
+ },
1299
+ {
1300
+ type: "string"
1301
+ }
1302
+ ],
1303
+ description: "Fallback for local development, could be a host config that points to any environment. If this is not provided, or the application is not running - requests to the application in local development will error.\n\nIf passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTPS. If omitted, the port defaults to `80` for HTTP and `443` for HTTPS."
1304
+ },
1305
+ task: {
1306
+ type: "string",
1307
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
1308
+ }
1309
+ },
1310
+ additionalProperties: false
1311
+ },
1312
+ LocalHostConfig: {
1313
+ type: "object",
1314
+ additionalProperties: false,
1315
+ properties: {
1316
+ host: {
1317
+ type: "string",
1318
+ description: "The hostname or IP address of the server. This can be a domain name (e.g., `example.com`) or an IP address (e.g., `192.168.1.1`)."
1319
+ },
1320
+ protocol: {
1321
+ type: "string",
1322
+ enum: [
1323
+ "http",
1324
+ "https"
1325
+ ],
1326
+ description: "The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n*"
1327
+ },
1328
+ port: {
1329
+ type: "number",
1330
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1331
+ }
1332
+ }
1333
+ },
1334
+ ChildApplication: {
1335
+ type: "object",
1336
+ properties: {
1337
+ vercel: {
1338
+ $ref: "#/definitions/Vercel",
1339
+ deprecated: "This is being replaced by the `projectId` field below."
1340
+ },
1341
+ projectId: {
1342
+ type: "string",
1343
+ description: "Vercel project ID"
1344
+ },
1345
+ production: {
1346
+ $ref: "#/definitions/HostConfig",
1347
+ deprecated: "This is a duplicate of the `development.fallback` field and this will be removed soon."
1348
+ },
1349
+ development: {
1350
+ $ref: "#/definitions/Development"
1351
+ },
1352
+ routing: {
1353
+ $ref: "#/definitions/Routing",
1354
+ description: "Groups of path expressions that are routed to this application."
1355
+ }
1356
+ },
1357
+ required: [
1358
+ "routing"
1359
+ ],
1360
+ additionalProperties: false
1361
+ },
1362
+ Routing: {
1363
+ type: "array",
1364
+ items: {
1365
+ $ref: "#/definitions/PathGroup"
1366
+ }
1367
+ },
1368
+ PathGroup: {
1369
+ type: "object",
1370
+ properties: {
1371
+ group: {
1372
+ type: "string",
1373
+ description: "Optional group name for the paths"
1374
+ },
1375
+ flag: {
1376
+ type: "string",
1377
+ description: "flag name that can be used to enable/disable all paths in the group"
1378
+ },
1379
+ paths: {
1380
+ type: "array",
1381
+ items: {
1382
+ type: "string"
1383
+ }
1384
+ }
1385
+ },
1386
+ required: [
1387
+ "paths"
1388
+ ],
1389
+ additionalProperties: false
1390
+ },
1391
+ ChildConfig: {
1392
+ type: "object",
1393
+ properties: {
1394
+ $schema: {
1395
+ type: "string"
1396
+ },
1397
+ version: {
1398
+ type: "string",
1399
+ const: "1"
1400
+ },
1401
+ options: {
1402
+ $ref: "#/definitions/Options"
1403
+ },
1404
+ partOf: {
1405
+ type: "string",
1406
+ description: "Applications that only serve a subset of the microfrontend routes only need to reference the name of the primary application that owns the full microfrontends configuration."
1407
+ }
1408
+ },
1409
+ required: [
1410
+ "partOf"
1411
+ ],
1412
+ additionalProperties: false
1413
+ }
1414
+ }
1415
+ };
1416
+
1417
+ // src/config/schema/utils/load.ts
1418
+ var SCHEMA = schema_default;
1419
+
1420
+ // src/config/microfrontends/server/validation.ts
1421
+ function filterAjvErrors(errors) {
1422
+ if (!errors) {
1423
+ return [];
1424
+ }
1425
+ return errors.filter((error) => {
1426
+ return error.keyword === "additionalProperties" || error.keyword === "required";
1427
+ });
1428
+ }
1429
+ function validateSchema(configString) {
1430
+ const parsedConfig = (0, import_jsonc_parser3.parse)(configString);
1431
+ const ajv = new import_ajv.Ajv();
1432
+ const validate = ajv.compile(SCHEMA);
1433
+ const isValid = validate(parsedConfig);
1434
+ if (!isValid) {
1435
+ throw new MicrofrontendError(
1436
+ `Invalid microfrontends config:
1437
+ - ${ajv.errorsText(filterAjvErrors(validate.errors), { separator: "\n - " })}
1438
+
1439
+ See https://openapi.vercel.sh/microfrontends.json for the schema.`,
1440
+ { type: "config", subtype: "does_not_match_schema" }
1441
+ );
1442
+ }
1443
+ return parsedConfig;
1444
+ }
1445
+
1446
+ // src/config/microfrontends/server/index.ts
1447
+ var MicrofrontendsServer = class extends Microfrontends {
1448
+ /**
1449
+ * Writes the configuration to a file.
1450
+ */
1451
+ writeConfig(opts = {
1452
+ pretty: true
1453
+ }) {
1454
+ const outputPath = getOutputFilePath();
1455
+ import_node_fs7.default.mkdirSync((0, import_node_path8.dirname)(outputPath), { recursive: true });
1456
+ import_node_fs7.default.writeFileSync(
1457
+ outputPath,
1458
+ JSON.stringify(
1459
+ this.config.toSchemaJson(),
1460
+ null,
1461
+ opts.pretty ?? true ? 2 : void 0
1462
+ )
1463
+ );
1464
+ }
1465
+ // --------- Static Methods ---------
1466
+ /**
1467
+ * Generates a MicrofrontendsServer instance from an unknown object.
1468
+ */
1469
+ static fromUnknown({
1470
+ config,
1471
+ cookies,
1472
+ meta
1473
+ }) {
1474
+ const overrides = cookies ? parseOverrides(cookies) : void 0;
1475
+ if (typeof config === "string") {
1476
+ return new MicrofrontendsServer({
1477
+ config: MicrofrontendsServer.validate(config),
1478
+ overrides,
1479
+ meta
1480
+ });
1481
+ }
1482
+ if (typeof config === "object") {
1483
+ return new MicrofrontendsServer({
1484
+ config,
1485
+ overrides,
1486
+ meta
1487
+ });
1488
+ }
1489
+ throw new MicrofrontendError(
1490
+ "Invalid config: must be a string or an object",
1491
+ { type: "config", subtype: "does_not_match_schema" }
1492
+ );
1493
+ }
1494
+ /**
1495
+ * Generates a MicrofrontendsServer instance from the environment.
1496
+ * Uses additional validation that is only available when in a node runtime
1497
+ */
1498
+ static fromEnv({
1499
+ cookies,
1500
+ meta
1501
+ }) {
1502
+ return new MicrofrontendsServer({
1503
+ config: MicrofrontendsServer.validate(getConfigStringFromEnv()),
1504
+ overrides: parseOverrides(cookies),
1505
+ meta
1506
+ });
1507
+ }
1508
+ /**
1509
+ * Validates the configuration against the JSON schema
1510
+ */
1511
+ static validate(config) {
1512
+ if (typeof config === "string") {
1513
+ const c = validateSchema(config);
1514
+ return c;
1515
+ }
1516
+ return config;
1517
+ }
1518
+ /**
1519
+ * Looks up the configuration by inferring the package root and looking for a microfrontends config file. If a file is not found,
1520
+ * it will look for a package in the repository with a microfrontends file that contains the current application
1521
+ * and use that configuration.
1522
+ *
1523
+ * This can return either a Child or Main configuration.
1524
+ */
1525
+ static infer({
1526
+ directory,
1527
+ filePath,
1528
+ meta,
1529
+ cookies,
1530
+ options
1531
+ } = {}) {
1532
+ if (filePath && meta) {
1533
+ return MicrofrontendsServer.fromFile({
1534
+ filePath,
1535
+ cookies,
1536
+ meta,
1537
+ options
1538
+ });
1539
+ }
1540
+ try {
1541
+ const packageRoot = findPackageRoot(directory);
1542
+ const packageJsonPath = (0, import_node_path8.join)(packageRoot, "package.json");
1543
+ const packageJson = JSON.parse(
1544
+ import_node_fs7.default.readFileSync(packageJsonPath, "utf-8")
1545
+ );
1546
+ if (!packageJson.name) {
1547
+ throw new Error(`No name found in package.json at ${packageJsonPath}`);
1548
+ }
1549
+ const configMeta = meta ?? { fromApp: packageJson.name };
1550
+ const maybeConfig = findConfig({ dir: packageRoot });
1551
+ if (maybeConfig) {
1552
+ return MicrofrontendsServer.fromFile({
1553
+ filePath: maybeConfig,
1554
+ cookies,
1555
+ meta: configMeta,
1556
+ options
1557
+ });
1558
+ }
1559
+ const repositoryRoot = findRepositoryRoot();
1560
+ const isMonorepo2 = isMonorepo({ repositoryRoot });
1561
+ if (isMonorepo2) {
1562
+ const defaultPackage = findDefaultMicrofrontendsPackage({
1563
+ repositoryRoot,
1564
+ applicationName: packageJson.name
1565
+ });
1566
+ const maybeConfigFromDefault = findConfig({ dir: defaultPackage });
1567
+ if (maybeConfigFromDefault) {
1568
+ return MicrofrontendsServer.fromFile({
1569
+ filePath: maybeConfigFromDefault,
1570
+ cookies,
1571
+ meta: configMeta,
1572
+ options
1573
+ });
1574
+ }
1575
+ }
1576
+ throw new Error("Unable to infer");
1577
+ } catch (e) {
1578
+ throw new MicrofrontendError(
1579
+ "Unable to locate and parse microfrontends configuration",
1580
+ { cause: e, type: "config", subtype: "inference_failed" }
1581
+ );
1582
+ }
1583
+ }
1584
+ /*
1585
+ * Generates a MicrofrontendsServer instance from a file.
1586
+ */
1587
+ static fromFile({
1588
+ filePath,
1589
+ cookies,
1590
+ meta,
1591
+ options
1592
+ }) {
1593
+ try {
1594
+ const configJson = import_node_fs7.default.readFileSync(filePath, "utf-8");
1595
+ const config = MicrofrontendsServer.validate(configJson);
1596
+ if (!isMainConfig(config) && options?.resolveMainConfig) {
1597
+ const repositoryRoot = findRepositoryRoot();
1598
+ const isMonorepo2 = isMonorepo({ repositoryRoot });
1599
+ if (isMonorepo2) {
1600
+ const packagePath = findPackagePath({
1601
+ repositoryRoot,
1602
+ name: config.partOf
1603
+ });
1604
+ if (!packagePath) {
1605
+ throw new MicrofrontendError(
1606
+ `Could not find default application "${config.partOf}" in the repository`,
1607
+ { type: "config", subtype: "not_found" }
1608
+ );
1609
+ }
1610
+ const maybeConfig = findConfig({ dir: packagePath });
1611
+ if (!maybeConfig) {
1612
+ throw new MicrofrontendError(
1613
+ `Could not find microfrontends configuration in ${packagePath}`,
1614
+ { type: "config", subtype: "not_found" }
1615
+ );
1616
+ }
1617
+ return MicrofrontendsServer.fromMainConfigFile({
1618
+ filePath: maybeConfig,
1619
+ overrides: cookies ? parseOverrides(cookies) : void 0
1620
+ });
1621
+ }
1622
+ }
1623
+ return new MicrofrontendsServer({
1624
+ config,
1625
+ overrides: cookies ? parseOverrides(cookies) : void 0,
1626
+ meta
1627
+ });
1628
+ } catch (e) {
1629
+ throw MicrofrontendError.handle(e, {
1630
+ fileName: filePath
1631
+ });
1632
+ }
1633
+ }
1634
+ /*
1635
+ * Generates a MicrofrontendMainConfig instance from a file.
1636
+ */
1637
+ static fromMainConfigFile({
1638
+ filePath,
1639
+ overrides
1640
+ }) {
1641
+ try {
1642
+ const config = import_node_fs7.default.readFileSync(filePath, "utf-8");
1643
+ const validatedConfig = MicrofrontendsServer.validate(config);
1644
+ if (!isMainConfig(validatedConfig)) {
1645
+ throw new MicrofrontendError(
1646
+ `${filePath} is not a main microfrontend config`,
1647
+ {
1648
+ type: "config",
1649
+ subtype: "invalid_main_path"
1650
+ }
1651
+ );
1652
+ }
1653
+ const [defaultApplication] = Object.entries(validatedConfig.applications).filter(([, app]) => isDefaultApp(app)).map(([name]) => name);
1654
+ if (!defaultApplication) {
1655
+ throw new MicrofrontendError(
1656
+ "No default application found. At least one application needs to be the default by omitting routing.",
1657
+ { type: "config", subtype: "no_default_application" }
1658
+ );
1659
+ }
1660
+ return new MicrofrontendsServer({
1661
+ config: validatedConfig,
1662
+ overrides,
1663
+ meta: { fromApp: defaultApplication }
1664
+ });
1665
+ } catch (e) {
1666
+ throw MicrofrontendError.handle(e, {
1667
+ fileName: filePath
1668
+ });
1669
+ }
1670
+ }
1671
+ };
1672
+
1673
+ // src/config/microfrontends/utils/get-application-context.ts
1674
+ var import_node_fs8 = __toESM(require("fs"), 1);
1675
+ function getApplicationContext(opts) {
1676
+ if (opts?.appName) {
1677
+ return { name: opts.appName };
1678
+ }
1679
+ try {
1680
+ const packageJsonString = import_node_fs8.default.readFileSync("./package.json", "utf-8");
1681
+ const packageJson = JSON.parse(packageJsonString);
1682
+ if (!packageJson.name) {
1683
+ throw new MicrofrontendError(
1684
+ `package.json file missing required field "name"`,
1685
+ {
1686
+ type: "packageJson",
1687
+ subtype: "missing_field_name",
1688
+ source: "@vercel/microfrontends/next"
1689
+ }
1690
+ );
1691
+ }
1692
+ return { name: packageJson.name };
1693
+ } catch (err) {
1694
+ throw MicrofrontendError.handle(err, {
1695
+ fileName: "package.json"
1696
+ });
1697
+ }
1698
+ }
1699
+
1700
+ // src/vite/index.ts
1701
+ function microfrontends(opts) {
1702
+ const { name: fromApp } = getApplicationContext();
1703
+ const microfrontendsObj = MicrofrontendsServer.infer({
1704
+ meta: {
1705
+ fromApp
1706
+ }
1707
+ });
1708
+ const app = microfrontendsObj.config.getApplication(fromApp);
1709
+ const additionalConfigOptions = {};
1710
+ if (!app.isDefault()) {
1711
+ if (opts?.basePath) {
1712
+ additionalConfigOptions.base = `/${opts.basePath}`;
1713
+ } else {
1714
+ const isSvelteKit = (0, import_node_fs9.existsSync)((0, import_node_path9.join)((0, import_node_process.cwd)(), "svelte.config.js"));
1715
+ if (!isSvelteKit) {
1716
+ additionalConfigOptions.experimental = {
1717
+ renderBuiltUrl(filename, { type }) {
1718
+ if (type === "asset") {
1719
+ return `/${app.getAssetPrefix()}/${filename}`;
1720
+ }
1721
+ }
1722
+ };
1723
+ }
1724
+ }
1725
+ }
1726
+ return {
1727
+ name: "vite-plugin-vercel-microfrontends",
1728
+ config: () => {
1729
+ return {
1730
+ ...additionalConfigOptions,
1731
+ define: {
1732
+ "import.meta.env.MFE_CURRENT_APPLICATION": JSON.stringify(app.name),
1733
+ "import.meta.env.MFE_CONFIG": JSON.stringify(
1734
+ microfrontendsObj.config.getConfig()
1735
+ )
1736
+ }
1737
+ };
1738
+ }
1739
+ };
1740
+ }
1741
+ // Annotate the CommonJS export names for ESM import in node:
1742
+ 0 && (module.exports = {
1743
+ microfrontends
1744
+ });
1745
+ //# sourceMappingURL=vite.cjs.map