@vercel/microfrontends 0.13.0 → 0.14.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 (76) hide show
  1. package/README.md +3 -3
  2. package/dist/bin/cli.cjs +85 -60
  3. package/dist/config/client.d.ts +1 -1
  4. package/dist/config.cjs.map +1 -1
  5. package/dist/config.d.ts +1 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/{index-83133f2d.d.ts → index-bf67a461.d.ts} +3 -10
  8. package/dist/next/client.cjs +1 -1
  9. package/dist/next/client.cjs.map +1 -1
  10. package/dist/next/client.js +1 -1
  11. package/dist/next/client.js.map +1 -1
  12. package/dist/next/endpoints.cjs.map +1 -1
  13. package/dist/next/endpoints.d.ts +1 -1
  14. package/dist/next/endpoints.js.map +1 -1
  15. package/dist/next/middleware.cjs +0 -29
  16. package/dist/next/middleware.cjs.map +1 -1
  17. package/dist/next/middleware.js +0 -29
  18. package/dist/next/middleware.js.map +1 -1
  19. package/dist/{types-a995174e.d.ts → types-a29d224a.d.ts} +1 -7
  20. package/dist/{types-15b7f215.d.ts → types-cfe3308b.d.ts} +1 -1
  21. package/dist/types-fc30696d.d.ts +11 -0
  22. package/dist/utils/mfe-port.cjs +70 -56
  23. package/dist/utils/mfe-port.cjs.map +1 -1
  24. package/dist/utils/mfe-port.js +67 -53
  25. package/dist/utils/mfe-port.js.map +1 -1
  26. package/dist/v2/config.cjs +0 -14
  27. package/dist/v2/config.cjs.map +1 -1
  28. package/dist/v2/config.d.ts +4 -3
  29. package/dist/v2/config.js +0 -14
  30. package/dist/v2/config.js.map +1 -1
  31. package/dist/v2/microfrontends/server.cjs +68 -54
  32. package/dist/v2/microfrontends/server.cjs.map +1 -1
  33. package/dist/v2/microfrontends/server.d.ts +6 -5
  34. package/dist/v2/microfrontends/server.js +65 -51
  35. package/dist/v2/microfrontends/server.js.map +1 -1
  36. package/dist/v2/microfrontends.cjs +0 -14
  37. package/dist/v2/microfrontends.cjs.map +1 -1
  38. package/dist/v2/microfrontends.d.ts +4 -3
  39. package/dist/v2/microfrontends.js +0 -14
  40. package/dist/v2/microfrontends.js.map +1 -1
  41. package/dist/v2/next/client.cjs +1 -1
  42. package/dist/v2/next/client.cjs.map +1 -1
  43. package/dist/v2/next/client.js +1 -1
  44. package/dist/v2/next/client.js.map +1 -1
  45. package/dist/v2/next/config.cjs +106 -60
  46. package/dist/v2/next/config.cjs.map +1 -1
  47. package/dist/v2/next/config.js +103 -57
  48. package/dist/v2/next/config.js.map +1 -1
  49. package/dist/v2/next/endpoints.cjs.map +1 -1
  50. package/dist/v2/next/endpoints.d.ts +13 -2
  51. package/dist/v2/next/endpoints.js.map +1 -1
  52. package/dist/v2/next/middleware.cjs +10 -54
  53. package/dist/v2/next/middleware.cjs.map +1 -1
  54. package/dist/v2/next/middleware.d.ts +7 -2
  55. package/dist/v2/next/middleware.js +10 -54
  56. package/dist/v2/next/middleware.js.map +1 -1
  57. package/dist/v2/next/testing.cjs +992 -0
  58. package/dist/v2/next/testing.cjs.map +1 -0
  59. package/dist/v2/next/testing.d.ts +55 -0
  60. package/dist/v2/next/testing.js +961 -0
  61. package/dist/v2/next/testing.js.map +1 -0
  62. package/dist/v2/overrides.d.ts +3 -3
  63. package/dist/v2/routing.cjs +19 -0
  64. package/dist/v2/routing.cjs.map +1 -0
  65. package/dist/v2/routing.d.ts +26 -0
  66. package/dist/v2/routing.js +1 -0
  67. package/dist/v2/routing.js.map +1 -0
  68. package/dist/v2/schema.cjs.map +1 -1
  69. package/dist/v2/schema.d.ts +1 -1
  70. package/dist/validation.cjs +0 -4
  71. package/dist/validation.cjs.map +1 -1
  72. package/dist/validation.d.ts +0 -6
  73. package/dist/validation.js +0 -4
  74. package/dist/validation.js.map +1 -1
  75. package/package.json +20 -5
  76. package/schema/schema-v2.json +0 -4
