@vercel/microfrontends 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +202 -0
  2. package/cli/index.cjs +21 -0
  3. package/dist/bin/cli.cjs +1604 -0
  4. package/dist/config/client.cjs +54 -0
  5. package/dist/config/client.cjs.map +1 -0
  6. package/dist/config/client.d.ts +23 -0
  7. package/dist/config/client.js +28 -0
  8. package/dist/config/client.js.map +1 -0
  9. package/dist/config/edge.cjs +508 -0
  10. package/dist/config/edge.cjs.map +1 -0
  11. package/dist/config/edge.d.ts +20 -0
  12. package/dist/config/edge.js +481 -0
  13. package/dist/config/edge.js.map +1 -0
  14. package/dist/config.cjs +1254 -0
  15. package/dist/config.cjs.map +1 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +1212 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/index-eff254d8.d.ts +175 -0
  20. package/dist/micro-frontend-config-42886104.d.ts +154 -0
  21. package/dist/next/client.cjs +3 -0
  22. package/dist/next/client.cjs.map +1 -0
  23. package/dist/next/client.d.ts +45 -0
  24. package/dist/next/client.js +3 -0
  25. package/dist/next/client.js.map +1 -0
  26. package/dist/next/config.cjs +1793 -0
  27. package/dist/next/config.cjs.map +1 -0
  28. package/dist/next/config.d.ts +22 -0
  29. package/dist/next/config.js +1758 -0
  30. package/dist/next/config.js.map +1 -0
  31. package/dist/next/endpoints.cjs +82 -0
  32. package/dist/next/endpoints.cjs.map +1 -0
  33. package/dist/next/endpoints.d.ts +15 -0
  34. package/dist/next/endpoints.js +57 -0
  35. package/dist/next/endpoints.js.map +1 -0
  36. package/dist/next/middleware.cjs +763 -0
  37. package/dist/next/middleware.cjs.map +1 -0
  38. package/dist/next/middleware.d.ts +29 -0
  39. package/dist/next/middleware.js +735 -0
  40. package/dist/next/middleware.js.map +1 -0
  41. package/dist/next/testing.cjs +1430 -0
  42. package/dist/next/testing.cjs.map +1 -0
  43. package/dist/next/testing.d.ts +53 -0
  44. package/dist/next/testing.js +1389 -0
  45. package/dist/next/testing.js.map +1 -0
  46. package/dist/overrides.cjs +143 -0
  47. package/dist/overrides.cjs.map +1 -0
  48. package/dist/overrides.d.ts +2 -0
  49. package/dist/overrides.js +115 -0
  50. package/dist/overrides.js.map +1 -0
  51. package/dist/schema-83a75e61.d.ts +188 -0
  52. package/dist/types-4fd1c7c6.d.ts +157 -0
  53. package/dist/v2/config.cjs +720 -0
  54. package/dist/v2/config.cjs.map +1 -0
  55. package/dist/v2/config.d.ts +2 -0
  56. package/dist/v2/config.js +695 -0
  57. package/dist/v2/config.js.map +1 -0
  58. package/dist/v2/microfrontends/server.cjs +1312 -0
  59. package/dist/v2/microfrontends/server.cjs.map +1 -0
  60. package/dist/v2/microfrontends/server.d.ts +48 -0
  61. package/dist/v2/microfrontends/server.js +1277 -0
  62. package/dist/v2/microfrontends/server.js.map +1 -0
  63. package/dist/v2/microfrontends.cjs +803 -0
  64. package/dist/v2/microfrontends.cjs.map +1 -0
  65. package/dist/v2/microfrontends.d.ts +44 -0
  66. package/dist/v2/microfrontends.js +776 -0
  67. package/dist/v2/microfrontends.js.map +1 -0
  68. package/dist/v2/next/client.cjs +3 -0
  69. package/dist/v2/next/client.cjs.map +1 -0
  70. package/dist/v2/next/client.d.ts +45 -0
  71. package/dist/v2/next/client.js +3 -0
  72. package/dist/v2/next/client.js.map +1 -0
  73. package/dist/v2/next/config.cjs +1829 -0
  74. package/dist/v2/next/config.cjs.map +1 -0
  75. package/dist/v2/next/config.d.ts +22 -0
  76. package/dist/v2/next/config.js +1794 -0
  77. package/dist/v2/next/config.js.map +1 -0
  78. package/dist/v2/next/endpoints.cjs +138 -0
  79. package/dist/v2/next/endpoints.cjs.map +1 -0
  80. package/dist/v2/next/endpoints.d.ts +15 -0
  81. package/dist/v2/next/endpoints.js +113 -0
  82. package/dist/v2/next/endpoints.js.map +1 -0
  83. package/dist/v2/next/middleware.cjs +1110 -0
  84. package/dist/v2/next/middleware.cjs.map +1 -0
  85. package/dist/v2/next/middleware.d.ts +29 -0
  86. package/dist/v2/next/middleware.js +1082 -0
  87. package/dist/v2/next/middleware.js.map +1 -0
  88. package/dist/v2/schema.cjs +19 -0
  89. package/dist/v2/schema.cjs.map +1 -0
  90. package/dist/v2/schema.d.ts +1 -0
  91. package/dist/v2/schema.js +1 -0
  92. package/dist/v2/schema.js.map +1 -0
  93. package/dist/validation.cjs +754 -0
  94. package/dist/validation.cjs.map +1 -0
  95. package/dist/validation.d.ts +163 -0
  96. package/dist/validation.js +726 -0
  97. package/dist/validation.js.map +1 -0
  98. package/package.json +204 -0
  99. package/schema/schema-v2.json +288 -0
  100. package/schema/schema.json +352 -0
