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