@@ -0,0 +1,961 @@
1
+ // src/next-v2/testing/index.ts
2
+ import { readFileSync } from "node:fs";
3
+ import {
4
+ NextRequest
5
+ } from "next/server";
6
+ import { match } from "path-to-regexp";
7
+ import { parse as parse2 } from "jsonc-parser";
8
+ import { matchHas } from "next/dist/shared/lib/router/utils/prepare-destination";
9
+ import { NextRequestHint } from "next/dist/server/web/adapter";
10
+ import { WebNextRequest } from "next/dist/server/base-http/web";
11
+
12
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
13
+ import { parse } from "jsonc-parser";
14
+
15
+ // src/config-v2/errors.ts
16
+ var MicrofrontendError = class extends Error {
17
+ constructor(message, opts) {
18
+ super(message);
19
+ this.name = "MicrofrontendsError";
20
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/microfrontends";
21
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
22
+ this.subtype = opts == null ? void 0 : opts.subtype;
23
+ Error.captureStackTrace(this, MicrofrontendError);
24
+ }
25
+ isKnown() {
26
+ return this.type !== "unknown";
27
+ }
28
+ isUnknown() {
29
+ return !this.isKnown();
30
+ }
31
+ /**
32
+ * Converts an error to a MicrofrontendsError.
33
+ * @param original - The original error to convert.
34
+ * @returns The converted MicrofrontendsError.
35
+ */
36
+ static convert(original, opts) {
37
+ if (opts == null ? void 0 : opts.fileName) {
38
+ const err = MicrofrontendError.convertFSError(original, opts.fileName);
39
+ if (err) {
40
+ return err;
41
+ }
42
+ }
43
+ if (original.message.includes(
44
+ "Code generation from strings disallowed for this context"
45
+ )) {
46
+ return new MicrofrontendError(original.message, {
47
+ type: "config",
48
+ subtype: "unsupported_validation_env",
49
+ source: "ajv"
50
+ });
51
+ }
52
+ return new MicrofrontendError(original.message);
53
+ }
54
+ static convertFSError(original, fileName) {
55
+ if (original instanceof Error && "code" in original) {
56
+ if (original.code === "ENOENT") {
57
+ return new MicrofrontendError(`Could not find "${fileName}"`, {
58
+ type: "config",
59
+ subtype: "unable_to_read_file",
60
+ source: "fs"
61
+ });
62
+ }
63
+ if (original.code === "EACCES") {
64
+ return new MicrofrontendError(
65
+ `Permission denied while accessing "${fileName}"`,
66
+ {
67
+ type: "config",
68
+ subtype: "invalid_permissions",
69
+ source: "fs"
70
+ }
71
+ );
72
+ }
73
+ }
74
+ if (original instanceof SyntaxError) {
75
+ return new MicrofrontendError(
76
+ `Failed to parse "${fileName}": Invalid JSON format.`,
77
+ {
78
+ type: "config",
79
+ subtype: "invalid_syntax",
80
+ source: "fs"
81
+ }
82
+ );
83
+ }
84
+ return null;
85
+ }
86
+ /**
87
+ * Handles an unknown error and returns a MicrofrontendsError instance.
88
+ * @param err - The error to handle.
89
+ * @returns A MicrofrontendsError instance.
90
+ */
91
+ static handle(err, opts) {
92
+ if (err instanceof MicrofrontendError) {
93
+ return err;
94
+ }
95
+ if (err instanceof Error) {
96
+ return MicrofrontendError.convert(err, opts);
97
+ }
98
+ if (typeof err === "object" && err !== null) {
99
+ if ("message" in err && typeof err.message === "string") {
100
+ return MicrofrontendError.convert(new Error(err.message), opts);
101
+ }
102
+ }
103
+ return new MicrofrontendError("An unknown error occurred");
104
+ }
105
+ };
106
+
107
+ // src/config-v2/microfrontends-config/utils/get-config-from-env.ts
108
+ function getConfigStringFromEnv() {
109
+ const config = process.env.MFE_CONFIG;
110
+ if (!config) {
111
+ throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
112
+ type: "config",
113
+ subtype: "not_found_in_env"
114
+ });
115
+ }
116
+ return config;
117
+ }
118
+
119
+ // src/config-v2/schema/utils/is-main-config.ts
120
+ function isMainConfig(c) {
121
+ return !("partOf" in c);
122
+ }
123
+
124
+ // src/config-v2/schema/utils/is-default-app.ts
125
+ function isDefaultApp(a) {
126
+ return !("routing" in a);
127
+ }
128
+
129
+ // src/config-v2/microfrontends-config/client/index.ts
130
+ import { pathToRegexp } from "path-to-regexp";
131
+ var MicrofrontendConfigClient = class {
132
+ constructor(config, opts) {
133
+ this.pathCache = {};
134
+ this.serialized = config;
135
+ if (opts == null ? void 0 : opts.removeFlaggedPaths) {
136
+ for (const app of Object.values(config.applications)) {
137
+ if (app.routing) {
138
+ app.routing = app.routing.filter((match2) => !match2.flag);
139
+ }
140
+ }
141
+ }
142
+ this.applications = config.applications;
143
+ }
144
+ /**
145
+ * Create a new `MicrofrontendConfigClient` from a JSON string.
146
+ * Config must be passed in to remain framework agnostic
147
+ */
148
+ static fromEnv(config, opts) {
149
+ if (!config) {
150
+ throw new Error("No microfrontends configuration found");
151
+ }
152
+ return new MicrofrontendConfigClient(
153
+ JSON.parse(config),
154
+ opts
155
+ );
156
+ }
157
+ isEqual(other) {
158
+ return JSON.stringify(this.applications) === JSON.stringify(other.applications);
159
+ }
160
+ getApplicationNameForPath(path) {
161
+ if (!path.startsWith("/")) {
162
+ throw new Error(`Path must start with a /`);
163
+ }
164
+ if (this.pathCache[path]) {
165
+ return this.pathCache[path];
166
+ }
167
+ const pathname = new URL(path, "https://example.com").pathname;
168
+ for (const [name, application] of Object.entries(this.applications)) {
169
+ if (application.routing) {
170
+ for (const group of application.routing) {
171
+ for (const childPath of group.paths) {
172
+ const regexp = pathToRegexp(childPath);
173
+ if (regexp.test(pathname)) {
174
+ this.pathCache[path] = name;
175
+ return name;
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+ const defaultApplication = Object.entries(this.applications).find(
182
+ ([, application]) => application.default
183
+ );
184
+ if (!defaultApplication) {
185
+ return null;
186
+ }
187
+ this.pathCache[path] = defaultApplication[0];
188
+ return defaultApplication[0];
189
+ }
190
+ serialize() {
191
+ return this.serialized;
192
+ }
193
+ };
194
+
195
+ // src/config-v2/overrides/constants.ts
196
+ var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
197
+ var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
198
+
199
+ // src/config-v2/overrides/is-override-cookie.ts
200
+ function isOverrideCookie(cookie) {
201
+ var _a;
202
+ return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
203
+ }
204
+
205
+ // src/config-v2/overrides/get-override-from-cookie.ts
206
+ function getOverrideFromCookie(cookie) {
207
+ if (!isOverrideCookie(cookie) || !cookie.value)
208
+ return;
209
+ return {
210
+ application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
211
+ host: cookie.value
212
+ };
213
+ }
214
+
215
+ // src/config-v2/overrides/parse-overrides.ts
216
+ function parseOverrides(cookies) {
217
+ const overridesConfig = { applications: {} };
218
+ cookies.forEach((cookie) => {
219
+ const override = getOverrideFromCookie(cookie);
220
+ if (!override)
221
+ return;
222
+ overridesConfig.applications[override.application] = {
223
+ environment: { host: override.host }
224
+ };
225
+ });
226
+ return overridesConfig;
227
+ }
228
+
229
+ // src/config-v2/microfrontends-config/isomorphic/validation.ts
230
+ import { pathToRegexp as pathToRegexp2, parse as parsePathRegexp } from "path-to-regexp";
231
+ var SUPPORTED_VERSIONS = ["2"];
232
+ var validateConfigVersion = (version) => {
233
+ if (!SUPPORTED_VERSIONS.includes(version)) {
234
+ throw new MicrofrontendError(
235
+ `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
236
+ ", "
237
+ )}`,
238
+ { type: "config", subtype: "unsupported_version" }
239
+ );
240
+ }
241
+ };
242
+ var validateConfigPaths = (applicationConfigsById) => {
243
+ if (!applicationConfigsById) {
244
+ return;
245
+ }
246
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
247
+ const errors = [];
248
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
249
+ if (isDefaultApp(app)) {
250
+ continue;
251
+ }
252
+ for (const pathMatch of app.routing) {
253
+ for (const path of pathMatch.paths) {
254
+ const tokens = parsePathRegexp(path);
255
+ for (const token of tokens.slice(0, -1)) {
256
+ if (typeof token !== "string") {
257
+ errors.push(
258
+ `Path ${path} may only have a :wildcard in the last path component`
259
+ );
260
+ }
261
+ }
262
+ const existing = pathsByApplicationId.get(path);
263
+ if (existing) {
264
+ existing.applications.push(id);
265
+ } else {
266
+ pathsByApplicationId.set(path, {
267
+ applications: [id],
268
+ matcher: pathToRegexp2(path),
269
+ applicationId: id
270
+ });
271
+ }
272
+ }
273
+ }
274
+ }
275
+ const entries = Array.from(pathsByApplicationId.entries());
276
+ entries.forEach(([path, { applications: ids, matcher, applicationId }]) => {
277
+ if (ids.length > 1) {
278
+ errors.push(
279
+ `Duplicate path "${path}" for applications "${ids.join(", ")}"`
280
+ );
281
+ }
282
+ entries.forEach(
283
+ ([
284
+ matchPath,
285
+ { applications: matchIds, applicationId: matchApplicationId }
286
+ ]) => {
287
+ if (path === matchPath) {
288
+ return;
289
+ }
290
+ if (applicationId === matchApplicationId) {
291
+ return;
292
+ }
293
+ if (matcher.test(matchPath)) {
294
+ const source = `"${path}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
295
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
296
+ errors.push(
297
+ `Overlapping path detected between ${source} and ${destination}`
298
+ );
299
+ }
300
+ }
301
+ );
302
+ });
303
+ if (errors.length) {
304
+ throw new MicrofrontendError(`Invalid paths: ${errors.join(", ")}`, {
305
+ type: "config",
306
+ subtype: "conflicting_paths"
307
+ });
308
+ }
309
+ };
310
+ var validateAppPaths = (name, app) => {
311
+ for (const group of app.routing) {
312
+ for (const p of group.paths) {
313
+ if (p === "/") {
314
+ continue;
315
+ }
316
+ if (p.endsWith("/")) {
317
+ throw new MicrofrontendError(
318
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
319
+ { type: "application", subtype: "invalid_path" }
320
+ );
321
+ }
322
+ if (!p.startsWith("/")) {
323
+ throw new MicrofrontendError(
324
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
325
+ { type: "application", subtype: "invalid_path" }
326
+ );
327
+ }
328
+ }
329
+ }
330
+ };
331
+ var validateConfigDefaultApplication = (applicationConfigsById) => {
332
+ if (!applicationConfigsById) {
333
+ return;
334
+ }
335
+ const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
336
+ ([, app]) => !isDefaultApp(app)
337
+ );
338
+ const applicationsWithRoutingNames = applicationsWithRouting.map(
339
+ ([key]) => key
340
+ );
341
+ const numApplications = Object.keys(applicationConfigsById).length;
342
+ const numApplicationsWithRouting = applicationsWithRoutingNames.length;
343
+ const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
344
+ if (numApplicationsWithoutRouting === 0) {
345
+ throw new MicrofrontendError(
346
+ `No default application found. At least one application needs to be the default by omitting routing.`,
347
+ { type: "config", subtype: "no_default_application" }
348
+ );
349
+ }
350
+ if (numApplicationsWithoutRouting > 1) {
351
+ throw new MicrofrontendError(
352
+ `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
353
+ { type: "config", subtype: "multiple_default_applications" }
354
+ );
355
+ }
356
+ };
357
+
358
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
359
+ var PREFIX = "vc-ap";
360
+ function generateAssetPrefixFromName({
361
+ name
362
+ }) {
363
+ if (!name) {
364
+ throw new Error("Name is required to generate an asset prefix");
365
+ }
366
+ return `${PREFIX}-${name}`;
367
+ }
368
+
369
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-port.ts
370
+ function generatePortFromName({
371
+ name,
372
+ minPort = 3e3,
373
+ maxPort = 8e3
374
+ }) {
375
+ if (!name) {
376
+ throw new Error("Name is required to generate a port");
377
+ }
378
+ let hash = 0;
379
+ for (let i = 0; i < name.length; i++) {
380
+ hash = (hash << 5) - hash + name.charCodeAt(i);
381
+ hash |= 0;
382
+ }
383
+ hash = Math.abs(hash);
384
+ const range = maxPort - minPort;
385
+ const port = minPort + hash % range;
386
+ return port;
387
+ }
388
+
389
+ // src/config-v2/microfrontends-config/isomorphic/host.ts
390
+ var Host = class {
391
+ constructor(hostConfig, options) {
392
+ const { protocol = "https", host, port } = hostConfig;
393
+ this.protocol = protocol;
394
+ this.host = host;
395
+ this.port = Host.getPort({ port, protocol: this.protocol });
396
+ this.local = options == null ? void 0 : options.isLocal;
397
+ }
398
+ isLocal() {
399
+ return this.local || this.host === "localhost" || this.host === "127.0.0.1";
400
+ }
401
+ static getPort({
402
+ protocol,
403
+ port
404
+ }) {
405
+ if (!port) {
406
+ if (protocol === "http") {
407
+ return 80;
408
+ }
409
+ return 443;
410
+ }
411
+ return port;
412
+ }
413
+ isDefaultPort() {
414
+ return this.port === Host.getPort({ protocol: this.protocol });
415
+ }
416
+ toString(opts = {}) {
417
+ const url = this.toUrl(opts);
418
+ return url.toString().replace(/\/$/, "");
419
+ }
420
+ toUrl(opts = {}) {
421
+ const { includeDefaultPort } = opts;
422
+ const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
423
+ return new URL(url);
424
+ }
425
+ };
426
+ var LocalHost = class extends Host {
427
+ constructor({
428
+ appName,
429
+ ...hostConfig
430
+ }) {
431
+ const host = hostConfig.host ?? "localhost";
432
+ const port = hostConfig.port ?? generatePortFromName({ name: appName });
433
+ const protocol = hostConfig.protocol ?? "http";
434
+ super({ protocol, host, port });
435
+ }
436
+ };
437
+
438
+ // src/config-v2/microfrontends-config/isomorphic/application.ts
439
+ var Application = class {
440
+ constructor(name, {
441
+ app,
442
+ overrides,
443
+ isDefault
444
+ }) {
445
+ var _a, _b;
446
+ this.name = name;
447
+ this.development = {
448
+ local: new LocalHost({
449
+ appName: name,
450
+ ...(_a = app.development) == null ? void 0 : _a.local
451
+ }),
452
+ fallback: ((_b = app.development) == null ? void 0 : _b.fallback) ? new Host(app.development.fallback) : void 0
453
+ };
454
+ this.production = app.production ? new Host(app.production) : void 0;
455
+ this.vercel = app.vercel;
456
+ this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
457
+ environment: new Host(overrides.environment)
458
+ } : void 0;
459
+ this.default = isDefault ?? false;
460
+ this.serialized = app;
461
+ }
462
+ isDefault() {
463
+ return this.default;
464
+ }
465
+ getAssetPrefix() {
466
+ return generateAssetPrefixFromName({ name: this.name });
467
+ }
468
+ serialize() {
469
+ return this.serialized;
470
+ }
471
+ };
472
+ var DefaultApplication = class extends Application {
473
+ constructor(name, {
474
+ app,
475
+ overrides
476
+ }) {
477
+ super(name, {
478
+ app,
479
+ overrides,
480
+ isDefault: true
481
+ });
482
+ this.default = true;
483
+ this.production = new Host(app.production);
484
+ }
485
+ getAssetPrefix() {
486
+ return "";
487
+ }
488
+ };
489
+ var ChildApplication = class extends Application {
490
+ constructor(name, {
491
+ app,
492
+ overrides
493
+ }) {
494
+ ChildApplication.validate(name, app);
495
+ super(name, {
496
+ app,
497
+ overrides,
498
+ isDefault: false
499
+ });
500
+ this.default = false;
501
+ this.routing = app.routing;
502
+ }
503
+ static validate(name, app) {
504
+ validateAppPaths(name, app);
505
+ }
506
+ };
507
+
508
+ // src/config-v2/microfrontends-config/isomorphic/constants.ts
509
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
510
+
511
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
512
+ var MicrofrontendConfigIsomorphic = class {
513
+ constructor({
514
+ config,
515
+ overrides,
516
+ meta
517
+ }) {
518
+ this.childApplications = {};
519
+ var _a, _b, _c, _d;
520
+ MicrofrontendConfigIsomorphic.validate(config);
521
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
522
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
523
+ this.isMainConfig = isMainConfig(config);
524
+ if (isMainConfig(config)) {
525
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
526
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
527
+ if (isDefaultApp(appConfig)) {
528
+ this.defaultApplication = new DefaultApplication(appId, {
529
+ app: appConfig,
530
+ overrides: appOverrides
531
+ });
532
+ } else {
533
+ this.childApplications[appId] = new ChildApplication(appId, {
534
+ app: appConfig,
535
+ overrides: appOverrides
536
+ });
537
+ }
538
+ }
539
+ } else {
540
+ this.partOf = config.partOf;
541
+ const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
542
+ this.childApplications[meta.fromApp] = new ChildApplication(
543
+ meta.fromApp,
544
+ {
545
+ // we don't know routing because we're not in the main config
546
+ app: { routing: [] },
547
+ overrides: appOverrides
548
+ }
549
+ );
550
+ }
551
+ if (isMainConfig(config) && !this.defaultApplication) {
552
+ throw new MicrofrontendError(
553
+ `Could not find default application in microfrontends configuration`,
554
+ {
555
+ type: "application",
556
+ subtype: "not_found"
557
+ }
558
+ );
559
+ }
560
+ this.config = config;
561
+ this.options = config.options;
562
+ this.serialized = {
563
+ config,
564
+ overrides,
565
+ meta
566
+ };
567
+ }
568
+ static validate(config) {
569
+ const c = typeof config === "string" ? parse(config) : config;
570
+ if (isMainConfig(c)) {
571
+ validateConfigVersion(c.version);
572
+ validateConfigPaths(c.applications);
573
+ validateConfigDefaultApplication(c.applications);
574
+ }
575
+ return c;
576
+ }
577
+ static fromEnv({
578
+ meta,
579
+ cookies
580
+ }) {
581
+ return new MicrofrontendConfigIsomorphic({
582
+ config: parse(getConfigStringFromEnv()),
583
+ overrides: parseOverrides(cookies ?? []),
584
+ meta
585
+ });
586
+ }
587
+ isOverridesDisabled() {
588
+ var _a, _b;
589
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
590
+ }
591
+ getConfig() {
592
+ return this.config;
593
+ }
594
+ getApplicationsByType() {
595
+ return {
596
+ defaultApplication: this.defaultApplication,
597
+ applications: Object.values(this.childApplications)
598
+ };
599
+ }
600
+ getChildApplications() {
601
+ return Object.values(this.childApplications);
602
+ }
603
+ getAllApplications() {
604
+ return [
605
+ this.defaultApplication,
606
+ ...Object.values(this.childApplications)
607
+ ].filter(Boolean);
608
+ }
609
+ getApplication(name) {
610
+ var _a;
611
+ if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
612
+ return this.defaultApplication;
613
+ }
614
+ const app = this.childApplications[name];
615
+ if (!app) {
616
+ throw new MicrofrontendError(
617
+ `Could not find microfrontends configuration for application "${name}"`,
618
+ {
619
+ type: "application",
620
+ subtype: "not_found"
621
+ }
622
+ );
623
+ }
624
+ return app;
625
+ }
626
+ getApplicationByProjectId(projectId) {
627
+ var _a, _b;
628
+ if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
629
+ return this.defaultApplication;
630
+ }
631
+ return Object.values(this.childApplications).find(
632
+ (app) => {
633
+ var _a2;
634
+ return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
635
+ }
636
+ );
637
+ }
638
+ /**
639
+ * Returns the default application. This can throw if the default application
640
+ * is undefined ( )
641
+ */
642
+ getDefaultApplication() {
643
+ if (!this.defaultApplication) {
644
+ throw new MicrofrontendError(
645
+ `Could not find default application in microfrontends configuration`,
646
+ {
647
+ type: "application",
648
+ subtype: "not_found"
649
+ }
650
+ );
651
+ }
652
+ return this.defaultApplication;
653
+ }
654
+ /**
655
+ * Returns the configured port for the local proxy
656
+ */
657
+ getLocalProxyPort() {
658
+ var _a, _b;
659
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
660
+ }
661
+ /**
662
+ * Serializes the class back to the Schema type.
663
+ *
664
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
665
+ */
666
+ toSchemaJson() {
667
+ return this.serialized.config;
668
+ }
669
+ toClientConfig() {
670
+ const applications = Object.fromEntries(
671
+ Object.entries(this.childApplications).map(([name, application]) => [
672
+ name,
673
+ {
674
+ default: false,
675
+ routing: application.routing
676
+ }
677
+ ])
678
+ );
679
+ if (this.defaultApplication) {
680
+ applications[this.defaultApplication.name] = {
681
+ default: true
682
+ };
683
+ }
684
+ return new MicrofrontendConfigClient({
685
+ applications
686
+ });
687
+ }
688
+ serialize() {
689
+ return this.serialized;
690
+ }
691
+ };
692
+
693
+ // src/routing-v2/get-domain-from-environment.ts
694
+ function getDomainFromEnvironment({
695
+ app,
696
+ target
697
+ }) {
698
+ var _a;
699
+ const mfeProjects = JSON.parse(
700
+ process.env.VERCEL_MICROFRONTENDS_PROJECTS ?? "[]"
701
+ );
702
+ if (mfeProjects.length === 0) {
703
+ throw new Error("Missing related microfrontends project information");
704
+ }
705
+ if (!((_a = app.vercel) == null ? void 0 : _a.projectId)) {
706
+ throw new Error(`Missing applications[${app.name}].vercel.projectId`);
707
+ }
708
+ const vercelProject = mfeProjects.find(
709
+ (p) => {
710
+ var _a2;
711
+ return p.project.id === ((_a2 = app.vercel) == null ? void 0 : _a2.projectId);
712
+ }
713
+ );
714
+ if (!vercelProject) {
715
+ throw new Error(
716
+ `Missing related microfrontends project information for application "${app.name}"`
717
+ );
718
+ }
719
+ const domain = target === "preview" && vercelProject.preview.branch ? vercelProject.preview.branch : vercelProject.production.alias ?? vercelProject.production.url;
720
+ if (!domain) {
721
+ throw new Error(
722
+ `Missing domain for target "${target}" in application "${app.name}"`
723
+ );
724
+ }
725
+ return domain.startsWith("https://") ? domain : `https://${domain}`;
726
+ }
727
+
728
+ // src/next-v2/testing/index.ts
729
+ function expandWildcards(path) {
730
+ if (path.includes("/:path*") || path.includes("/:slug*")) {
731
+ return [
732
+ path === "/:path*" || path === "/:slug*" ? "/" : path.replace("/:path*", "").replace("/:slug*", ""),
733
+ path.replace("/:path*", "/foo").replace("/:slug*", "/foo"),
734
+ path.replace("/:path*", "/foo/bar").replace("/:slug*", "/foo/bar")
735
+ ];
736
+ }
737
+ if (path.includes("/:path+") || path.includes("/:slug+")) {
738
+ return [
739
+ path.replace("/:path+", "/foo").replace("/:slug+", "/foo"),
740
+ path.replace("/:path+", "/foo/bar").replace("/:slug+", "/foo/bar")
741
+ ];
742
+ }
743
+ if (path.includes("/:path") || path.includes("/:slug")) {
744
+ return [path.replace("/:path", "/foo").replace("/:slug", "/foo")];
745
+ }
746
+ return [path];
747
+ }
748
+ function loadMicrofrontendConfigForEdge(path) {
749
+ const rawMfConfig = parse2(readFileSync(path, "utf-8"));
750
+ return new MicrofrontendConfigIsomorphic({
751
+ config: rawMfConfig,
752
+ meta: { fromApp: "test" }
753
+ });
754
+ }
755
+ function getAllChildApplicationNames(mfConfig) {
756
+ return mfConfig.getChildApplications().map((app) => app.name);
757
+ }
758
+ function getLaunchedPathsForApp(mfConfig, appName) {
759
+ const app = mfConfig.getApplication(appName);
760
+ if (app instanceof DefaultApplication) {
761
+ return [];
762
+ }
763
+ return [
764
+ `/${app.getAssetPrefix()}/_next/static`,
765
+ ...app.routing.filter((group) => !group.flag).flatMap((group) => group.paths.flatMap(expandWildcards))
766
+ ];
767
+ }
768
+ function getFlaggedPathsForApp(mfConfig, appName) {
769
+ const app = mfConfig.getApplication(appName);
770
+ if (app instanceof DefaultApplication) {
771
+ return [];
772
+ }
773
+ return app.routing.filter((group) => Boolean(group.flag)).flatMap((group) => group.paths.flatMap(expandWildcards));
774
+ }
775
+ function getExpectedDomainForApp(mfConfig, appName, env) {
776
+ const app = mfConfig.getApplication(appName);
777
+ const defaultApp = mfConfig.getDefaultApplication();
778
+ if (env === "development") {
779
+ return app.development.local.toString();
780
+ }
781
+ if (["preview", "production"].includes(env)) {
782
+ const target = env;
783
+ return getDomainFromEnvironment({ app, target });
784
+ }
785
+ return defaultApp.production.toString();
786
+ }
787
+ function getAllMultiZonesPaths(mfConfig) {
788
+ return mfConfig.getChildApplications().flatMap((app) => {
789
+ return app.routing.flatMap((group) => group.paths.flatMap(expandWildcards));
790
+ });
791
+ }
792
+ function urlMatches(middlewareConfig, path, host) {
793
+ if (!middlewareConfig.matcher) {
794
+ return false;
795
+ }
796
+ const matchers = Array.isArray(middlewareConfig.matcher) ? middlewareConfig.matcher : [middlewareConfig.matcher];
797
+ for (let matcher of matchers) {
798
+ matcher = typeof matcher === "string" ? { source: matcher } : matcher;
799
+ if (match(matcher.source)(path)) {
800
+ if (matchHas(
801
+ new WebNextRequest(
802
+ new NextRequestHint({
803
+ init: { headers: { host } },
804
+ input: `https://${host}${path}`,
805
+ page: "unused_placeholder"
806
+ })
807
+ ),
808
+ {},
809
+ matcher.has,
810
+ matcher.missing
811
+ )) {
812
+ return true;
813
+ }
814
+ }
815
+ }
816
+ return false;
817
+ }
818
+ function validateMiddlewareConfig(middlewareConfig, microfrontendConfigOrPath, extraProductionMatches) {
819
+ const microfrontendConfig = typeof microfrontendConfigOrPath === "string" ? loadMicrofrontendConfigForEdge(microfrontendConfigOrPath) : microfrontendConfigOrPath;
820
+ const errors = [];
821
+ const usedExtraProductionMatches = /* @__PURE__ */ new Set();
822
+ for (const application of microfrontendConfig.getChildApplications()) {
823
+ const matches = [...application.routing];
824
+ matches.push({
825
+ paths: [`/${application.getAssetPrefix()}/_next/:path+`]
826
+ });
827
+ for (const aMatch of matches) {
828
+ const isFlagged = Boolean(aMatch.flag);
829
+ for (const path of aMatch.paths) {
830
+ const pathsToTest = expandWildcards(path);
831
+ for (const testPath of pathsToTest) {
832
+ const productionHost = microfrontendConfig.getDefaultApplication().production.host;
833
+ const pathForDisplay = `${testPath}${path === testPath ? "" : ` (synthesized from ${path})`}`;
834
+ if (!urlMatches(middlewareConfig, testPath, "test.nonproduction.host")) {
835
+ errors.push(
836
+ `Matcher misconfigured for ${pathForDisplay}. This path should have matched the middleware config on a non-production host, but did not. Microfrontends require a middleware config matcher that matches on this host everywhere but in production. That can be configured with a configuration like this:
837
+ ${getSampleMatcher(path, productionHost)}`
838
+ );
839
+ break;
840
+ }
841
+ const productionUrlMatches = urlMatches(
842
+ middlewareConfig,
843
+ testPath,
844
+ productionHost
845
+ );
846
+ if (isFlagged) {
847
+ if (!productionUrlMatches) {
848
+ errors.push(
849
+ `Matcher misconfigured for ${pathForDisplay}. Middleware config matchers for flagged paths should ALWAYS match.`
850
+ );
851
+ break;
852
+ }
853
+ } else if (productionUrlMatches) {
854
+ if (extraProductionMatches == null ? void 0 : extraProductionMatches.includes(path)) {
855
+ usedExtraProductionMatches.add(path);
856
+ } else {
857
+ errors.push(
858
+ `Matcher misconfigured for ${pathForDisplay}. This path matched the middleware config on a production host, but should not have. Microfrontends require a middleware config matcher that matches on this host everywhere but in production. If this is desired, you can add the path the to extraProductionMatches parameter. Otherwise, you can set up a configuration like this:
859
+ ${getSampleMatcher(path, productionHost)}`
860
+ );
861
+ }
862
+ break;
863
+ }
864
+ }
865
+ }
866
+ }
867
+ }
868
+ const unusedExtraProductionMatches = extraProductionMatches == null ? void 0 : extraProductionMatches.filter(
869
+ (x) => !usedExtraProductionMatches.has(x)
870
+ );
871
+ if (unusedExtraProductionMatches == null ? void 0 : unusedExtraProductionMatches.length) {
872
+ errors.push(
873
+ `The following paths were passed to the extraProductionMatches parameter but were unused. You probably want to remove them from the extraProductionMatches parameter: ${unusedExtraProductionMatches.join(", ")}`
874
+ );
875
+ }
876
+ if (errors.length > 0) {
877
+ const message = `Found the following inconsistencies between your microfrontend config ${typeof microfrontendConfigOrPath === "string" ? `(at ${microfrontendConfigOrPath}) ` : ""}and middleware config:
878
+
879
+ - `;
880
+ throw new Error(message + errors.join("\n\n- "));
881
+ }
882
+ }
883
+ function getSampleMatcher(path, host) {
884
+ return ` {
885
+ source: '${path}', // This can also be a broader regular expression.
886
+ missing: [
887
+ type: 'header',
888
+ key: 'host',
889
+ value '${host}',
890
+ ],
891
+ }`;
892
+ }
893
+ async function validateMiddlewareOnFlaggedPaths(microfrontendConfigOrPath, middleware) {
894
+ const initialEnv = process.env.VERCEL_ENV;
895
+ const initialMfePreviewDomains = process.env.MFE_PREVIEW_DOMAINS;
896
+ try {
897
+ const microfrontendConfig = typeof microfrontendConfigOrPath === "string" ? loadMicrofrontendConfigForEdge(microfrontendConfigOrPath) : microfrontendConfigOrPath;
898
+ const allAppNames = getAllChildApplicationNames(microfrontendConfig);
899
+ const errors = [];
900
+ for (const appName of allAppNames) {
901
+ const flaggedPaths = getFlaggedPathsForApp(microfrontendConfig, appName);
902
+ if (flaggedPaths.length) {
903
+ for (const env of ["preview", "production"]) {
904
+ process.env.VERCEL_ENV = env;
905
+ for (const path of flaggedPaths) {
906
+ const expectedHost = getExpectedDomainForApp(
907
+ microfrontendConfig,
908
+ appName,
909
+ env
910
+ );
911
+ const expectedDefaultHost = getExpectedDomainForApp(
912
+ microfrontendConfig,
913
+ microfrontendConfig.getDefaultApplication().name,
914
+ env
915
+ );
916
+ const requestPath = `${expectedDefaultHost}${path}`;
917
+ const request = new NextRequest(requestPath, {
918
+ headers: { "x-vercel-skip-deployment-existence-check": "1" }
919
+ });
920
+ const response = await middleware(
921
+ request,
922
+ {}
923
+ );
924
+ const expectedUrl = `${expectedHost}${path}`;
925
+ if (!response) {
926
+ errors.push(
927
+ `middleware did not action for ${requestPath} in ${env}. Expected a rewrite to ${expectedUrl}`
928
+ );
929
+ } else if (response.status !== 200) {
930
+ errors.push(
931
+ `expected 200 status for ${requestPath} in ${env} but got ${response.status}`
932
+ );
933
+ } else if (response.headers.get("x-middleware-rewrite") !== expectedUrl) {
934
+ errors.push(
935
+ `expected rewrite from ${requestPath} to ${expectedUrl} in ${env}, but got ${response.headers.get("x-middleware-rewrite")}`
936
+ );
937
+ }
938
+ }
939
+ }
940
+ }
941
+ }
942
+ if (errors.length) {
943
+ throw new Error(errors.join("\n"));
944
+ }
945
+ } finally {
946
+ process.env.VERCEL_ENV = initialEnv;
947
+ process.env.MFE_PREVIEW_DOMAINS = initialMfePreviewDomains;
948
+ }
949
+ }
950
+ export {
951
+ expandWildcards,
952
+ getAllChildApplicationNames,
953
+ getAllMultiZonesPaths,
954
+ getExpectedDomainForApp,
955
+ getFlaggedPathsForApp,
956
+ getLaunchedPathsForApp,
957
+ loadMicrofrontendConfigForEdge,
958
+ validateMiddlewareConfig,
959
+ validateMiddlewareOnFlaggedPaths
960
+ };
961
+ //# sourceMappingURL=testing.js.map