@@ -0,0 +1,1110 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/next-v2/middleware/index.ts
21
+ var middleware_exports = {};
22
+ __export(middleware_exports, {
23
+ getMicroFrontendsMiddleware: () => getMicroFrontendsMiddleware,
24
+ runMicroFrontendsMiddleware: () => runMicroFrontendsMiddleware
25
+ });
26
+ module.exports = __toCommonJS(middleware_exports);
27
+
28
+ // src/next-v2/middleware/middleware.ts
29
+ var import_server = require("next/server");
30
+ var import_path_to_regexp3 = require("path-to-regexp");
31
+
32
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
33
+ var import_jsonc_parser = require("jsonc-parser");
34
+
35
+ // src/config-v2/errors.ts
36
+ var MicroFrontendError = class extends Error {
37
+ constructor(message, opts) {
38
+ super(message);
39
+ this.name = "MicroFrontendsError";
40
+ this.source = (opts == null ? void 0 : opts.source) ?? "@vercel/micro-frontends";
41
+ this.type = (opts == null ? void 0 : opts.type) ?? "unknown";
42
+ this.subtype = opts == null ? void 0 : opts.subtype;
43
+ Error.captureStackTrace(this, MicroFrontendError);
44
+ }
45
+ isKnown() {
46
+ return this.type !== "unknown";
47
+ }
48
+ isUnknown() {
49
+ return !this.isKnown();
50
+ }
51
+ /**
52
+ * Converts an error to a MicroFrontendsError.
53
+ * @param original - The original error to convert.
54
+ * @returns The converted MicroFrontendsError.
55
+ */
56
+ static convert(original, opts) {
57
+ if (opts == null ? void 0 : opts.fileName) {
58
+ const err = MicroFrontendError.convertFSError(original, opts.fileName);
59
+ if (err) {
60
+ return err;
61
+ }
62
+ }
63
+ if (original.message.includes(
64
+ "Code generation from strings disallowed for this context"
65
+ )) {
66
+ return new MicroFrontendError(original.message, {
67
+ type: "config",
68
+ subtype: "unsupported_validation_env",
69
+ source: "ajv"
70
+ });
71
+ }
72
+ return new MicroFrontendError(original.message);
73
+ }
74
+ static convertFSError(original, fileName) {
75
+ if (original instanceof Error && "code" in original) {
76
+ if (original.code === "ENOENT") {
77
+ return new MicroFrontendError(`Could not find "${fileName}"`, {
78
+ type: "config",
79
+ subtype: "unable_to_read_file",
80
+ source: "fs"
81
+ });
82
+ }
83
+ if (original.code === "EACCES") {
84
+ return new MicroFrontendError(
85
+ `Permission denied while accessing "${fileName}"`,
86
+ {
87
+ type: "config",
88
+ subtype: "invalid_permissions",
89
+ source: "fs"
90
+ }
91
+ );
92
+ }
93
+ }
94
+ if (original instanceof SyntaxError) {
95
+ return new MicroFrontendError(
96
+ `Failed to parse "${fileName}": Invalid JSON format.`,
97
+ {
98
+ type: "config",
99
+ subtype: "invalid_syntax",
100
+ source: "fs"
101
+ }
102
+ );
103
+ }
104
+ return null;
105
+ }
106
+ /**
107
+ * Handles an unknown error and returns a MicroFrontendsError instance.
108
+ * @param err - The error to handle.
109
+ * @returns A MicroFrontendsError instance.
110
+ */
111
+ static handle(err, opts) {
112
+ if (err instanceof MicroFrontendError) {
113
+ return err;
114
+ }
115
+ if (err instanceof Error) {
116
+ return MicroFrontendError.convert(err, opts);
117
+ }
118
+ if (typeof err === "object" && err !== null) {
119
+ if ("message" in err && typeof err.message === "string") {
120
+ return MicroFrontendError.convert(new Error(err.message), opts);
121
+ }
122
+ }
123
+ return new MicroFrontendError("An unknown error occurred");
124
+ }
125
+ };
126
+
127
+ // src/config-v2/microfrontends-config/utils/get-config-from-env.ts
128
+ function getConfigStringFromEnv() {
129
+ const config = process.env.MFE_CONFIG;
130
+ if (!config) {
131
+ throw new MicroFrontendError(`Missing "MFE_CONFIG" in environment.`, {
132
+ type: "config",
133
+ subtype: "not_found_in_env"
134
+ });
135
+ }
136
+ return config;
137
+ }
138
+
139
+ // src/config-v2/schema/utils/is-main-config.ts
140
+ function isMainConfig(c) {
141
+ return !("partOf" in c);
142
+ }
143
+
144
+ // src/config-v2/schema/utils/is-default-app.ts
145
+ function isDefaultApp(a) {
146
+ return !("routing" in a);
147
+ }
148
+
149
+ // src/config-v2/microfrontends-config/client/index.ts
150
+ var import_path_to_regexp = require("path-to-regexp");
151
+ var MicroFrontendConfigClient = class {
152
+ constructor(config, opts) {
153
+ this.pathCache = {};
154
+ this.serialized = config;
155
+ if (opts == null ? void 0 : opts.removeFlaggedPaths) {
156
+ for (const app of Object.values(config.applications)) {
157
+ if (app.routing) {
158
+ app.routing = app.routing.filter((match) => !match.flag);
159
+ }
160
+ }
161
+ }
162
+ this.applications = config.applications;
163
+ }
164
+ /**
165
+ * Create a new `MicroFrontendConfigClient` from a JSON string.
166
+ * Config must be passed in to remain framework agnostic
167
+ */
168
+ static fromEnv(config, opts) {
169
+ if (!config) {
170
+ throw new Error("No micro-frontends configuration found");
171
+ }
172
+ return new MicroFrontendConfigClient(
173
+ JSON.parse(config),
174
+ opts
175
+ );
176
+ }
177
+ isEqual(other) {
178
+ return JSON.stringify(this.applications) === JSON.stringify(other.applications);
179
+ }
180
+ getApplicationNameForPath(path) {
181
+ if (!path.startsWith("/")) {
182
+ throw new Error(`Path must start with a /`);
183
+ }
184
+ if (this.pathCache[path]) {
185
+ return this.pathCache[path];
186
+ }
187
+ const pathname = new URL(path, "https://example.com").pathname;
188
+ for (const [name, application] of Object.entries(this.applications)) {
189
+ if (application.routing) {
190
+ for (const group of application.routing) {
191
+ for (const childPath of group.paths) {
192
+ const regexp = (0, import_path_to_regexp.pathToRegexp)(childPath);
193
+ if (regexp.test(pathname)) {
194
+ this.pathCache[path] = name;
195
+ return name;
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+ const defaultApplication = Object.entries(this.applications).find(
202
+ ([, application]) => application.default
203
+ );
204
+ if (!defaultApplication) {
205
+ return null;
206
+ }
207
+ this.pathCache[path] = defaultApplication[0];
208
+ return defaultApplication[0];
209
+ }
210
+ serialize() {
211
+ return this.serialized;
212
+ }
213
+ };
214
+
215
+ // src/config-v2/overrides/constants.ts
216
+ var OVERRIDES_COOKIE_PREFIX = "vercel-microfrontends-override";
217
+ var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
218
+
219
+ // src/config-v2/overrides/is-override-cookie.ts
220
+ function isOverrideCookie(cookie) {
221
+ var _a;
222
+ return Boolean((_a = cookie.name) == null ? void 0 : _a.startsWith(OVERRIDES_COOKIE_PREFIX));
223
+ }
224
+
225
+ // src/config-v2/overrides/get-override-from-cookie.ts
226
+ function getOverrideFromCookie(cookie) {
227
+ if (!isOverrideCookie(cookie) || !cookie.value)
228
+ return;
229
+ return {
230
+ application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
231
+ host: cookie.value
232
+ };
233
+ }
234
+
235
+ // src/config-v2/overrides/parse-overrides.ts
236
+ function parseOverrides(cookies) {
237
+ const overridesConfig = { applications: {} };
238
+ cookies.forEach((cookie) => {
239
+ const override = getOverrideFromCookie(cookie);
240
+ if (!override)
241
+ return;
242
+ overridesConfig.applications[override.application] = {
243
+ environment: { host: override.host }
244
+ };
245
+ });
246
+ return overridesConfig;
247
+ }
248
+
249
+ // src/config-v2/microfrontends-config/isomorphic/validation.ts
250
+ var import_path_to_regexp2 = require("path-to-regexp");
251
+ var SUPPORTED_VERSIONS = ["2"];
252
+ var validateConfigVersion = (version) => {
253
+ if (!SUPPORTED_VERSIONS.includes(version)) {
254
+ throw new MicroFrontendError(
255
+ `Unsupported version: ${version}. Supported versions are: ${SUPPORTED_VERSIONS.join(
256
+ ", "
257
+ )}`,
258
+ { type: "config", subtype: "unsupported_version" }
259
+ );
260
+ }
261
+ };
262
+ var validateConfigPaths = (applicationConfigsById) => {
263
+ if (!applicationConfigsById) {
264
+ return;
265
+ }
266
+ const pathsByApplicationId = /* @__PURE__ */ new Map();
267
+ const errors = [];
268
+ for (const [id, app] of Object.entries(applicationConfigsById)) {
269
+ if (isDefaultApp(app)) {
270
+ continue;
271
+ }
272
+ for (const pathMatch of app.routing) {
273
+ for (const path of pathMatch.paths) {
274
+ const tokens = (0, import_path_to_regexp2.parse)(path);
275
+ for (const token of tokens.slice(0, -1)) {
276
+ if (typeof token !== "string") {
277
+ errors.push(
278
+ `Path ${path} may only have a :wildcard in the last path component`
279
+ );
280
+ }
281
+ }
282
+ const existing = pathsByApplicationId.get(path);
283
+ if (existing) {
284
+ existing.applications.push(id);
285
+ } else {
286
+ pathsByApplicationId.set(path, {
287
+ applications: [id],
288
+ matcher: (0, import_path_to_regexp2.pathToRegexp)(path),
289
+ applicationId: id
290
+ });
291
+ }
292
+ }
293
+ }
294
+ }
295
+ const entries = Array.from(pathsByApplicationId.entries());
296
+ entries.forEach(([path, { applications: ids, matcher, applicationId }]) => {
297
+ if (ids.length > 1) {
298
+ errors.push(
299
+ `Duplicate path "${path}" for applications "${ids.join(", ")}"`
300
+ );
301
+ }
302
+ entries.forEach(
303
+ ([
304
+ matchPath,
305
+ { applications: matchIds, applicationId: matchApplicationId }
306
+ ]) => {
307
+ if (path === matchPath) {
308
+ return;
309
+ }
310
+ if (applicationId === matchApplicationId) {
311
+ return;
312
+ }
313
+ if (matcher.test(matchPath)) {
314
+ const source = `"${path}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
315
+ const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
316
+ errors.push(
317
+ `Overlapping path detected between ${source} and ${destination}`
318
+ );
319
+ }
320
+ }
321
+ );
322
+ });
323
+ if (errors.length) {
324
+ throw new MicroFrontendError(`Invalid paths: ${errors.join(", ")}`, {
325
+ type: "config",
326
+ subtype: "conflicting_paths"
327
+ });
328
+ }
329
+ };
330
+ var validateAppPaths = (name, app) => {
331
+ for (const group of app.routing) {
332
+ for (const p of group.paths) {
333
+ if (p === "/") {
334
+ continue;
335
+ }
336
+ if (p.endsWith("/")) {
337
+ throw new MicroFrontendError(
338
+ `Invalid path for application "${name}". ${p} must not end with a slash.`,
339
+ { type: "application", subtype: "invalid_path" }
340
+ );
341
+ }
342
+ if (!p.startsWith("/")) {
343
+ throw new MicroFrontendError(
344
+ `Invalid path for application "${name}". ${p} must start with a slash.`,
345
+ { type: "application", subtype: "invalid_path" }
346
+ );
347
+ }
348
+ }
349
+ }
350
+ };
351
+ var validateConfigDefaultApplication = (applicationConfigsById) => {
352
+ if (!applicationConfigsById) {
353
+ return;
354
+ }
355
+ const applicationsWithRouting = Object.entries(applicationConfigsById).filter(
356
+ ([, app]) => !isDefaultApp(app)
357
+ );
358
+ const applicationsWithRoutingNames = applicationsWithRouting.map(
359
+ ([key]) => key
360
+ );
361
+ const numApplications = Object.keys(applicationConfigsById).length;
362
+ const numApplicationsWithRouting = applicationsWithRoutingNames.length;
363
+ const numApplicationsWithoutRouting = numApplications - numApplicationsWithRouting;
364
+ if (numApplicationsWithoutRouting === 0) {
365
+ throw new MicroFrontendError(
366
+ `No default application found. At least one application needs to be the default by omitting routing.`,
367
+ { type: "config", subtype: "no_default_application" }
368
+ );
369
+ }
370
+ if (numApplicationsWithoutRouting > 1) {
371
+ throw new MicroFrontendError(
372
+ `Only one application can omit "routing". Found ${applicationsWithRoutingNames.length - Object.keys(applicationConfigsById).length > 1}.`,
373
+ { type: "config", subtype: "multiple_default_applications" }
374
+ );
375
+ }
376
+ };
377
+ var validateConfigOptions = (options) => {
378
+ var _a;
379
+ if ((_a = options == null ? void 0 : options.vercel) == null ? void 0 : _a.previewDeploymentSuffix) {
380
+ if (!/^[a-zA-Z]{2,}\.[a-zA-Z]{2,}$/.test(
381
+ options.vercel.previewDeploymentSuffix
382
+ )) {
383
+ throw new MicroFrontendError(
384
+ `Invalid preview deployment suffix: ${options.vercel.previewDeploymentSuffix}. Should have be formatted like "vercel.app".`,
385
+ { type: "config", subtype: "invalid_preview_deployment_suffix" }
386
+ );
387
+ }
388
+ }
389
+ };
390
+
391
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
392
+ var PREFIX = "vc-ap";
393
+ function generateAssetPrefixFromName({
394
+ name
395
+ }) {
396
+ if (!name) {
397
+ throw new Error("Name is required to generate an asset prefix");
398
+ }
399
+ return `${PREFIX}-${name}`;
400
+ }
401
+
402
+ // src/config-v2/microfrontends-config/isomorphic/utils/generate-port.ts
403
+ function generatePortFromName({
404
+ name,
405
+ minPort = 3e3,
406
+ maxPort = 8e3
407
+ }) {
408
+ if (!name) {
409
+ throw new Error("Name is required to generate a port");
410
+ }
411
+ let hash = 0;
412
+ for (let i = 0; i < name.length; i++) {
413
+ hash = (hash << 5) - hash + name.charCodeAt(i);
414
+ hash |= 0;
415
+ }
416
+ hash = Math.abs(hash);
417
+ const range = maxPort - minPort;
418
+ const port = minPort + hash % range;
419
+ return port;
420
+ }
421
+
422
+ // src/config-v2/microfrontends-config/isomorphic/host.ts
423
+ var Host = class {
424
+ constructor(hostConfig, options) {
425
+ const { protocol = "https", host, port } = hostConfig;
426
+ this.protocol = protocol;
427
+ this.host = host;
428
+ this.port = Host.getPort({ port, protocol: this.protocol });
429
+ this.local = options == null ? void 0 : options.isLocal;
430
+ }
431
+ isLocal() {
432
+ return this.local || this.host === "localhost" || this.host === "127.0.0.1";
433
+ }
434
+ static getPort({
435
+ protocol,
436
+ port
437
+ }) {
438
+ if (!port) {
439
+ if (protocol === "http") {
440
+ return 80;
441
+ }
442
+ return 443;
443
+ }
444
+ return port;
445
+ }
446
+ isDefaultPort() {
447
+ return this.port === Host.getPort({ protocol: this.protocol });
448
+ }
449
+ toString(opts = {}) {
450
+ const url = this.toUrl(opts);
451
+ return url.toString().replace(/\/$/, "");
452
+ }
453
+ toUrl(opts = {}) {
454
+ const { includeDefaultPort } = opts;
455
+ const url = `${this.protocol}://${this.host}${this.isDefaultPort() && !includeDefaultPort ? "" : `:${this.port}`}`;
456
+ return new URL(url);
457
+ }
458
+ };
459
+ var LocalHost = class extends Host {
460
+ constructor({
461
+ appName,
462
+ ...hostConfig
463
+ }) {
464
+ const host = hostConfig.host ?? "localhost";
465
+ const port = hostConfig.port ?? generatePortFromName({ name: appName });
466
+ const protocol = hostConfig.protocol ?? "http";
467
+ super({ protocol, host, port });
468
+ }
469
+ };
470
+
471
+ // src/config-v2/microfrontends-config/isomorphic/application.ts
472
+ var Application = class {
473
+ constructor(name, {
474
+ app,
475
+ overrides,
476
+ isDefault
477
+ }) {
478
+ var _a, _b;
479
+ this.name = name;
480
+ this.development = {
481
+ local: new LocalHost({
482
+ appName: name,
483
+ ...(_a = app.development) == null ? void 0 : _a.local
484
+ }),
485
+ fallback: ((_b = app.development) == null ? void 0 : _b.fallback) ? new Host(app.development.fallback) : void 0
486
+ };
487
+ this.production = app.production ? new Host(app.production) : void 0;
488
+ this.vercel = app.vercel;
489
+ this.overrides = (overrides == null ? void 0 : overrides.environment) ? {
490
+ environment: new Host(overrides.environment)
491
+ } : void 0;
492
+ this.default = isDefault ?? false;
493
+ this.serialized = app;
494
+ }
495
+ isDefault() {
496
+ return this.default;
497
+ }
498
+ getAssetPrefix() {
499
+ return generateAssetPrefixFromName({ name: this.name });
500
+ }
501
+ serialize() {
502
+ return this.serialized;
503
+ }
504
+ };
505
+ var DefaultApplication = class extends Application {
506
+ constructor(name, {
507
+ app,
508
+ overrides
509
+ }) {
510
+ super(name, {
511
+ app,
512
+ overrides,
513
+ isDefault: true
514
+ });
515
+ this.default = true;
516
+ this.production = new Host(app.production);
517
+ }
518
+ };
519
+ var ChildApplication = class extends Application {
520
+ constructor(name, {
521
+ app,
522
+ overrides
523
+ }) {
524
+ ChildApplication.validate(name, app);
525
+ super(name, {
526
+ app,
527
+ overrides,
528
+ isDefault: false
529
+ });
530
+ this.default = false;
531
+ this.routing = app.routing;
532
+ }
533
+ static validate(name, app) {
534
+ validateAppPaths(name, app);
535
+ }
536
+ };
537
+
538
+ // src/config-v2/microfrontends-config/isomorphic/constants.ts
539
+ var DEFAULT_LOCAL_PROXY_PORT = 3024;
540
+
541
+ // src/config-v2/microfrontends-config/isomorphic/index.ts
542
+ var MicroFrontendConfigIsomorphic = class {
543
+ constructor({
544
+ config,
545
+ overrides,
546
+ meta
547
+ }) {
548
+ this.childApplications = {};
549
+ var _a, _b, _c, _d;
550
+ MicroFrontendConfigIsomorphic.validate(config);
551
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
552
+ this.overrides = overrides && !disableOverrides ? overrides : void 0;
553
+ this.isMainConfig = isMainConfig(config);
554
+ if (isMainConfig(config)) {
555
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
556
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
557
+ if (isDefaultApp(appConfig)) {
558
+ this.defaultApplication = new DefaultApplication(appId, {
559
+ app: appConfig,
560
+ overrides: appOverrides
561
+ });
562
+ } else {
563
+ this.childApplications[appId] = new ChildApplication(appId, {
564
+ app: appConfig,
565
+ overrides: appOverrides
566
+ });
567
+ }
568
+ }
569
+ } else {
570
+ this.partOf = config.partOf;
571
+ const appOverrides = !disableOverrides ? (_d = this.overrides) == null ? void 0 : _d.applications[meta.fromApp] : void 0;
572
+ this.childApplications[meta.fromApp] = new ChildApplication(
573
+ meta.fromApp,
574
+ {
575
+ // we don't know routing because we're not in the main config
576
+ app: { routing: [] },
577
+ overrides: appOverrides
578
+ }
579
+ );
580
+ }
581
+ if (isMainConfig(config) && !this.defaultApplication) {
582
+ throw new MicroFrontendError(
583
+ `Could not find default application in microfrontends configuration`,
584
+ {
585
+ type: "application",
586
+ subtype: "not_found"
587
+ }
588
+ );
589
+ }
590
+ this.config = config;
591
+ this.options = config.options;
592
+ this.serialized = {
593
+ config,
594
+ overrides,
595
+ meta
596
+ };
597
+ }
598
+ static validate(config) {
599
+ const c = typeof config === "string" ? (0, import_jsonc_parser.parse)(config) : config;
600
+ if (isMainConfig(c)) {
601
+ validateConfigVersion(c.version);
602
+ validateConfigPaths(c.applications);
603
+ validateConfigDefaultApplication(c.applications);
604
+ }
605
+ validateConfigOptions(c.options);
606
+ return c;
607
+ }
608
+ static fromEnv({
609
+ meta,
610
+ cookies
611
+ }) {
612
+ return new MicroFrontendConfigIsomorphic({
613
+ config: (0, import_jsonc_parser.parse)(getConfigStringFromEnv()),
614
+ overrides: parseOverrides(cookies ?? []),
615
+ meta
616
+ });
617
+ }
618
+ isOverridesDisabled() {
619
+ var _a, _b;
620
+ return ((_b = (_a = this.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
621
+ }
622
+ getConfig() {
623
+ return this.config;
624
+ }
625
+ getApplicationsByType() {
626
+ return {
627
+ defaultApplication: this.defaultApplication,
628
+ applications: Object.values(this.childApplications)
629
+ };
630
+ }
631
+ getChildApplications() {
632
+ return Object.values(this.childApplications);
633
+ }
634
+ getAllApplications() {
635
+ return [
636
+ this.defaultApplication,
637
+ ...Object.values(this.childApplications)
638
+ ].filter(Boolean);
639
+ }
640
+ getApplication(name) {
641
+ var _a;
642
+ if (((_a = this.defaultApplication) == null ? void 0 : _a.name) === name) {
643
+ return this.defaultApplication;
644
+ }
645
+ const app = this.childApplications[name];
646
+ if (!app) {
647
+ throw new MicroFrontendError(
648
+ `Could not find microfrontends configuration for application "${name}"`,
649
+ {
650
+ type: "application",
651
+ subtype: "not_found"
652
+ }
653
+ );
654
+ }
655
+ return app;
656
+ }
657
+ getApplicationByProjectId(projectId) {
658
+ var _a, _b;
659
+ if (((_b = (_a = this.defaultApplication) == null ? void 0 : _a.vercel) == null ? void 0 : _b.projectId) === projectId) {
660
+ return this.defaultApplication;
661
+ }
662
+ return Object.values(this.childApplications).find(
663
+ (app) => {
664
+ var _a2;
665
+ return ((_a2 = app.vercel) == null ? void 0 : _a2.projectId) === projectId;
666
+ }
667
+ );
668
+ }
669
+ /**
670
+ * Returns the default application. This can throw if the default application
671
+ * is undefined ( )
672
+ */
673
+ getDefaultApplication() {
674
+ if (!this.defaultApplication) {
675
+ throw new MicroFrontendError(
676
+ `Could not find default application in microfrontends configuration`,
677
+ {
678
+ type: "application",
679
+ subtype: "not_found"
680
+ }
681
+ );
682
+ }
683
+ return this.defaultApplication;
684
+ }
685
+ /**
686
+ * Returns the configured port for the local proxy
687
+ */
688
+ getLocalProxyPort() {
689
+ var _a, _b;
690
+ return ((_b = (_a = this.config.options) == null ? void 0 : _a.localProxy) == null ? void 0 : _b.port) ?? DEFAULT_LOCAL_PROXY_PORT;
691
+ }
692
+ /**
693
+ * Serializes the class back to the Schema type.
694
+ *
695
+ * NOTE: This is used when writing the config to disk and must always match the input Schema
696
+ */
697
+ toSchemaJson() {
698
+ return this.serialized.config;
699
+ }
700
+ toClientConfig() {
701
+ const applications = Object.fromEntries(
702
+ Object.entries(this.childApplications).map(([name, application]) => [
703
+ name,
704
+ {
705
+ default: false,
706
+ routing: application.routing
707
+ }
708
+ ])
709
+ );
710
+ if (this.defaultApplication) {
711
+ applications[this.defaultApplication.name] = {
712
+ default: true
713
+ };
714
+ }
715
+ return new MicroFrontendConfigClient({
716
+ applications
717
+ });
718
+ }
719
+ serialize() {
720
+ return this.serialized;
721
+ }
722
+ };
723
+
724
+ // src/config-v2/microfrontends-config/isomorphic/child.ts
725
+ var MicroFrontendChildConfig = class extends MicroFrontendConfigIsomorphic {
726
+ constructor({
727
+ config,
728
+ overrides,
729
+ meta
730
+ }) {
731
+ super({ config, overrides, meta });
732
+ this.isMainConfig = false;
733
+ this.partOf = config.partOf;
734
+ }
735
+ };
736
+
737
+ // src/config-v2/microfrontends-config/isomorphic/main.ts
738
+ var MicroFrontendMainConfig = class extends MicroFrontendConfigIsomorphic {
739
+ constructor({
740
+ config,
741
+ overrides,
742
+ meta
743
+ }) {
744
+ var _a, _b, _c;
745
+ super({ config, overrides, meta });
746
+ this.isMainConfig = true;
747
+ this.provider = config.provider;
748
+ const disableOverrides = ((_b = (_a = config.options) == null ? void 0 : _a.vercel) == null ? void 0 : _b.disableOverrides) ?? false;
749
+ let defaultApplication;
750
+ for (const [appId, appConfig] of Object.entries(config.applications)) {
751
+ const appOverrides = !disableOverrides ? (_c = this.overrides) == null ? void 0 : _c.applications[appId] : void 0;
752
+ if (isDefaultApp(appConfig)) {
753
+ defaultApplication = new DefaultApplication(appId, {
754
+ app: appConfig,
755
+ overrides: appOverrides
756
+ });
757
+ } else {
758
+ this.childApplications[appId] = new ChildApplication(appId, {
759
+ app: appConfig,
760
+ overrides: appOverrides
761
+ });
762
+ }
763
+ }
764
+ if (!defaultApplication) {
765
+ throw new MicroFrontendError(
766
+ `Could not find default application in microfrontends configuration`,
767
+ {
768
+ type: "application",
769
+ subtype: "not_found"
770
+ }
771
+ );
772
+ }
773
+ this.defaultApplication = defaultApplication;
774
+ }
775
+ };
776
+
777
+ // src/config-v2/microfrontends/isomorphic/index.ts
778
+ var Microfrontends = class {
779
+ constructor({
780
+ config,
781
+ overrides,
782
+ meta
783
+ }) {
784
+ if (isMainConfig(config)) {
785
+ this.config = new MicroFrontendMainConfig({ config, overrides, meta });
786
+ } else {
787
+ this.config = new MicroFrontendChildConfig({ config, overrides, meta });
788
+ }
789
+ }
790
+ isChildConfig() {
791
+ return this.config instanceof MicroFrontendChildConfig;
792
+ }
793
+ static fromEnv({
794
+ cookies,
795
+ meta
796
+ }) {
797
+ const config = MicroFrontendConfigIsomorphic.fromEnv({
798
+ cookies,
799
+ meta
800
+ });
801
+ return new Microfrontends(config.serialize());
802
+ }
803
+ };
804
+
805
+ // src/routing-v2/get-domain-from-environment.ts
806
+ function getDomainFromEnvironment({
807
+ app,
808
+ target
809
+ }) {
810
+ const projects = JSON.parse(
811
+ process.env.VERCEL_RELATED_PROJECTS ?? "[]"
812
+ );
813
+ if (projects.length === 0) {
814
+ throw new Error("Missing related vercel project information");
815
+ }
816
+ const vercelProject = projects.find(
817
+ (project) => {
818
+ var _a;
819
+ return project.projectId === ((_a = app.vercel) == null ? void 0 : _a.projectId) || project.appName === app.name;
820
+ }
821
+ );
822
+ if (!vercelProject) {
823
+ throw new Error(
824
+ `Missing related vercel project information for application "${app.name}"`
825
+ );
826
+ }
827
+ return vercelProject.aliases[target];
828
+ }
829
+
830
+ // src/routing-v2/get-domain-for-current-environment.ts
831
+ function debugDomains(zone, env, domain) {
832
+ if (process.env.MFE_DEBUG === "true") {
833
+ const indent = " ".repeat(4);
834
+ const header = "domains (zone (env) -> domain)";
835
+ const separator = "\u23AF".repeat(header.length);
836
+ const line = `${indent} 1. ${zone} (${env}) -> ${domain}`;
837
+ console.log(`${indent}${header}
838
+ ${indent}${separator}
839
+ ${line}
840
+ `);
841
+ }
842
+ }
843
+ function getCurrentEnvironment() {
844
+ const isDevelopment = !process.env.VERCEL_ENV || process.env.VERCEL_ENV === "development";
845
+ const isPreview = process.env.VERCEL_ENV === "preview";
846
+ const isProduction = process.env.VERCEL_ENV === "production";
847
+ if (isDevelopment) {
848
+ return { group: "development" };
849
+ } else if (isProduction) {
850
+ return { group: "production" };
851
+ } else if (isPreview) {
852
+ return { group: "preview" };
853
+ }
854
+ return { group: "custom", name: process.env.VERCEL_ENV };
855
+ }
856
+ function getDomainForCurrentEnvironment(config, appName) {
857
+ var _a;
858
+ const app = config.getApplication(appName);
859
+ if ((_a = app.overrides) == null ? void 0 : _a.environment) {
860
+ return app.overrides.environment.toString();
861
+ }
862
+ const { group } = getCurrentEnvironment();
863
+ const productionHost = config.getDefaultApplication().production.toString();
864
+ switch (group) {
865
+ case "development": {
866
+ const domain = process.env.NODE_ENV === "test" ? app.development.local.toString() : productionHost;
867
+ debugDomains(appName, "development", domain);
868
+ return domain;
869
+ }
870
+ case "preview": {
871
+ return getDomainFromEnvironment({ app, target: "branch" });
872
+ }
873
+ case "production": {
874
+ return getDomainFromEnvironment({ app, target: "production" });
875
+ }
876
+ case "custom":
877
+ console.warn(
878
+ `Custom environments are not supported in getDomainForCurrentEnvironment`
879
+ );
880
+ return productionHost;
881
+ }
882
+ }
883
+
884
+ // src/next-v2/middleware/middleware.ts
885
+ async function verifyPreviewDomain(req, rewriteDomain) {
886
+ var _a;
887
+ const jwtCookie = (_a = req.cookies.get("_vercel_jwt")) == null ? void 0 : _a.value;
888
+ const deploymentProtectionBypassHeader = req.headers.get(
889
+ "x-vercel-protection-bypass"
890
+ );
891
+ const previewResponse = await fetch(rewriteDomain, {
892
+ method: "HEAD",
893
+ headers: {
894
+ "x-vercel-micro-frontends-check": "1",
895
+ ...jwtCookie ? { cookie: `_vercel_jwt=${jwtCookie}` } : {},
896
+ ...deploymentProtectionBypassHeader ? {
897
+ "x-vercel-protection-bypass": deploymentProtectionBypassHeader
898
+ } : {}
899
+ }
900
+ });
901
+ const vercelError = previewResponse.headers.get("x-vercel-error");
902
+ return !(previewResponse.status === 404 && (vercelError === "DEPLOYMENT_NOT_FOUND" || vercelError === "NOT_FOUND"));
903
+ }
904
+ function microFrontendInternalRoutingHandler({
905
+ config,
906
+ production
907
+ }) {
908
+ return async (req) => {
909
+ const payload = Object.fromEntries(
910
+ await Promise.all(
911
+ config.getAllApplications().map(async (application) => {
912
+ let rewriteDomain = getDomainForCurrentEnvironment(
913
+ config,
914
+ application.name
915
+ );
916
+ const isPreviewDomainAvailable = await verifyPreviewDomain(
917
+ req,
918
+ rewriteDomain
919
+ );
920
+ if (!isPreviewDomainAvailable) {
921
+ rewriteDomain = production.toString();
922
+ }
923
+ return [
924
+ application.name,
925
+ { routing: { host: rewriteDomain } }
926
+ ];
927
+ })
928
+ )
929
+ );
930
+ return import_server.NextResponse.json(payload);
931
+ };
932
+ }
933
+ function getHandler({
934
+ config,
935
+ application,
936
+ flagFn,
937
+ pattern,
938
+ production
939
+ }) {
940
+ return async (req) => {
941
+ var _a, _b;
942
+ const pathname = req.nextUrl.pathname;
943
+ const search = req.nextUrl.search;
944
+ let rewriteDomain = getDomainForCurrentEnvironment(
945
+ config,
946
+ application.name
947
+ );
948
+ const patchedHeaders = new Headers(req.headers);
949
+ const responseCallbacks = [];
950
+ const onRewrite = (response) => {
951
+ for (const callback of responseCallbacks) {
952
+ callback(response);
953
+ }
954
+ return response;
955
+ };
956
+ if (process.env.VERCEL_ENV === "preview" && rewriteDomain) {
957
+ const zoneFallbackCookieName = `__zone_${application.name}_production_fallback`;
958
+ const assetPrefix = application.getAssetPrefix();
959
+ if (assetPrefix && pathname.startsWith(`/${assetPrefix}`) && ((_a = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _a.value) === "1") {
960
+ rewriteDomain = production.toString();
961
+ } else {
962
+ try {
963
+ let deploymentFound;
964
+ if (req.headers.get("x-vercel-skip-deployment-existence-check")) {
965
+ deploymentFound = true;
966
+ } else {
967
+ deploymentFound = await verifyPreviewDomain(req, rewriteDomain);
968
+ }
969
+ if (!deploymentFound) {
970
+ rewriteDomain = production.toString();
971
+ responseCallbacks.push((response) => {
972
+ response.cookies.set(zoneFallbackCookieName, "1", {
973
+ httpOnly: true,
974
+ sameSite: "lax",
975
+ secure: true,
976
+ maxAge: 60
977
+ // 1 minute
978
+ });
979
+ });
980
+ try {
981
+ const existingCookie = patchedHeaders.get("cookie");
982
+ if (!(existingCookie == null ? void 0 : existingCookie.includes("__vercel_toolbar"))) {
983
+ patchedHeaders.set(
984
+ "cookie",
985
+ [`__vercel_toolbar=1`, existingCookie].join("; ")
986
+ );
987
+ responseCallbacks.push((response) => {
988
+ response.cookies.set("__vercel_toolbar", "1", {
989
+ httpOnly: false,
990
+ sameSite: "lax",
991
+ secure: true,
992
+ maxAge: 29030400
993
+ });
994
+ });
995
+ }
996
+ } catch (error) {
997
+ }
998
+ } else if (((_b = req.cookies.get(zoneFallbackCookieName)) == null ? void 0 : _b.value) === "1") {
999
+ responseCallbacks.push((response) => {
1000
+ response.cookies.set(zoneFallbackCookieName, "", {
1001
+ httpOnly: true,
1002
+ sameSite: "lax",
1003
+ secure: true,
1004
+ maxAge: 0
1005
+ });
1006
+ });
1007
+ }
1008
+ } catch {
1009
+ }
1010
+ }
1011
+ }
1012
+ const isFlagEnabled = async () => flagFn ? flagFn() : true;
1013
+ if (pattern.test(pathname) && await isFlagEnabled()) {
1014
+ return onRewrite(
1015
+ import_server.NextResponse.rewrite(`${rewriteDomain}${pathname}${search}`, {
1016
+ request: {
1017
+ headers: patchedHeaders
1018
+ }
1019
+ })
1020
+ );
1021
+ }
1022
+ };
1023
+ }
1024
+ function getMicroFrontendsMiddleware({
1025
+ request,
1026
+ flagValues
1027
+ }) {
1028
+ const microfrontends = Microfrontends.fromEnv({
1029
+ cookies: request.cookies.getAll(),
1030
+ meta: {
1031
+ fromApp: "vercel-site"
1032
+ }
1033
+ });
1034
+ const middlewares = [];
1035
+ if (microfrontends.config instanceof MicroFrontendChildConfig) {
1036
+ return middlewares;
1037
+ }
1038
+ const config = microfrontends.config;
1039
+ const production = config.defaultApplication.production;
1040
+ middlewares.push({
1041
+ src: "/.well-known/vercel/microfrontend-routing",
1042
+ fn: microFrontendInternalRoutingHandler({ config, production })
1043
+ });
1044
+ for (const application of config.getChildApplications()) {
1045
+ if (application.name === process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION) {
1046
+ continue;
1047
+ }
1048
+ if (process.env.VERCEL_ENV === "preview") {
1049
+ const pattern = (0, import_path_to_regexp3.pathToRegexp)(`/${application.getAssetPrefix()}/:path+`);
1050
+ middlewares.push({
1051
+ src: pattern,
1052
+ fn: getHandler({
1053
+ config,
1054
+ application,
1055
+ pattern,
1056
+ production
1057
+ })
1058
+ });
1059
+ }
1060
+ for (const pathGroup of application.routing) {
1061
+ if (process.env.VERCEL_ENV === "preview" || pathGroup.flag || pathGroup.routeToDefaultApplication) {
1062
+ const flagName = pathGroup.flag;
1063
+ let flagFn;
1064
+ if (flagName) {
1065
+ flagFn = flagValues == null ? void 0 : flagValues[flagName];
1066
+ if (!flagFn) {
1067
+ throw new Error(
1068
+ `Flag "${flagName}" was specified to control routing for path group "${pathGroup.group}" in application ${application.name} but not found in provided flag values.`
1069
+ );
1070
+ }
1071
+ }
1072
+ for (const path of pathGroup.paths) {
1073
+ const pattern = (0, import_path_to_regexp3.pathToRegexp)(path);
1074
+ middlewares.push({
1075
+ src: pattern,
1076
+ fn: getHandler({
1077
+ config,
1078
+ application,
1079
+ flagFn,
1080
+ pattern,
1081
+ production
1082
+ })
1083
+ });
1084
+ }
1085
+ }
1086
+ }
1087
+ }
1088
+ return middlewares;
1089
+ }
1090
+ async function runMicroFrontendsMiddleware(request, flagValues) {
1091
+ const pathname = request.nextUrl.pathname;
1092
+ const middlewares = getMicroFrontendsMiddleware({
1093
+ request,
1094
+ flagValues
1095
+ });
1096
+ for (const mware of middlewares) {
1097
+ if (typeof mware.src === "string" ? pathname === mware.src : mware.src.test(pathname)) {
1098
+ const response = await mware.fn(request);
1099
+ if (response) {
1100
+ return response;
1101
+ }
1102
+ }
1103
+ }
1104
+ }
1105
+ // Annotate the CommonJS export names for ESM import in node:
1106
+ 0 && (module.exports = {
1107
+ getMicroFrontendsMiddleware,
1108
+ runMicroFrontendsMiddleware
1109
+ });
1110
+ //# sourceMappingURL=middleware.cjs.map