@vercel/microfrontends 0.9.0

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 (100) hide show
  1. package/README.md +202 -0
  2. package/cli/index.cjs +21 -0
  3. package/dist/bin/cli.cjs +1604 -0
  4. package/dist/config/client.cjs +54 -0
  5. package/dist/config/client.cjs.map +1 -0
  6. package/dist/config/client.d.ts +23 -0
  7. package/dist/config/client.js +28 -0
  8. package/dist/config/client.js.map +1 -0
  9. package/dist/config/edge.cjs +508 -0
  10. package/dist/config/edge.cjs.map +1 -0
  11. package/dist/config/edge.d.ts +20 -0
  12. package/dist/config/edge.js +481 -0
  13. package/dist/config/edge.js.map +1 -0
  14. package/dist/config.cjs +1254 -0
  15. package/dist/config.cjs.map +1 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +1212 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/index-eff254d8.d.ts +175 -0
  20. package/dist/micro-frontend-config-42886104.d.ts +154 -0
  21. package/dist/next/client.cjs +3 -0
  22. package/dist/next/client.cjs.map +1 -0
  23. package/dist/next/client.d.ts +45 -0
  24. package/dist/next/client.js +3 -0
  25. package/dist/next/client.js.map +1 -0
  26. package/dist/next/config.cjs +1793 -0
  27. package/dist/next/config.cjs.map +1 -0
  28. package/dist/next/config.d.ts +22 -0
  29. package/dist/next/config.js +1758 -0
  30. package/dist/next/config.js.map +1 -0
  31. package/dist/next/endpoints.cjs +82 -0
  32. package/dist/next/endpoints.cjs.map +1 -0
  33. package/dist/next/endpoints.d.ts +15 -0
  34. package/dist/next/endpoints.js +57 -0
  35. package/dist/next/endpoints.js.map +1 -0
  36. package/dist/next/middleware.cjs +763 -0
  37. package/dist/next/middleware.cjs.map +1 -0
  38. package/dist/next/middleware.d.ts +29 -0
  39. package/dist/next/middleware.js +735 -0
  40. package/dist/next/middleware.js.map +1 -0
  41. package/dist/next/testing.cjs +1430 -0
  42. package/dist/next/testing.cjs.map +1 -0
  43. package/dist/next/testing.d.ts +53 -0
  44. package/dist/next/testing.js +1389 -0
  45. package/dist/next/testing.js.map +1 -0
  46. package/dist/overrides.cjs +143 -0
  47. package/dist/overrides.cjs.map +1 -0
  48. package/dist/overrides.d.ts +2 -0
  49. package/dist/overrides.js +115 -0
  50. package/dist/overrides.js.map +1 -0
  51. package/dist/schema-83a75e61.d.ts +188 -0
  52. package/dist/types-4fd1c7c6.d.ts +157 -0
  53. package/dist/v2/config.cjs +720 -0
  54. package/dist/v2/config.cjs.map +1 -0
  55. package/dist/v2/config.d.ts +2 -0
  56. package/dist/v2/config.js +695 -0
  57. package/dist/v2/config.js.map +1 -0
  58. package/dist/v2/microfrontends/server.cjs +1312 -0
  59. package/dist/v2/microfrontends/server.cjs.map +1 -0
  60. package/dist/v2/microfrontends/server.d.ts +48 -0
  61. package/dist/v2/microfrontends/server.js +1277 -0
  62. package/dist/v2/microfrontends/server.js.map +1 -0
  63. package/dist/v2/microfrontends.cjs +803 -0
  64. package/dist/v2/microfrontends.cjs.map +1 -0
  65. package/dist/v2/microfrontends.d.ts +44 -0
  66. package/dist/v2/microfrontends.js +776 -0
  67. package/dist/v2/microfrontends.js.map +1 -0
  68. package/dist/v2/next/client.cjs +3 -0
  69. package/dist/v2/next/client.cjs.map +1 -0
  70. package/dist/v2/next/client.d.ts +45 -0
  71. package/dist/v2/next/client.js +3 -0
  72. package/dist/v2/next/client.js.map +1 -0
  73. package/dist/v2/next/config.cjs +1829 -0
  74. package/dist/v2/next/config.cjs.map +1 -0
  75. package/dist/v2/next/config.d.ts +22 -0
  76. package/dist/v2/next/config.js +1794 -0
  77. package/dist/v2/next/config.js.map +1 -0
  78. package/dist/v2/next/endpoints.cjs +138 -0
  79. package/dist/v2/next/endpoints.cjs.map +1 -0
  80. package/dist/v2/next/endpoints.d.ts +15 -0
  81. package/dist/v2/next/endpoints.js +113 -0
  82. package/dist/v2/next/endpoints.js.map +1 -0
  83. package/dist/v2/next/middleware.cjs +1110 -0
  84. package/dist/v2/next/middleware.cjs.map +1 -0
  85. package/dist/v2/next/middleware.d.ts +29 -0
  86. package/dist/v2/next/middleware.js +1082 -0
  87. package/dist/v2/next/middleware.js.map +1 -0
  88. package/dist/v2/schema.cjs +19 -0
  89. package/dist/v2/schema.cjs.map +1 -0
  90. package/dist/v2/schema.d.ts +1 -0
  91. package/dist/v2/schema.js +1 -0
  92. package/dist/v2/schema.js.map +1 -0
  93. package/dist/validation.cjs +754 -0
  94. package/dist/validation.cjs.map +1 -0
  95. package/dist/validation.d.ts +163 -0
  96. package/dist/validation.js +726 -0
  97. package/dist/validation.js.map +1 -0
  98. package/package.json +204 -0
  99. package/schema/schema-v2.json +288 -0
  100. package/schema/schema.json +352 -0
@@ -0,0 +1,1829 @@
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/next-v2/config/index.ts
31
+ var config_exports = {};
32
+ __export(config_exports, {
33
+ withMicroFrontends: () => withMicroFrontends
34
+ });
35
+ module.exports = __toCommonJS(config_exports);
36
+ var import_node_fs2 = __toESM(require("fs"), 1);
37
+
38
+ // src/config-v2/microfrontends/server/index.ts
39
+ var import_node_fs = __toESM(require("fs"), 1);
40
+ var import_node_path2 = require("path");
41
+
42
+ // src/config-v2/overrides/constants.ts
43
+ var OVERRIDES_COOKIE_PREFIX = "vercel-microfrontends-override";
44
+ var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
45
+
46
+ // src/config-v2/overrides/is-override-cookie.ts
47
+ function isOverrideCookie(cookie) {
48
+ var _a;
49
+ return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
50
+ }
51
+
52
+ // src/config-v2/overrides/get-override-from-cookie.ts
53
+ function getOverrideFromCookie(cookie) {
54
+ if (!isOverrideCookie(cookie) || !cookie.value)
55
+ return;
56
+ return {
57
+ application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
58
+ host: cookie.value
59
+ };
60
+ }
61
+
62
+ // src/config-v2/overrides/parse-overrides.ts
63
+ function parseOverrides(cookies) {
64
+ const overridesConfig = { applications: {} };
65
+ cookies.forEach((cookie) => {
66
+ const override = getOverrideFromCookie(cookie);
67
+ if (!override)
68
+ return;
69
+ overridesConfig.applications[override.application] = {
70
+ environment: { host: override.host }
71
+ };
72
+ });
73
+ return overridesConfig;
74
+ }
75
+
76
+ // src/config-v2/errors.ts
77
+ var MicroFrontendError = class extends Error {
78
+ constructor(message, opts) {
79
+ super(message);
80
+ this.name = "MicroFrontendsError";
81
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/micro-frontends";
82
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
83
+ this.subtype = opts == null ? void 0 : opts.subtype;
84
+ Error.captureStackTrace(this, MicroFrontendError);
85
+ }
86
+ isKnown() {
87
+ return this.type !== "unknown";
88
+ }
89
+ isUnknown() {
90
+ return !this.isKnown();
91
+ }
92
+ /**
93
+ * Converts an error to a MicroFrontendsError.
94
+ * @param original - The original error to convert.
95
+ * @returns The converted MicroFrontendsError.
96
+ */
97
+ static convert(original, opts) {
98
+ if (opts == null ? void 0 : opts.fileName) {
99
+ const err = MicroFrontendError.convertFSError(original, opts.fileName);
100
+ if (err) {
101
+ return err;
102
+ }
103
+ }
104
+ if (original.message.includes(
105
+ "Code generation from strings disallowed for this context"
106
+ )) {
107
+ return new MicroFrontendError(original.message, {
108
+ type: "config",
109
+ subtype: "unsupported_validation_env",
110
+ source: "ajv"
111
+ });
112
+ }
113
+ return new MicroFrontendError(original.message);
114
+ }
115
+ static convertFSError(original, fileName) {
116
+ if (original instanceof Error && "code" in original) {
117
+ if (original.code === "ENOENT") {
118
+ return new MicroFrontendError(`Could not find "${fileName}"`, {
119
+ type: "config",
120
+ subtype: "unable_to_read_file",
121
+ source: "fs"
122
+ });
123
+ }
124
+ if (original.code === "EACCES") {
125
+ return new MicroFrontendError(
126
+ `Permission denied while accessing "${fileName}"`,
127
+ {
128
+ type: "config",
129
+ subtype: "invalid_permissions",
130
+ source: "fs"
131
+ }
132
+ );
133
+ }
134
+ }
135
+ if (original instanceof SyntaxError) {
136
+ return new MicroFrontendError(
137
+ `Failed to parse "${fileName}": Invalid JSON format.`,
138
+ {
139
+ type: "config",
140
+ subtype: "invalid_syntax",
141
+ source: "fs"
142
+ }
143
+ );
144
+ }
145
+ return null;
146
+ }
147
+ /**
148
+ * Handles an unknown error and returns a MicroFrontendsError instance.
149
+ * @param err - The error to handle.
150
+ * @returns A MicroFrontendsError instance.
151
+ */
152
+ static handle(err, opts) {
153
+ if (err instanceof MicroFrontendError) {
154
+ return err;
155
+ }
156
+ if (err instanceof Error) {
157
+ return MicroFrontendError.convert(err, opts);
158
+ }
159
+ if (typeof err === "object" && err !== null) {
160
+ if ("message" in err && typeof err.message === "string") {
161
+ return MicroFrontendError.convert(new Error(err.message), opts);
162
+ }
163
+ }
164
+ return new MicroFrontendError("An unknown error occurred");
165
+ }
166
+ };
167
+
168
+ // src/config-v2/microfrontends-config/utils/get-config-from-env.ts
169
+ function getConfigStringFromEnv() {
170
+ const config = process.env.MFE_CONFIG;
171
+ if (!config) {
172
+ throw new MicroFrontendError(`Missing "MFE_CONFIG" in environment.`, {
173
+ type: "config",
174
+ subtype: "not_found_in_env"
175
+ });
176
+ }
177
+ return config;
178
+ }
179
+
180
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
181
+ var import_jsonc_parser = require("jsonc-parser");
182
+
183
+ // src/config-v2/schema/utils/is-main-config.ts
184
+ function isMainConfig(c) {
185
+ return !("partOf" in c);
186
+ }
187
+
188
+ // src/config-v2/schema/utils/is-default-app.ts
189
+ function isDefaultApp(a) {
190
+ return !("routing" in a);
191
+ }
192
+
193
+ // src/config-v2/microfrontends-config/client/index.ts
194
+ var import_path_to_regexp = require("path-to-regexp");
195
+ var MicroFrontendConfigClient = class {
196
+ constructor(config, opts) {
197
+ this.pathCache = {};
198
+ this.serialized = config;
199
+ if (opts == null ? void 0 : opts.removeFlaggedPaths) {
200
+ for (const app of Object.values(config.applications)) {
201
+ if (app.routing) {
202
+ app.routing = app.routing.filter((match) => !match.flag);
203
+ }
204
+ }
205
+ }
206
+ this.applications = config.applications;
207
+ }
208
+ /**
209
+ * Create a new `MicroFrontendConfigClient` from a JSON string.
210
+ * Config must be passed in to remain framework agnostic
211
+ */
212
+ static fromEnv(config, opts) {
213
+ if (!config) {
214
+ throw new Error("No micro-frontends configuration found");
215
+ }
216
+ return new MicroFrontendConfigClient(
217
+ JSON.parse(config),
218
+ opts
219
+ );
220
+ }
221
+ isEqual(other) {
222
+ return JSON.stringify(this.applications) === JSON.stringify(other.applications);
223
+ }
224
+ getApplicationNameForPath(path2) {
225
+ if (!path2.startsWith("/")) {
226
+ throw new Error(`Path must start with a /`);
227
+ }
228
+ if (this.pathCache[path2]) {
229
+ return this.pathCache[path2];
230
+ }
231
+ const pathname = new URL(path2, "https://example.com").pathname;
232
+ for (const [name, application] of Object.entries(this.applications)) {
233
+ if (application.routing) {
234
+ for (const group of application.routing) {
235
+ for (const childPath of group.paths) {
236
+ const regexp = (0, import_path_to_regexp.pathToRegexp)(childPath);
237
+ if (regexp.test(pathname)) {
238
+ this.pathCache[path2] = name;
239
+ return name;
240
+ }
241
+ }
242
+ }
243
+ }
244
+ }
245
+ const defaultApplication = Object.entries(this.applications).find(
246
+ ([, application]) => application.default
247
+ );
248
+ if (!defaultApplication) {
249
+ return null;
250
+ }
251
+ this.pathCache[path2] = defaultApplication[0];
252
+ return defaultApplication[0];
253
+ }
254
+ serialize() {
255
+ return this.serialized;
256
+ }
257
+ };
258
+
259
+ // src/config-v2/microfrontends-config/isomorphic/validation.ts
260
+ var import_path_to_regexp2 = require("path-to-regexp");
261
+ var SUPPORTED_VERSIONS = ["2"];
262
+ var validateConfigVersion = (version) => {
263
+ if (!SUPPORTED_VERSIONS.includes(version)) {
264
+ throw new MicroFrontendError(
265
+ `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
266
+ ", "
267
+ )}`,
268
+ { type: "config", subtype: "unsupported_version" }
269
+ );
270
+ }
271
+ };
272
+ var validateConfigPaths = (applicationConfigsById) => {
273
+ if (!applicationConfigsById) {
274
+ return;
275
+ }
276
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
277
+ const errors = [];
278
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
279
+ if (isDefaultApp(app)) {
280
+ continue;
281
+ }
282
+ for (const pathMatch of app.routing) {
283
+ for (const path2 of pathMatch.paths) {
284
+ const tokens = (0, import_path_to_regexp2.parse)(path2);
285
+ for (const token of tokens.slice(0, -1)) {
286
+ if (typeof token !== "string") {
287
+ errors.push(
288
+ `Path ${path2} may only have a :wildcard in the last path component`
289
+ );
290
+ }
291
+ }
292
+ const existing = pathsByApplicationId.get(path2);
293
+ if (existing) {
294
+ existing.applications.push(id);
295
+ } else {
296
+ pathsByApplicationId.set(path2, {
297
+ applications: [id],
298
+ matcher: (0, import_path_to_regexp2.pathToRegexp)(path2),
299
+ applicationId: id
300
+ });
301
+ }
302
+ }
303
+ }
304
+ }
305
+ const entries = Array.from(pathsByApplicationId.entries());
306
+ entries.forEach(([path2, { applications: ids, matcher, applicationId }]) => {
307
+ if (ids.length > 1) {
308
+ errors.push(
309
+ `Duplicate path "${path2}" for applications "${ids.join(", ")}"`
310
+ );
311
+ }
312
+ entries.forEach(
313
+ ([
314
+ matchPath,
315
+ { applications: matchIds, applicationId: matchApplicationId }
316
+ ]) => {
317
+ if (path2 === matchPath) {
318
+ return;
319
+ }
320
+ if (applicationId === matchApplicationId) {
321
+ return;
322
+ }
323
+ if (matcher.test(matchPath)) {
324
+ const source = `"${path2}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
325
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
326
+ errors.push(
327
+ `Overlapping path detected between ${source} and ${destination}`
328
+ );
329
+ }
330
+ }
331
+ );
332
+ });
333
+ if (errors.length) {
334
+ throw new MicroFrontendError(`Invalid paths: ${errors.join(", ")}`, {
335
+ type: "config",
336
+ subtype: "conflicting_paths"
337
+ });
338
+ }
339
+ };
340
+ var validateAppPaths = (name, app) => {
341
+ for (const group of app.routing) {
342
+ for (const p of group.paths) {
343
+ if (p === "/") {
344
+ continue;
345
+ }
346
+ if (p.endsWith("/")) {
347
+ throw new MicroFrontendError(
348
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
349
+ { type: "application", subtype: "invalid_path" }
350
+ );
351
+ }
352
+ if (!p.startsWith("/")) {
353
+ throw new MicroFrontendError(
354
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
355
+ { type: "application", subtype: "invalid_path" }
356
+ );
357
+ }
358
+ }
359
+ }
360
+ };
361
+ var validateConfigDefaultApplication = (applicationConfigsById) => {
362
+ if (!applicationConfigsById) {
363
+ return;
364
+ }
365
+ const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
366
+ ([, app]) => !isDefaultApp(app)
367
+ );
368
+ const applicationsWithRoutingNames = applicationsWithRouting.map(
369
+ ([key]) => key
370
+ );
371
+ const numApplications = Object.keys(applicationConfigsById).length;
372
+ const numApplicationsWithRouting = applicationsWithRoutingNames.length;
373
+ const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
374
+ if (numApplicationsWithoutRouting === 0) {
375
+ throw new MicroFrontendError(
376
+ `No default application found. At least one application needs to be the default by omitting routing.`,
377
+ { type: "config", subtype: "no_default_application" }
378
+ );
379
+ }
380
+ if (numApplicationsWithoutRouting > 1) {
381
+ throw new MicroFrontendError(
382
+ `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
383
+ { type: "config", subtype: "multiple_default_applications" }
384
+ );
385
+ }
386
+ };
387
+ var validateConfigOptions = (options) => {
388
+ var _a;
389
+ if ((_a = options == null ? void 0 : options.vercel) == null ? void 0 : _a.previewDeploymentSuffix) {
390
+ if (!/^[a-zA-Z]{2,}\.[a-zA-Z]{2,}$/.test(
391
+ options.vercel.previewDeploymentSuffix
392
+ )) {
393
+ throw new MicroFrontendError(
394
+ `Invalid preview deployment suffix: ${options.vercel.previewDeploymentSuffix}. Should have be formatted like "vercel.app".`,
395
+ { type: "config", subtype: "invalid_preview_deployment_suffix" }
396
+ );
397
+ }
398
+ }
399
+ };
400
+
401
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
402
+ var PREFIX = "vc-ap";
403
+ function generateAssetPrefixFromName({
404
+ name
405
+ }) {
406
+ if (!name) {
407
+ throw new Error("Name is required to generate an asset prefix");
408
+ }
409
+ return `${PREFIX}-${name}`;
410
+ }
411
+
412
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-port.ts
413
+ function generatePortFromName({
414
+ name,
415
+ minPort = 3e3,
416
+ maxPort = 8e3
417
+ }) {
418
+ if (!name) {
419
+ throw new Error("Name is required to generate a port");
420
+ }
421
+ let hash = 0;
422
+ for (let i = 0; i < name.length; i++) {
423
+ hash = (hash << 5) - hash + name.charCodeAt(i);
424
+ hash |= 0;
425
+ }
426
+ hash = Math.abs(hash);
427
+ const range = maxPort - minPort;
428
+ const port = minPort + hash % range;
429
+ return port;
430
+ }
431
+
432
+ // src/config-v2/microfrontends-config/isomorphic/host.ts
433
+ var Host = class {
434
+ constructor(hostConfig, options) {
435
+ const { protocol = "https", host, port } = hostConfig;
436
+ this.protocol = protocol;
437
+ this.host = host;
438
+ this.port = Host.getPort({ port, protocol: this.protocol });
439
+ this.local = options == null ? void 0 : options.isLocal;
440
+ }
441
+ isLocal() {
442
+ return this.local || this.host === "localhost" || this.host === "127.0.0.1";
443
+ }
444
+ static getPort({
445
+ protocol,
446
+ port
447
+ }) {
448
+ if (!port) {
449
+ if (protocol === "http") {
450
+ return 80;
451
+ }
452
+ return 443;
453
+ }
454
+ return port;
455
+ }
456
+ isDefaultPort() {
457
+ return this.port === Host.getPort({ protocol: this.protocol });
458
+ }
459
+ toString(opts = {}) {
460
+ const url = this.toUrl(opts);
461
+ return url.toString().replace(/\/$/, "");
462
+ }
463
+ toUrl(opts = {}) {
464
+ const { includeDefaultPort } = opts;
465
+ const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
466
+ return new URL(url);
467
+ }
468
+ };
469
+ var LocalHost = class extends Host {
470
+ constructor({
471
+ appName,
472
+ ...hostConfig
473
+ }) {
474
+ const host = hostConfig.host ?? "localhost";
475
+ const port = hostConfig.port ?? generatePortFromName({ name: appName });
476
+ const protocol = hostConfig.protocol ?? "http";
477
+ super({ protocol, host, port });
478
+ }
479
+ };
480
+
481
+ // src/config-v2/microfrontends-config/isomorphic/application.ts
482
+ var Application = class {
483
+ constructor(name, {
484
+ app,
485
+ overrides,
486
+ isDefault
487
+ }) {
488
+ var _a, _b;
489
+ this.name = name;
490
+ this.development = {
491
+ local: new LocalHost({
492
+ appName: name,
493
+ ...(_a = app.development) == null ? void 0 : _a.local
494
+ }),
495
+ fallback: ((_b = app.development) == null ? void 0 : _b.fallback) ? new Host(app.development.fallback) : void 0
496
+ };
497
+ this.production = app.production ? new Host(app.production) : void 0;
498
+ this.vercel = app.vercel;
499
+ this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
500
+ environment: new Host(overrides.environment)
501
+ } : void 0;
502
+ this.default = isDefault ?? false;
503
+ this.serialized = app;
504
+ }
505
+ isDefault() {
506
+ return this.default;
507
+ }
508
+ getAssetPrefix() {
509
+ return generateAssetPrefixFromName({ name: this.name });
510
+ }
511
+ serialize() {
512
+ return this.serialized;
513
+ }
514
+ };
515
+ var DefaultApplication = class extends Application {
516
+ constructor(name, {
517
+ app,
518
+ overrides
519
+ }) {
520
+ super(name, {
521
+ app,
522
+ overrides,
523
+ isDefault: true
524
+ });
525
+ this.default = true;
526
+ this.production = new Host(app.production);
527
+ }
528
+ };
529
+ var ChildApplication = class extends Application {
530
+ constructor(name, {
531
+ app,
532
+ overrides
533
+ }) {
534
+ ChildApplication.validate(name, app);
535
+ super(name, {
536
+ app,
537
+ overrides,
538
+ isDefault: false
539
+ });
540
+ this.default = false;
541
+ this.routing = app.routing;
542
+ }
543
+ static validate(name, app) {
544
+ validateAppPaths(name, app);
545
+ }
546
+ };
547
+
548
+ // src/config-v2/microfrontends-config/isomorphic/constants.ts
549
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
550
+
551
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
552
+ var MicroFrontendConfigIsomorphic = class {
553
+ constructor({
554
+ config,
555
+ overrides,
556
+ meta
557
+ }) {
558
+ this.childApplications = {};
559
+ var _a, _b, _c, _d;
560
+ MicroFrontendConfigIsomorphic.validate(config);
561
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
562
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
563
+ this.isMainConfig = isMainConfig(config);
564
+ if (isMainConfig(config)) {
565
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
566
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
567
+ if (isDefaultApp(appConfig)) {
568
+ this.defaultApplication = new DefaultApplication(appId, {
569
+ app: appConfig,
570
+ overrides: appOverrides
571
+ });
572
+ } else {
573
+ this.childApplications[appId] = new ChildApplication(appId, {
574
+ app: appConfig,
575
+ overrides: appOverrides
576
+ });
577
+ }
578
+ }
579
+ } else {
580
+ this.partOf = config.partOf;
581
+ const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
582
+ this.childApplications[meta.fromApp] = new ChildApplication(
583
+ meta.fromApp,
584
+ {
585
+ // we don't know routing because we're not in the main config
586
+ app: { routing: [] },
587
+ overrides: appOverrides
588
+ }
589
+ );
590
+ }
591
+ if (isMainConfig(config) && !this.defaultApplication) {
592
+ throw new MicroFrontendError(
593
+ `Could not find default application in microfrontends configuration`,
594
+ {
595
+ type: "application",
596
+ subtype: "not_found"
597
+ }
598
+ );
599
+ }
600
+ this.config = config;
601
+ this.options = config.options;
602
+ this.serialized = {
603
+ config,
604
+ overrides,
605
+ meta
606
+ };
607
+ }
608
+ static validate(config) {
609
+ const c = typeof config === "string" ? (0, import_jsonc_parser.parse)(config) : config;
610
+ if (isMainConfig(c)) {
611
+ validateConfigVersion(c.version);
612
+ validateConfigPaths(c.applications);
613
+ validateConfigDefaultApplication(c.applications);
614
+ }
615
+ validateConfigOptions(c.options);
616
+ return c;
617
+ }
618
+ static fromEnv({
619
+ meta,
620
+ cookies
621
+ }) {
622
+ return new MicroFrontendConfigIsomorphic({
623
+ config: (0, import_jsonc_parser.parse)(getConfigStringFromEnv()),
624
+ overrides: parseOverrides(cookies ?? []),
625
+ meta
626
+ });
627
+ }
628
+ isOverridesDisabled() {
629
+ var _a, _b;
630
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
631
+ }
632
+ getConfig() {
633
+ return this.config;
634
+ }
635
+ getApplicationsByType() {
636
+ return {
637
+ defaultApplication: this.defaultApplication,
638
+ applications: Object.values(this.childApplications)
639
+ };
640
+ }
641
+ getChildApplications() {
642
+ return Object.values(this.childApplications);
643
+ }
644
+ getAllApplications() {
645
+ return [
646
+ this.defaultApplication,
647
+ ...Object.values(this.childApplications)
648
+ ].filter(Boolean);
649
+ }
650
+ getApplication(name) {
651
+ var _a;
652
+ if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
653
+ return this.defaultApplication;
654
+ }
655
+ const app = this.childApplications[name];
656
+ if (!app) {
657
+ throw new MicroFrontendError(
658
+ `Could not find microfrontends configuration for application "${name}"`,
659
+ {
660
+ type: "application",
661
+ subtype: "not_found"
662
+ }
663
+ );
664
+ }
665
+ return app;
666
+ }
667
+ getApplicationByProjectId(projectId) {
668
+ var _a, _b;
669
+ if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
670
+ return this.defaultApplication;
671
+ }
672
+ return Object.values(this.childApplications).find(
673
+ (app) => {
674
+ var _a2;
675
+ return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
676
+ }
677
+ );
678
+ }
679
+ /**
680
+ * Returns the default application. This can throw if the default application
681
+ * is undefined ( )
682
+ */
683
+ getDefaultApplication() {
684
+ if (!this.defaultApplication) {
685
+ throw new MicroFrontendError(
686
+ `Could not find default application in microfrontends configuration`,
687
+ {
688
+ type: "application",
689
+ subtype: "not_found"
690
+ }
691
+ );
692
+ }
693
+ return this.defaultApplication;
694
+ }
695
+ /**
696
+ * Returns the configured port for the local proxy
697
+ */
698
+ getLocalProxyPort() {
699
+ var _a, _b;
700
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
701
+ }
702
+ /**
703
+ * Serializes the class back to the Schema type.
704
+ *
705
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
706
+ */
707
+ toSchemaJson() {
708
+ return this.serialized.config;
709
+ }
710
+ toClientConfig() {
711
+ const applications = Object.fromEntries(
712
+ Object.entries(this.childApplications).map(([name, application]) => [
713
+ name,
714
+ {
715
+ default: false,
716
+ routing: application.routing
717
+ }
718
+ ])
719
+ );
720
+ if (this.defaultApplication) {
721
+ applications[this.defaultApplication.name] = {
722
+ default: true
723
+ };
724
+ }
725
+ return new MicroFrontendConfigClient({
726
+ applications
727
+ });
728
+ }
729
+ serialize() {
730
+ return this.serialized;
731
+ }
732
+ };
733
+
734
+ // src/config-v2/microfrontends-config/isomorphic/child.ts
735
+ var MicroFrontendChildConfig = class extends MicroFrontendConfigIsomorphic {
736
+ constructor({
737
+ config,
738
+ overrides,
739
+ meta
740
+ }) {
741
+ super({ config, overrides, meta });
742
+ this.isMainConfig = false;
743
+ this.partOf = config.partOf;
744
+ }
745
+ };
746
+
747
+ // src/config-v2/microfrontends-config/isomorphic/main.ts
748
+ var MicroFrontendMainConfig = class extends MicroFrontendConfigIsomorphic {
749
+ constructor({
750
+ config,
751
+ overrides,
752
+ meta
753
+ }) {
754
+ var _a, _b, _c;
755
+ super({ config, overrides, meta });
756
+ this.isMainConfig = true;
757
+ this.provider = config.provider;
758
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
759
+ let defaultApplication;
760
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
761
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
762
+ if (isDefaultApp(appConfig)) {
763
+ defaultApplication = new DefaultApplication(appId, {
764
+ app: appConfig,
765
+ overrides: appOverrides
766
+ });
767
+ } else {
768
+ this.childApplications[appId] = new ChildApplication(appId, {
769
+ app: appConfig,
770
+ overrides: appOverrides
771
+ });
772
+ }
773
+ }
774
+ if (!defaultApplication) {
775
+ throw new MicroFrontendError(
776
+ `Could not find default application in microfrontends configuration`,
777
+ {
778
+ type: "application",
779
+ subtype: "not_found"
780
+ }
781
+ );
782
+ }
783
+ this.defaultApplication = defaultApplication;
784
+ }
785
+ };
786
+
787
+ // src/config-v2/microfrontends/isomorphic/index.ts
788
+ var Microfrontends = class {
789
+ constructor({
790
+ config,
791
+ overrides,
792
+ meta
793
+ }) {
794
+ if (isMainConfig(config)) {
795
+ this.config = new MicroFrontendMainConfig({ config, overrides, meta });
796
+ } else {
797
+ this.config = new MicroFrontendChildConfig({ config, overrides, meta });
798
+ }
799
+ }
800
+ isChildConfig() {
801
+ return this.config instanceof MicroFrontendChildConfig;
802
+ }
803
+ static fromEnv({
804
+ cookies,
805
+ meta
806
+ }) {
807
+ const config = MicroFrontendConfigIsomorphic.fromEnv({
808
+ cookies,
809
+ meta
810
+ });
811
+ return new Microfrontends(config.serialize());
812
+ }
813
+ };
814
+
815
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
816
+ var import_node_path = __toESM(require("path"), 1);
817
+
818
+ // src/config-v2/microfrontends/server/constants.ts
819
+ var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
820
+ var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
821
+
822
+ // src/utils/is-vercel.ts
823
+ function isVercel() {
824
+ return process.env.VERCEL === "1";
825
+ }
826
+
827
+ // src/config-v2/microfrontends/server/utils/get-output-file-path.ts
828
+ function getOutputFilePath() {
829
+ if (isVercel()) {
830
+ return import_node_path.default.join(
831
+ ".vercel",
832
+ MFE_CONFIG_DEFAULT_FILE_PATH,
833
+ MFE_CONFIG_DEFAULT_FILE_NAME
834
+ );
835
+ }
836
+ return import_node_path.default.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
837
+ }
838
+
839
+ // src/config-v2/microfrontends/server/validation.ts
840
+ var import_jsonc_parser2 = require("jsonc-parser");
841
+ var import_ajv = require("ajv");
842
+
843
+ // src/config/errors.ts
844
+ var MicroFrontendError2 = class extends Error {
845
+ constructor(message, opts) {
846
+ super(message);
847
+ this.name = "MicroFrontendsError";
848
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/micro-frontends";
849
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
850
+ this.subtype = opts == null ? void 0 : opts.subtype;
851
+ Error.captureStackTrace(this, MicroFrontendError2);
852
+ }
853
+ isKnown() {
854
+ return this.type !== "unknown";
855
+ }
856
+ isUnknown() {
857
+ return !this.isKnown();
858
+ }
859
+ /**
860
+ * Converts an error to a MicroFrontendsError.
861
+ * @param original - The original error to convert.
862
+ * @returns The converted MicroFrontendsError.
863
+ */
864
+ static convert(original, opts) {
865
+ if (opts == null ? void 0 : opts.fileName) {
866
+ const err = MicroFrontendError2.convertFSError(original, opts.fileName);
867
+ if (err) {
868
+ return err;
869
+ }
870
+ }
871
+ if (original.message.includes(
872
+ "Code generation from strings disallowed for this context"
873
+ )) {
874
+ return new MicroFrontendError2(original.message, {
875
+ type: "config",
876
+ subtype: "unsupported_validation_env",
877
+ source: "ajv"
878
+ });
879
+ }
880
+ return new MicroFrontendError2(original.message);
881
+ }
882
+ static convertFSError(original, fileName) {
883
+ if (original instanceof Error && "code" in original) {
884
+ if (original.code === "ENOENT") {
885
+ return new MicroFrontendError2(`Could not find "${fileName}"`, {
886
+ type: "config",
887
+ subtype: "unable_to_read_file",
888
+ source: "fs"
889
+ });
890
+ }
891
+ if (original.code === "EACCES") {
892
+ return new MicroFrontendError2(
893
+ `Permission denied while accessing "${fileName}"`,
894
+ {
895
+ type: "config",
896
+ subtype: "invalid_permissions",
897
+ source: "fs"
898
+ }
899
+ );
900
+ }
901
+ }
902
+ if (original instanceof SyntaxError) {
903
+ return new MicroFrontendError2(
904
+ `Failed to parse "${fileName}": Invalid JSON format.`,
905
+ {
906
+ type: "config",
907
+ subtype: "invalid_syntax",
908
+ source: "fs"
909
+ }
910
+ );
911
+ }
912
+ return null;
913
+ }
914
+ /**
915
+ * Handles an unknown error and returns a MicroFrontendsError instance.
916
+ * @param err - The error to handle.
917
+ * @returns A MicroFrontendsError instance.
918
+ */
919
+ static handle(err, opts) {
920
+ if (err instanceof MicroFrontendError2) {
921
+ return err;
922
+ }
923
+ if (err instanceof Error) {
924
+ return MicroFrontendError2.convert(err, opts);
925
+ }
926
+ if (typeof err === "object" && err !== null) {
927
+ if ("message" in err && typeof err.message === "string") {
928
+ return MicroFrontendError2.convert(new Error(err.message), opts);
929
+ }
930
+ }
931
+ return new MicroFrontendError2("An unknown error occurred");
932
+ }
933
+ };
934
+
935
+ // schema/schema-v2.json
936
+ var schema_v2_default = {
937
+ $schema: "http://json-schema.org/draft-07/schema#",
938
+ $ref: "#/definitions/Config",
939
+ definitions: {
940
+ Config: {
941
+ anyOf: [
942
+ {
943
+ $ref: "#/definitions/MainConfig"
944
+ },
945
+ {
946
+ $ref: "#/definitions/ChildConfig"
947
+ }
948
+ ]
949
+ },
950
+ MainConfig: {
951
+ type: "object",
952
+ properties: {
953
+ $schema: {
954
+ type: "string"
955
+ },
956
+ version: {
957
+ type: "string",
958
+ const: "2"
959
+ },
960
+ options: {
961
+ $ref: "#/definitions/Options"
962
+ },
963
+ remotes: {
964
+ type: "object",
965
+ additionalProperties: {
966
+ $ref: "#/definitions/Application"
967
+ },
968
+ 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."
969
+ },
970
+ provider: {
971
+ $ref: "#/definitions/Provider"
972
+ },
973
+ applications: {
974
+ $ref: "#/definitions/ApplicationRouting",
975
+ 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"
976
+ }
977
+ },
978
+ required: ["applications", "provider", "version"]
979
+ },
980
+ Options: {
981
+ type: "object",
982
+ properties: {
983
+ vercel: {
984
+ $ref: "#/definitions/VercelOptions",
985
+ description: "Micro-Frontends wide options for Vercel."
986
+ },
987
+ localProxy: {
988
+ $ref: "#/definitions/LocalProxyOptions",
989
+ description: "Options for local proxy."
990
+ }
991
+ }
992
+ },
993
+ VercelOptions: {
994
+ type: "object",
995
+ properties: {
996
+ previewDeploymentSuffix: {
997
+ type: "string",
998
+ description: "If your team uses a custom Preview Deployment Suffix, please specify it here. See https://vercel.com/docs/deployments/preview-deployment-suffix. The default is `vercel.app`."
999
+ },
1000
+ teamSlug: {
1001
+ type: "string",
1002
+ description: "Team slug for the Vercel team"
1003
+ },
1004
+ disableOverrides: {
1005
+ type: "boolean",
1006
+ 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."
1007
+ }
1008
+ }
1009
+ },
1010
+ LocalProxyOptions: {
1011
+ type: "object",
1012
+ properties: {
1013
+ port: {
1014
+ type: "number",
1015
+ description: "The port number used by the local proxy server.\n\nThe default is `3024`."
1016
+ }
1017
+ }
1018
+ },
1019
+ Application: {
1020
+ anyOf: [
1021
+ {
1022
+ $ref: "#/definitions/DefaultApplication"
1023
+ },
1024
+ {
1025
+ $ref: "#/definitions/ChildApplication"
1026
+ }
1027
+ ]
1028
+ },
1029
+ DefaultApplication: {
1030
+ type: "object",
1031
+ properties: {
1032
+ vercel: {
1033
+ $ref: "#/definitions/Vercel"
1034
+ },
1035
+ development: {
1036
+ $ref: "#/definitions/Development"
1037
+ },
1038
+ production: {
1039
+ $ref: "#/definitions/HostConfig"
1040
+ }
1041
+ },
1042
+ required: ["production"]
1043
+ },
1044
+ Vercel: {
1045
+ type: "object",
1046
+ properties: {
1047
+ projectId: {
1048
+ type: "string",
1049
+ description: "Vercel project ID"
1050
+ },
1051
+ routeSpeedInsightsToDefaultZone: {
1052
+ type: "boolean"
1053
+ }
1054
+ },
1055
+ required: ["projectId"]
1056
+ },
1057
+ Development: {
1058
+ type: "object",
1059
+ properties: {
1060
+ local: {
1061
+ $ref: "#/definitions/LocalHostConfig"
1062
+ },
1063
+ fallback: {
1064
+ $ref: "#/definitions/HostConfig",
1065
+ 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."
1066
+ },
1067
+ task: {
1068
+ type: "string",
1069
+ description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
1070
+ }
1071
+ }
1072
+ },
1073
+ LocalHostConfig: {
1074
+ type: "object",
1075
+ properties: {
1076
+ host: {
1077
+ type: "string",
1078
+ 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`)."
1079
+ },
1080
+ protocol: {
1081
+ type: "string",
1082
+ enum: ["http", "https"],
1083
+ description: 'The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n* @defaultValue "http" for local development, "https" for otherwise'
1084
+ },
1085
+ port: {
1086
+ type: "number",
1087
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1088
+ }
1089
+ }
1090
+ },
1091
+ HostConfig: {
1092
+ type: "object",
1093
+ properties: {
1094
+ protocol: {
1095
+ type: "string",
1096
+ enum: ["http", "https"],
1097
+ description: 'The protocol to be used for the connection.\n- `http`: Hypertext Transfer Protocol (HTTP).\n- `https`: Secure Hypertext Transfer Protocol (HTTPS).\n\n* @defaultValue "http" for local development, "https" for otherwise'
1098
+ },
1099
+ host: {
1100
+ type: "string",
1101
+ 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`)."
1102
+ },
1103
+ port: {
1104
+ type: "number",
1105
+ description: "The port number to be used for the connection. Common values include `80` for HTTP and `443` for HTTPS."
1106
+ }
1107
+ },
1108
+ required: ["host"]
1109
+ },
1110
+ ChildApplication: {
1111
+ type: "object",
1112
+ properties: {
1113
+ vercel: {
1114
+ $ref: "#/definitions/Vercel"
1115
+ },
1116
+ development: {
1117
+ $ref: "#/definitions/Development"
1118
+ },
1119
+ routing: {
1120
+ $ref: "#/definitions/Routing",
1121
+ description: "Groups of path expressions that are routed to this application."
1122
+ },
1123
+ production: {
1124
+ $ref: "#/definitions/HostConfig"
1125
+ }
1126
+ },
1127
+ required: ["routing"]
1128
+ },
1129
+ Routing: {
1130
+ type: "array",
1131
+ items: {
1132
+ $ref: "#/definitions/PathGroup"
1133
+ }
1134
+ },
1135
+ PathGroup: {
1136
+ type: "object",
1137
+ properties: {
1138
+ group: {
1139
+ type: "string",
1140
+ description: "Optional group name for the paths"
1141
+ },
1142
+ flag: {
1143
+ type: "string",
1144
+ description: "flag name that can be used to enable/disable all paths in the group"
1145
+ },
1146
+ routeToDefaultApplication: {
1147
+ type: "boolean",
1148
+ description: "True to route the request to the default application for this micro-frontends set-up. This must be `true` when using `flag` or when you want to use custom logic to make the routing decision for this group of paths."
1149
+ },
1150
+ paths: {
1151
+ type: "array",
1152
+ items: {
1153
+ type: "string"
1154
+ }
1155
+ }
1156
+ },
1157
+ required: ["paths"]
1158
+ },
1159
+ Provider: {
1160
+ type: "string",
1161
+ enum: ["vercel", "other"]
1162
+ },
1163
+ ApplicationRouting: {
1164
+ type: "object",
1165
+ additionalProperties: {
1166
+ $ref: "#/definitions/Application"
1167
+ }
1168
+ },
1169
+ ChildConfig: {
1170
+ type: "object",
1171
+ properties: {
1172
+ $schema: {
1173
+ type: "string"
1174
+ },
1175
+ version: {
1176
+ type: "string",
1177
+ const: "2"
1178
+ },
1179
+ options: {
1180
+ $ref: "#/definitions/Options"
1181
+ },
1182
+ remotes: {
1183
+ type: "object",
1184
+ additionalProperties: {
1185
+ $ref: "#/definitions/Application"
1186
+ },
1187
+ 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."
1188
+ },
1189
+ partOf: {
1190
+ type: "string",
1191
+ 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."
1192
+ }
1193
+ },
1194
+ required: ["partOf", "version"]
1195
+ }
1196
+ }
1197
+ };
1198
+
1199
+ // src/config-v2/schema/utils/load.ts
1200
+ var SCHEMA = schema_v2_default;
1201
+
1202
+ // src/config-v2/microfrontends/server/validation.ts
1203
+ function validateSchema(configString) {
1204
+ const parsedConfig = (0, import_jsonc_parser2.parse)(configString);
1205
+ const ajv = new import_ajv.Ajv();
1206
+ const validate = ajv.compile(SCHEMA);
1207
+ const isValid = validate(parsedConfig);
1208
+ if (!isValid) {
1209
+ throw new MicroFrontendError2(
1210
+ `Invalid config: ${ajv.errorsText(validate.errors)}`,
1211
+ { type: "config", subtype: "does_not_match_schema" }
1212
+ );
1213
+ }
1214
+ return parsedConfig;
1215
+ }
1216
+
1217
+ // src/config-v2/microfrontends/server/index.ts
1218
+ var MicrofrontendsServer = class extends Microfrontends {
1219
+ /**
1220
+ * Writes the configuration to a file.
1221
+ */
1222
+ writeConfig(opts = {
1223
+ pretty: true
1224
+ }) {
1225
+ const outputPath = getOutputFilePath();
1226
+ import_node_fs.default.mkdirSync((0, import_node_path2.dirname)(outputPath), { recursive: true });
1227
+ import_node_fs.default.writeFileSync(
1228
+ outputPath,
1229
+ JSON.stringify(
1230
+ this.config.toSchemaJson(),
1231
+ null,
1232
+ opts.pretty ?? true ? 2 : void 0
1233
+ )
1234
+ );
1235
+ }
1236
+ // --------- Static Methods ---------
1237
+ /**
1238
+ * Generates a MicrofrontendsServer instance from an unknown object.
1239
+ */
1240
+ static fromUnknown({
1241
+ config,
1242
+ cookies,
1243
+ meta
1244
+ }) {
1245
+ const overrides = cookies ? parseOverrides(cookies) : void 0;
1246
+ if (typeof config === "string") {
1247
+ return new MicrofrontendsServer({
1248
+ config: MicrofrontendsServer.validate(config),
1249
+ overrides,
1250
+ meta
1251
+ });
1252
+ }
1253
+ if (typeof config === "object") {
1254
+ return new MicrofrontendsServer({
1255
+ config,
1256
+ overrides,
1257
+ meta
1258
+ });
1259
+ }
1260
+ throw new MicroFrontendError(
1261
+ "Invalid config: must be a string or an object",
1262
+ { type: "config", subtype: "does_not_match_schema" }
1263
+ );
1264
+ }
1265
+ /**
1266
+ * Generates a MicrofrontendsServer instance from the environment.
1267
+ * Uses additional validation that is only available when in a node runtime
1268
+ */
1269
+ static fromEnv({
1270
+ cookies,
1271
+ meta
1272
+ }) {
1273
+ return new MicrofrontendsServer({
1274
+ config: MicrofrontendsServer.validate(getConfigStringFromEnv()),
1275
+ overrides: parseOverrides(cookies),
1276
+ meta
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Validates the configuration against the JSON schema
1281
+ */
1282
+ static validate(config) {
1283
+ if (typeof config === "string") {
1284
+ const c = validateSchema(config);
1285
+ return c;
1286
+ }
1287
+ return config;
1288
+ }
1289
+ /*
1290
+ * Generates a MicrofrontendsServer instance from a file.
1291
+ */
1292
+ static fromFile({
1293
+ filePath,
1294
+ cookies,
1295
+ meta
1296
+ }) {
1297
+ try {
1298
+ const config = import_node_fs.default.readFileSync(filePath, "utf-8");
1299
+ return new MicrofrontendsServer({
1300
+ config: MicrofrontendsServer.validate(config),
1301
+ overrides: cookies ? parseOverrides(cookies) : void 0,
1302
+ meta
1303
+ });
1304
+ } catch (e) {
1305
+ throw MicroFrontendError.handle(e, {
1306
+ fileName: filePath
1307
+ });
1308
+ }
1309
+ }
1310
+ };
1311
+
1312
+ // src/next-v2/utils/check-proxy.ts
1313
+ function displayLocalProxyInfo(port) {
1314
+ const { MFE_PROXY_MESSAGE_PRINTED, TURBO_TASK_HAS_MFE_PROXY } = process.env;
1315
+ if (TURBO_TASK_HAS_MFE_PROXY === "true" && MFE_PROXY_MESSAGE_PRINTED !== "true") {
1316
+ process.env.MFE_PROXY_MESSAGE_PRINTED = "true";
1317
+ console.log(`Microfrontends Proxy running on http://localhost:${port}`);
1318
+ }
1319
+ }
1320
+
1321
+ // src/next-v2/config/transforms/asset-prefix.ts
1322
+ function transform(args) {
1323
+ const { next, app } = args;
1324
+ if (app.isDefault()) {
1325
+ return {
1326
+ next
1327
+ };
1328
+ }
1329
+ if (next.assetPrefix !== void 0 && next.assetPrefix !== app.getAssetPrefix()) {
1330
+ console.log(
1331
+ `"assetPrefix" already set. This route must be manually configured in your microfrontend.json file.`
1332
+ );
1333
+ } else {
1334
+ next.assetPrefix = `/${app.getAssetPrefix()}`;
1335
+ }
1336
+ return {
1337
+ next
1338
+ };
1339
+ }
1340
+
1341
+ // src/next-v2/config/transforms/draft-mode.ts
1342
+ function transform2(args) {
1343
+ var _a;
1344
+ const { next } = args;
1345
+ if (((_a = next.experimental) == null ? void 0 : _a.multiZoneDraftMode) !== void 0) {
1346
+ return {
1347
+ next
1348
+ };
1349
+ }
1350
+ next.experimental = next.experimental || {};
1351
+ next.experimental.multiZoneDraftMode = true;
1352
+ return {
1353
+ next
1354
+ };
1355
+ }
1356
+
1357
+ // src/next-v2/config/transforms/headers.ts
1358
+ function transform3(args) {
1359
+ const { next, app } = args;
1360
+ if (app.isDefault()) {
1361
+ return {
1362
+ next
1363
+ };
1364
+ }
1365
+ const headersToAdd = [
1366
+ {
1367
+ source: "/:path*",
1368
+ headers: [
1369
+ {
1370
+ key: "X-Vercel-Zone",
1371
+ value: app.name
1372
+ },
1373
+ {
1374
+ key: "X-Vercel-MFE-App",
1375
+ value: app.name
1376
+ }
1377
+ ]
1378
+ },
1379
+ {
1380
+ source: "/:path*",
1381
+ has: [
1382
+ {
1383
+ type: "host",
1384
+ value: "(?<host>.*)"
1385
+ }
1386
+ ],
1387
+ headers: [
1388
+ {
1389
+ // TODO: we may want to revisit before launch whether we want to expose this
1390
+ // value on all responses publicly since users may not want to reveal this host
1391
+ // (maybe just in preview? or when the user is logged in to the toolbar?)
1392
+ key: "X-Vercel-Host",
1393
+ value: ":host"
1394
+ }
1395
+ ]
1396
+ }
1397
+ ];
1398
+ if (next.headers && typeof next.headers === "function") {
1399
+ const originalHeadersFn = next.headers;
1400
+ next.headers = async () => {
1401
+ const originalHeaders = await originalHeadersFn();
1402
+ return [...originalHeaders, ...headersToAdd];
1403
+ };
1404
+ } else {
1405
+ next.headers = () => {
1406
+ return Promise.resolve(headersToAdd);
1407
+ };
1408
+ }
1409
+ return {
1410
+ next
1411
+ };
1412
+ }
1413
+
1414
+ // src/routing-v2/get-domain-from-environment.ts
1415
+ function getDomainFromEnvironment({
1416
+ app,
1417
+ target
1418
+ }) {
1419
+ const projects = JSON.parse(
1420
+ process.env.VERCEL_RELATED_PROJECTS ?? "[]"
1421
+ );
1422
+ if (projects.length === 0) {
1423
+ throw new Error("Missing related vercel project information");
1424
+ }
1425
+ const vercelProject = projects.find(
1426
+ (project) => {
1427
+ var _a;
1428
+ return project.projectId === ((_a = app.vercel) == null ? void 0 : _a.projectId) || project.appName === app.name;
1429
+ }
1430
+ );
1431
+ if (!vercelProject) {
1432
+ throw new Error(
1433
+ `Missing related vercel project information for application "${app.name}"`
1434
+ );
1435
+ }
1436
+ return vercelProject.aliases[target];
1437
+ }
1438
+
1439
+ // src/routing-v2/get-domain-for-current-environment.ts
1440
+ function debugDomains(zone, env, domain) {
1441
+ if (process.env.MFE_DEBUG === "true") {
1442
+ const indent = " ".repeat(4);
1443
+ const header = "domains (zone (env) -> domain)";
1444
+ const separator = "\u23AF".repeat(header.length);
1445
+ const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
1446
+ console.log(`${indent}${header}
1447
+ ${indent}${separator}
1448
+ ${line}
1449
+ `);
1450
+ }
1451
+ }
1452
+ function getCurrentEnvironment() {
1453
+ const isDevelopment = !process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development";
1454
+ const isPreview = process.env.VERCEL_ENV === "preview";
1455
+ const isProduction2 = process.env.VERCEL_ENV === "production";
1456
+ if (isDevelopment) {
1457
+ return { group: "development" };
1458
+ } else if (isProduction2) {
1459
+ return { group: "production" };
1460
+ } else if (isPreview) {
1461
+ return { group: "preview" };
1462
+ }
1463
+ return { group: "custom", name: process.env.VERCEL_ENV };
1464
+ }
1465
+ function getDomainForCurrentEnvironment(config, appName) {
1466
+ var _a;
1467
+ const app = config.getApplication(appName);
1468
+ if ((_a = app.overrides) == null ? void 0 : _a.environment) {
1469
+ return app.overrides.environment.toString();
1470
+ }
1471
+ const { group } = getCurrentEnvironment();
1472
+ const productionHost = config.getDefaultApplication().production.toString();
1473
+ switch (group) {
1474
+ case "development": {
1475
+ const domain = process.env.NODE_ENV === "test" ? app.development.local.toString() : productionHost;
1476
+ debugDomains(appName, "development", domain);
1477
+ return domain;
1478
+ }
1479
+ case "preview": {
1480
+ return getDomainFromEnvironment({ app, target: "branch" });
1481
+ }
1482
+ case "production": {
1483
+ return getDomainFromEnvironment({ app, target: "production" });
1484
+ }
1485
+ case "custom":
1486
+ console.warn(
1487
+ `Custom environments are not supported in getDomainForCurrentEnvironment`
1488
+ );
1489
+ return productionHost;
1490
+ }
1491
+ }
1492
+
1493
+ // src/next-v2/config/transforms/rewrites.ts
1494
+ function debugRewrites(rewrites) {
1495
+ if (process.env.MFE_DEBUG === "true") {
1496
+ const indent = " ".repeat(4);
1497
+ const header = "rewrites (source \u2192 destination)";
1498
+ const separator = "\u23AF".repeat(header.length);
1499
+ const maxSourceLength = Math.max(
1500
+ ...rewrites.map((key) => key.source.length)
1501
+ );
1502
+ const table = rewrites.map((route, idx) => {
1503
+ const paddedSource = route.source.padEnd(maxSourceLength);
1504
+ return `${indent} ${idx + 1}. ${paddedSource} \u2192 ${route.destination}`;
1505
+ }).join("\n");
1506
+ console.log(`${indent}${header}
1507
+ ${indent}${separator}
1508
+ ${table}
1509
+ `);
1510
+ }
1511
+ }
1512
+ function pathToRewrites(path2) {
1513
+ var _a;
1514
+ const regex = /(?<base>^.+)\/:.+\*$/;
1515
+ const match = regex.exec(path2);
1516
+ const paths = [path2];
1517
+ if ((_a = match == null ? void 0 : match.groups) == null ? void 0 : _a.base) {
1518
+ paths.unshift(match.groups.base);
1519
+ }
1520
+ return paths;
1521
+ }
1522
+ function rewritesMapToArr(rewrites) {
1523
+ return Array.from(rewrites.entries()).flatMap(([source, rewrite]) => {
1524
+ const destination = `${rewrite.destination.domain || ""}${rewrite.destination.pathname}`;
1525
+ if (source === destination)
1526
+ return [];
1527
+ return [
1528
+ {
1529
+ source,
1530
+ destination
1531
+ }
1532
+ ];
1533
+ });
1534
+ }
1535
+ function transform4(args) {
1536
+ const { next, microFrontend, app } = args;
1537
+ const buildBeforeFiles = () => {
1538
+ var _a;
1539
+ const rewrites = /* @__PURE__ */ new Map();
1540
+ if (!app.isDefault()) {
1541
+ rewrites.set(`/${app.getAssetPrefix()}/_next/:path+`, {
1542
+ destination: {
1543
+ pathname: `/_next/:path+`
1544
+ }
1545
+ });
1546
+ if (!((_a = app.vercel) == null ? void 0 : _a.routeSpeedInsightsToDefaultZone)) {
1547
+ rewrites.set(`/${app.getAssetPrefix()}/_vercel/:path*`, {
1548
+ destination: { pathname: "/_vercel/:path*" }
1549
+ });
1550
+ }
1551
+ } else if (microFrontend instanceof MicroFrontendMainConfig) {
1552
+ for (const [_, a] of Object.entries(
1553
+ microFrontend.getChildApplications()
1554
+ )) {
1555
+ const { routing } = a;
1556
+ const domain = getDomainForCurrentEnvironment(microFrontend, a.name);
1557
+ rewrites.set(`/${a.getAssetPrefix()}/:path+`, {
1558
+ destination: {
1559
+ domain,
1560
+ pathname: `/${a.getAssetPrefix()}/:path+`
1561
+ }
1562
+ });
1563
+ for (const group of routing) {
1564
+ if (group.routeToDefaultApplication) {
1565
+ continue;
1566
+ } else if (group.flag) {
1567
+ continue;
1568
+ } else {
1569
+ for (const source of group.paths) {
1570
+ const paths = pathToRewrites(source);
1571
+ for (const p of paths) {
1572
+ rewrites.set(p, {
1573
+ destination: { domain, pathname: p }
1574
+ });
1575
+ }
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ }
1581
+ return rewritesMapToArr(rewrites);
1582
+ };
1583
+ const newBeforeFiles = buildBeforeFiles();
1584
+ if (next.rewrites && typeof next.rewrites === "function") {
1585
+ const originalRewritesFn = next.rewrites;
1586
+ next.rewrites = async () => {
1587
+ const originalRewrites = await originalRewritesFn();
1588
+ if (typeof originalRewrites === "object" && !Array.isArray(originalRewrites)) {
1589
+ const { beforeFiles = [] } = originalRewrites;
1590
+ return {
1591
+ beforeFiles: [...newBeforeFiles, ...beforeFiles],
1592
+ afterFiles: originalRewrites.afterFiles,
1593
+ fallback: originalRewrites.fallback
1594
+ };
1595
+ }
1596
+ return {
1597
+ beforeFiles: newBeforeFiles,
1598
+ afterFiles: originalRewrites,
1599
+ fallback: []
1600
+ };
1601
+ };
1602
+ } else {
1603
+ next.rewrites = async () => ({
1604
+ beforeFiles: newBeforeFiles,
1605
+ afterFiles: [],
1606
+ fallback: []
1607
+ });
1608
+ }
1609
+ debugRewrites(newBeforeFiles);
1610
+ return {
1611
+ next
1612
+ };
1613
+ }
1614
+
1615
+ // src/next-v2/config/transforms/server-actions.ts
1616
+ var formatDomainForServerAction = (domain) => domain.replace(/https?:\/\//, "");
1617
+ function transform5(args) {
1618
+ var _a;
1619
+ const { next, app, microFrontend } = args;
1620
+ if (microFrontend instanceof MicroFrontendChildConfig) {
1621
+ console.warn(
1622
+ "server actions transform requires the full config - skipping"
1623
+ );
1624
+ return {
1625
+ next
1626
+ };
1627
+ }
1628
+ const defaultApplication = microFrontend.getDefaultApplication();
1629
+ const appsToAllow = [
1630
+ // this zone - this is included by default unless allowedOrigins is overridden (which we are)
1631
+ // so we re-add it here.
1632
+ app,
1633
+ // this is the default zone for the micro-frontend. Allow child zones to call server actions
1634
+ // that are in the default zone.
1635
+ defaultApplication
1636
+ ];
1637
+ const existingServerActionConfig = (_a = next.experimental) == null ? void 0 : _a.serverActions;
1638
+ next.experimental = {
1639
+ ...next.experimental,
1640
+ serverActions: {
1641
+ ...existingServerActionConfig,
1642
+ allowedOrigins: Array.from(
1643
+ /* @__PURE__ */ new Set([
1644
+ ...(existingServerActionConfig == null ? void 0 : existingServerActionConfig.allowedOrigins) ?? [],
1645
+ ...appsToAllow.flatMap((a) => [
1646
+ formatDomainForServerAction(
1647
+ defaultApplication.production.toString()
1648
+ ),
1649
+ formatDomainForServerAction(
1650
+ getDomainForCurrentEnvironment(microFrontend, a.name)
1651
+ )
1652
+ ])
1653
+ ])
1654
+ )
1655
+ }
1656
+ };
1657
+ return {
1658
+ next
1659
+ };
1660
+ }
1661
+
1662
+ // src/next-v2/config/transforms/webpack.ts
1663
+ function transform6(args) {
1664
+ const { next, microFrontend } = args;
1665
+ const configWithWebpack = {
1666
+ ...next,
1667
+ webpack(cfg, context) {
1668
+ const config = typeof next.webpack === "function" ? next.webpack(cfg, context) : cfg;
1669
+ const { isServer, nextRuntime, webpack: wpFromNext } = context;
1670
+ if (isServer || nextRuntime === "edge") {
1671
+ config.plugins.push(
1672
+ new wpFromNext.EnvironmentPlugin({
1673
+ MFE_CONFIG: JSON.stringify(microFrontend.serialize())
1674
+ })
1675
+ );
1676
+ }
1677
+ config.plugins.push(
1678
+ // Remove node: from import specifiers, because Next.js does not yet support node: scheme
1679
+ // https://github.com/vercel/next.js/issues/28774
1680
+ new wpFromNext.NormalModuleReplacementPlugin(
1681
+ /^node:/,
1682
+ (resource) => {
1683
+ resource.request = resource.request.replace(/^node:/, "");
1684
+ }
1685
+ )
1686
+ );
1687
+ if (!isServer) {
1688
+ config.resolve.fallback = {
1689
+ fs: false,
1690
+ path: false,
1691
+ crypto: false,
1692
+ ...config.resolve.fallback
1693
+ };
1694
+ }
1695
+ return config;
1696
+ }
1697
+ };
1698
+ return {
1699
+ next: configWithWebpack
1700
+ };
1701
+ }
1702
+
1703
+ // src/next-v2/config/transforms/index.ts
1704
+ var transforms = {
1705
+ assetPrefix: transform,
1706
+ draftMode: transform2,
1707
+ headers: transform3,
1708
+ rewrites: transform4,
1709
+ serverActions: transform5,
1710
+ webpack: transform6
1711
+ };
1712
+
1713
+ // src/next-v2/config/env.ts
1714
+ function debugEnv(env) {
1715
+ if (process.env.MFE_DEBUG === "true") {
1716
+ const indent = " ".repeat(4);
1717
+ const header = "env (key \u2192 val)";
1718
+ const separator = "\u23AF".repeat(header.length);
1719
+ const maxKeyLength = Math.max(...Object.keys(env).map((key) => key.length));
1720
+ const table = Object.keys(env).map((key, idx) => {
1721
+ const paddedKey = key.padEnd(maxKeyLength);
1722
+ return `${indent} ${idx + 1}. ${paddedKey} = ${env[key]}`;
1723
+ }).join("\n");
1724
+ console.log(`${indent}${header}
1725
+ ${indent}${separator}
1726
+ ${table}
1727
+ `);
1728
+ }
1729
+ }
1730
+ function setEnvironment({
1731
+ app,
1732
+ microfrontends
1733
+ }) {
1734
+ const clientEnvs = {
1735
+ NEXT_PUBLIC_MFE_CURRENT_APPLICATION: app.name,
1736
+ NEXT_PUBLIC_MFE_CLIENT_CONFIG: JSON.stringify(
1737
+ microfrontends.config.toClientConfig().serialize()
1738
+ )
1739
+ };
1740
+ const serverEnvs = {
1741
+ MFE_CURRENT_APPLICATION: app.name,
1742
+ MFE_CONFIG: JSON.stringify(microfrontends.config.getConfig())
1743
+ };
1744
+ const allEnvs = { ...clientEnvs, ...serverEnvs };
1745
+ for (const [key, value] of Object.entries(allEnvs)) {
1746
+ process.env[key] = value;
1747
+ }
1748
+ debugEnv(allEnvs);
1749
+ }
1750
+
1751
+ // src/next-v2/config/index.ts
1752
+ function typedEntries(obj) {
1753
+ return Object.entries(obj);
1754
+ }
1755
+ function isProduction(opts) {
1756
+ if (opts == null ? void 0 : opts.isProduction) {
1757
+ return opts.isProduction();
1758
+ }
1759
+ return process.env.VERCEL_ENV === "production";
1760
+ }
1761
+ function getApplicationContext(opts) {
1762
+ if (opts == null ? void 0 : opts.appName) {
1763
+ return { name: opts.appName };
1764
+ }
1765
+ try {
1766
+ const packageJsonString = import_node_fs2.default.readFileSync("./package.json", "utf-8");
1767
+ const packageJson = JSON.parse(packageJsonString);
1768
+ if (!packageJson.name) {
1769
+ throw new MicroFrontendError(
1770
+ `package.json file missing required field "name"`,
1771
+ {
1772
+ type: "packageJson",
1773
+ subtype: "missing_field_name",
1774
+ source: "@vercel/micro-frontends/next"
1775
+ }
1776
+ );
1777
+ }
1778
+ return { name: packageJson.name };
1779
+ } catch (err) {
1780
+ throw MicroFrontendError.handle(err, {
1781
+ fileName: "package.json"
1782
+ });
1783
+ }
1784
+ }
1785
+ function withMicroFrontends(nextConfig, opts) {
1786
+ var _a;
1787
+ if (opts == null ? void 0 : opts.debug) {
1788
+ process.env.MFE_DEBUG = "true";
1789
+ }
1790
+ const { name: fromApp } = getApplicationContext(opts);
1791
+ const microfrontends = MicrofrontendsServer.fromFile({
1792
+ filePath: (opts == null ? void 0 : opts.configPath) ?? "./microfrontends.json",
1793
+ meta: {
1794
+ fromApp
1795
+ }
1796
+ });
1797
+ const app = microfrontends.config.getApplication(fromApp);
1798
+ setEnvironment({ app, microfrontends });
1799
+ let next = { ...nextConfig };
1800
+ for (const [key, transform7] of typedEntries(transforms)) {
1801
+ if ((_a = opts == null ? void 0 : opts.skipTransforms) == null ? void 0 : _a.includes(key)) {
1802
+ console.log(`Skipping ${key} transform`);
1803
+ continue;
1804
+ }
1805
+ try {
1806
+ const transformedConfig = transform7({
1807
+ app,
1808
+ next,
1809
+ microFrontend: microfrontends.config,
1810
+ opts: {
1811
+ isProduction: isProduction(opts)
1812
+ }
1813
+ });
1814
+ next = transformedConfig.next;
1815
+ } catch (e) {
1816
+ console.error("Error transforming next config", e);
1817
+ }
1818
+ }
1819
+ displayLocalProxyInfo(microfrontends.config.getLocalProxyPort());
1820
+ if (isVercel()) {
1821
+ microfrontends.writeConfig();
1822
+ }
1823
+ return next;
1824
+ }
1825
+ // Annotate the CommonJS export names for ESM import in node:
1826
+ 0 && (module.exports = {
1827
+ withMicroFrontends
1828
+ });
1829
+ //# sourceMappingURL=config.cjs.map