@vercel/microfrontends
Version:
Defines configuration and utilities for microfrontends development
1,475 lines (1,435 loc) • 54.1 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/config/microfrontends/server/index.ts
var server_exports = {};
__export(server_exports, {
MicrofrontendsServer: () => MicrofrontendsServer,
getApplicationContext: () => getApplicationContext
});
module.exports = __toCommonJS(server_exports);
var import_node_fs7 = __toESM(require("fs"), 1);
var import_node_path8 = require("path");
// src/config/overrides/constants.ts
var OVERRIDES_COOKIE_PREFIX = "vercel-micro-frontends-override";
var OVERRIDES_ENV_COOKIE_PREFIX = `${OVERRIDES_COOKIE_PREFIX}:env:`;
// src/config/overrides/is-override-cookie.ts
function isOverrideCookie(cookie) {
return Boolean(cookie.name?.startsWith(OVERRIDES_COOKIE_PREFIX));
}
// src/config/overrides/get-override-from-cookie.ts
function getOverrideFromCookie(cookie) {
if (!isOverrideCookie(cookie) || !cookie.value)
return;
return {
application: cookie.name.replace(OVERRIDES_ENV_COOKIE_PREFIX, ""),
host: cookie.value
};
}
// src/config/overrides/parse-overrides.ts
function parseOverrides(cookies) {
const overridesConfig = { applications: {} };
cookies.forEach((cookie) => {
const override = getOverrideFromCookie(cookie);
if (!override)
return;
overridesConfig.applications[override.application] = {
environment: { host: override.host }
};
});
return overridesConfig;
}
// src/config/errors.ts
var MicrofrontendError = class extends Error {
constructor(message, opts) {
super(message, { cause: opts?.cause });
this.name = "MicrofrontendsError";
this.source = opts?.source ?? "@vercel/microfrontends";
this.type = opts?.type ?? "unknown";
this.subtype = opts?.subtype;
Error.captureStackTrace(this, MicrofrontendError);
}
isKnown() {
return this.type !== "unknown";
}
isUnknown() {
return !this.isKnown();
}
/**
* Converts an error to a MicrofrontendsError.
* @param original - The original error to convert.
* @returns The converted MicrofrontendsError.
*/
static convert(original, opts) {
if (opts?.fileName) {
const err = MicrofrontendError.convertFSError(original, opts.fileName);
if (err) {
return err;
}
}
if (original.message.includes(
"Code generation from strings disallowed for this context"
)) {
return new MicrofrontendError(original.message, {
type: "config",
subtype: "unsupported_validation_env",
source: "ajv"
});
}
return new MicrofrontendError(original.message);
}
static convertFSError(original, fileName) {
if (original instanceof Error && "code" in original) {
if (original.code === "ENOENT") {
return new MicrofrontendError(`Could not find "${fileName}"`, {
type: "config",
subtype: "unable_to_read_file",
source: "fs"
});
}
if (original.code === "EACCES") {
return new MicrofrontendError(
`Permission denied while accessing "${fileName}"`,
{
type: "config",
subtype: "invalid_permissions",
source: "fs"
}
);
}
}
if (original instanceof SyntaxError) {
return new MicrofrontendError(
`Failed to parse "${fileName}": Invalid JSON format.`,
{
type: "config",
subtype: "invalid_syntax",
source: "fs"
}
);
}
return null;
}
/**
* Handles an unknown error and returns a MicrofrontendsError instance.
* @param err - The error to handle.
* @returns A MicrofrontendsError instance.
*/
static handle(err, opts) {
if (err instanceof MicrofrontendError) {
return err;
}
if (err instanceof Error) {
return MicrofrontendError.convert(err, opts);
}
if (typeof err === "object" && err !== null) {
if ("message" in err && typeof err.message === "string") {
return MicrofrontendError.convert(new Error(err.message), opts);
}
}
return new MicrofrontendError("An unknown error occurred");
}
};
// src/config/microfrontends-config/utils/get-config-from-env.ts
function getConfigStringFromEnv() {
const config = process.env.MFE_CONFIG;
if (!config) {
throw new MicrofrontendError(`Missing "MFE_CONFIG" in environment.`, {
type: "config",
subtype: "not_found_in_env"
});
}
return config;
}
// src/config/schema/utils/is-default-app.ts
function isDefaultApp(a) {
return !("routing" in a);
}
// src/config/microfrontends/utils/find-repository-root.ts
var import_node_fs = __toESM(require("fs"), 1);
var import_node_path = __toESM(require("path"), 1);
var GIT_DIRECTORY = ".git";
function hasGitDirectory(dir) {
const gitPath = import_node_path.default.join(dir, GIT_DIRECTORY);
return import_node_fs.default.existsSync(gitPath) && import_node_fs.default.statSync(gitPath).isDirectory();
}
function hasPnpmWorkspaces(dir) {
return import_node_fs.default.existsSync(import_node_path.default.join(dir, "pnpm-workspace.yaml"));
}
function hasPackageJson(dir) {
return import_node_fs.default.existsSync(import_node_path.default.join(dir, "package.json"));
}
function findRepositoryRoot(startDir) {
if (process.env.NX_WORKSPACE_ROOT) {
return process.env.NX_WORKSPACE_ROOT;
}
let currentDir = startDir || process.cwd();
let lastPackageJsonDir = null;
while (currentDir !== import_node_path.default.parse(currentDir).root) {
if (hasGitDirectory(currentDir) || hasPnpmWorkspaces(currentDir)) {
return currentDir;
}
if (hasPackageJson(currentDir)) {
lastPackageJsonDir = currentDir;
}
currentDir = import_node_path.default.dirname(currentDir);
}
if (lastPackageJsonDir) {
return lastPackageJsonDir;
}
throw new Error(
`Could not find the root of the repository for ${startDir}. Please ensure that the directory is part of a Git repository. If you suspect that this should work, please file an issue to the Vercel team.`
);
}
// src/config/microfrontends/utils/infer-microfrontends-location.ts
var import_node_path2 = require("path");
var import_node_fs2 = require("fs");
var import_jsonc_parser = require("jsonc-parser");
var import_fast_glob = __toESM(require("fast-glob"), 1);
// src/config/constants.ts
var CONFIGURATION_FILENAMES = [
"microfrontends.jsonc",
"microfrontends.json"
];
// src/config/microfrontends/utils/infer-microfrontends-location.ts
var configCache = {};
function findPackageWithMicrofrontendsConfig({
repositoryRoot,
applicationContext
}) {
const applicationName = applicationContext.name;
try {
const microfrontendsJsonPaths = import_fast_glob.default.globSync(
`**/{${CONFIGURATION_FILENAMES.join(",")}}`,
{
cwd: repositoryRoot,
absolute: true,
onlyFiles: true,
followSymbolicLinks: false,
ignore: ["**/node_modules/**", "**/.git/**"]
}
);
const matchingPaths = [];
for (const microfrontendsJsonPath of microfrontendsJsonPaths) {
try {
const microfrontendsJsonContent = (0, import_node_fs2.readFileSync)(
microfrontendsJsonPath,
"utf-8"
);
const microfrontendsJson = (0, import_jsonc_parser.parse)(microfrontendsJsonContent);
if (microfrontendsJson.applications[applicationName]) {
matchingPaths.push(microfrontendsJsonPath);
} else {
for (const [_, app] of Object.entries(
microfrontendsJson.applications
)) {
if (app.packageName === applicationName) {
matchingPaths.push(microfrontendsJsonPath);
}
}
}
} catch (error) {
}
}
if (matchingPaths.length > 1) {
throw new MicrofrontendError(
`Found multiple \`microfrontends.json\` files in the repository referencing the application "${applicationName}", but only one is allowed.
${matchingPaths.join("\n \u2022 ")}`,
{ type: "config", subtype: "inference_failed" }
);
}
if (matchingPaths.length === 0) {
let additionalErrorMessage = "";
if (microfrontendsJsonPaths.length > 0) {
if (!applicationContext.projectName) {
additionalErrorMessage = `
If the name in package.json (${applicationContext.packageJsonName}) differs from your Vercel Project name, set the \`packageName\` field for the application in \`microfrontends.json\` to ensure that the configuration can be found locally.`;
} else {
additionalErrorMessage = `
Names of applications in \`microfrontends.json\` must match the Vercel Project name (${applicationContext.projectName}).`;
}
}
throw new MicrofrontendError(
`Could not find a \`microfrontends.json\` file in the repository that contains the "${applicationName}" application.${additionalErrorMessage}
If your Vercel Microfrontends configuration is not in this repository, you can use the Vercel CLI to pull the Vercel Microfrontends configuration using the "vercel microfrontends pull" command, or you can specify the path manually using the VC_MICROFRONTENDS_CONFIG environment variable.
If you suspect this is thrown in error, please reach out to the Vercel team.`,
{ type: "config", subtype: "inference_failed" }
);
}
const [packageJsonPath] = matchingPaths;
return (0, import_node_path2.dirname)(packageJsonPath);
} catch (error) {
if (error instanceof MicrofrontendError) {
throw error;
}
return null;
}
}
function inferMicrofrontendsLocation(opts) {
const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}`;
if (configCache[cacheKey]) {
return configCache[cacheKey];
}
const result = findPackageWithMicrofrontendsConfig(opts);
if (!result) {
throw new MicrofrontendError(
`Could not infer the location of the \`microfrontends.json\` file for application "${opts.applicationContext.name}" starting in directory "${opts.repositoryRoot}".`,
{ type: "config", subtype: "inference_failed" }
);
}
configCache[cacheKey] = result;
return result;
}
// src/config/microfrontends/utils/is-monorepo.ts
var import_node_fs3 = __toESM(require("fs"), 1);
var import_node_path3 = __toESM(require("path"), 1);
function isMonorepo({
repositoryRoot
}) {
try {
if (import_node_fs3.default.existsSync(import_node_path3.default.join(repositoryRoot, "pnpm-workspace.yaml"))) {
return true;
}
if (import_node_fs3.default.existsSync(import_node_path3.default.join(repositoryRoot, "vlt-workspaces.json"))) {
return true;
}
if (process.env.NX_WORKSPACE_ROOT === import_node_path3.default.resolve(repositoryRoot)) {
return true;
}
const packageJsonPath = import_node_path3.default.join(repositoryRoot, "package.json");
if (!import_node_fs3.default.existsSync(packageJsonPath)) {
return false;
}
const packageJson = JSON.parse(
import_node_fs3.default.readFileSync(packageJsonPath, "utf-8")
);
return packageJson.workspaces !== void 0;
} catch (error) {
console.error("Error determining if repository is a monorepo", error);
return false;
}
}
// src/config/microfrontends/utils/find-package-root.ts
var import_node_fs4 = __toESM(require("fs"), 1);
var import_node_path4 = __toESM(require("path"), 1);
var PACKAGE_JSON = "package.json";
function findPackageRoot(startDir) {
let currentDir = startDir || process.cwd();
while (currentDir !== import_node_path4.default.parse(currentDir).root) {
const pkgJsonPath = import_node_path4.default.join(currentDir, PACKAGE_JSON);
if (import_node_fs4.default.existsSync(pkgJsonPath)) {
return currentDir;
}
currentDir = import_node_path4.default.dirname(currentDir);
}
throw new Error(
`The root of the package that contains the \`package.json\` file for the \`${startDir}\` directory could not be found.`
);
}
// src/config/microfrontends/utils/find-config.ts
var import_node_fs5 = __toESM(require("fs"), 1);
var import_node_path5 = require("path");
function findConfig({ dir }) {
for (const filename of CONFIGURATION_FILENAMES) {
const maybeConfig = (0, import_node_path5.join)(dir, filename);
if (import_node_fs5.default.existsSync(maybeConfig)) {
return maybeConfig;
}
}
return null;
}
// src/config/microfrontends-config/isomorphic/index.ts
var import_jsonc_parser2 = require("jsonc-parser");
// src/config/microfrontends-config/client/index.ts
var import_path_to_regexp = require("path-to-regexp");
var regexpCache = /* @__PURE__ */ new Map();
var getRegexp = (path6) => {
const existing = regexpCache.get(path6);
if (existing) {
return existing;
}
const regexp = (0, import_path_to_regexp.pathToRegexp)(path6);
regexpCache.set(path6, regexp);
return regexp;
};
var MicrofrontendConfigClient = class {
constructor(config, opts) {
this.pathCache = {};
this.hasFlaggedPaths = config.hasFlaggedPaths ?? false;
for (const app of Object.values(config.applications)) {
if (app.routing) {
if (app.routing.some((match) => match.flag)) {
this.hasFlaggedPaths = true;
}
const newRouting = [];
const pathsWithoutFlags = [];
for (const group of app.routing) {
if (group.flag) {
if (opts?.removeFlaggedPaths) {
continue;
}
if (group.group) {
delete group.group;
}
newRouting.push(group);
} else {
pathsWithoutFlags.push(...group.paths);
}
}
if (pathsWithoutFlags.length > 0) {
newRouting.push({ paths: pathsWithoutFlags });
}
app.routing = newRouting;
}
}
this.serialized = config;
if (this.hasFlaggedPaths) {
this.serialized.hasFlaggedPaths = this.hasFlaggedPaths;
}
this.applications = config.applications;
}
/**
* Create a new `MicrofrontendConfigClient` from a JSON string.
* Config must be passed in to remain framework agnostic
*/
static fromEnv(config) {
if (!config) {
throw new Error(
"Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`?"
);
}
return new MicrofrontendConfigClient(JSON.parse(config));
}
isEqual(other) {
return this === other || JSON.stringify(this.applications) === JSON.stringify(other.applications);
}
getApplicationNameForPath(path6) {
if (!path6.startsWith("/")) {
throw new Error(`Path must start with a /`);
}
if (this.pathCache[path6]) {
return this.pathCache[path6];
}
const pathname = new URL(path6, "https://example.com").pathname;
for (const [name, application] of Object.entries(this.applications)) {
if (application.routing) {
for (const group of application.routing) {
for (const childPath of group.paths) {
const regexp = getRegexp(childPath);
if (regexp.test(pathname)) {
this.pathCache[path6] = name;
return name;
}
}
}
}
}
const defaultApplication = Object.entries(this.applications).find(
([, application]) => application.default
);
if (!defaultApplication) {
return null;
}
this.pathCache[path6] = defaultApplication[0];
return defaultApplication[0];
}
serialize() {
return this.serialized;
}
};
// src/config/microfrontends-config/isomorphic/validation.ts
var import_path_to_regexp2 = require("path-to-regexp");
var LIST_FORMATTER = new Intl.ListFormat("en", {
style: "long",
type: "conjunction"
});
var VALID_ASSET_PREFIX_REGEXP = /^[a-z](?:[a-z0-9-]*[a-z0-9])?$/;
var validateConfigPaths = (applicationConfigsById) => {
if (!applicationConfigsById) {
return;
}
const pathsByApplicationId = /* @__PURE__ */ new Map();
const errors = [];
for (const [id, app] of Object.entries(applicationConfigsById)) {
if (isDefaultApp(app)) {
continue;
}
for (const pathMatch of app.routing) {
for (const path6 of pathMatch.paths) {
const maybeError = validatePathExpression(path6);
if (maybeError) {
errors.push(maybeError);
} else {
const existing = pathsByApplicationId.get(path6);
if (existing) {
existing.applications.push(id);
} else {
pathsByApplicationId.set(path6, {
applications: [id],
matcher: (0, import_path_to_regexp2.pathToRegexp)(path6),
applicationId: id
});
}
}
}
}
}
const entries = Array.from(pathsByApplicationId.entries());
for (const [path6, { applications: ids, matcher, applicationId }] of entries) {
if (ids.length > 1) {
errors.push(
`Duplicate path "${path6}" for applications "${ids.join(", ")}"`
);
}
for (const [
matchPath,
{ applications: matchIds, applicationId: matchApplicationId }
] of entries) {
if (path6 === matchPath) {
continue;
}
if (applicationId === matchApplicationId) {
continue;
}
if (matcher.test(matchPath)) {
const source = `"${path6}" of application${ids.length > 0 ? "s" : ""} ${ids.join(", ")}`;
const destination = `"${matchPath}" of application${matchIds.length > 0 ? "s" : ""} ${matchIds.join(", ")}`;
errors.push(
`Overlapping path detected between ${source} and ${destination}`
);
}
}
}
if (errors.length) {
throw new MicrofrontendError(
`Invalid paths: ${errors.join(", ")}. See supported paths in the documentation https://vercel.com/docs/microfrontends/path-routing#supported-path-expressions.`,
{
type: "config",
subtype: "conflicting_paths"
}
);
}
};
var PATH_DEFAULT_PATTERN = "[^\\/#\\?]+?";
function validatePathExpression(path6) {
try {
const tokens = (0, import_path_to_regexp2.parse)(path6);
if (/(?<!\\)\{/.test(path6)) {
return `Optional paths are not supported: ${path6}`;
}
if (/(?<!\\|\()\?/.test(path6)) {
return `Optional paths are not supported: ${path6}`;
}
if (/\/[^/]*(?<!\\):[^/]*(?<!\\):[^/]*/.test(path6)) {
return `Only one wildcard is allowed per path segment: ${path6}`;
}
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token === void 0) {
return `token ${i} in ${path6} is undefined, this shouldn't happen`;
}
if (typeof token !== "string") {
if (!token.name) {
return `Only named wildcards are allowed: ${path6} (hint: add ":path" to the wildcard)`;
}
if (token.pattern !== PATH_DEFAULT_PATTERN && // Allows (a|b|c) and ((?!a|b|c).*) regex
// Only limited regex is supported for now, due to performance considerations
!/^(?<allowed>[\w]+(?:\|[^:|()]+)+)$|^\(\?!(?<disallowed>[\w]+(?:\|[^:|()]+)*)\)\.\*$/.test(
token.pattern
)) {
return `Path ${path6} cannot use unsupported regular expression wildcard`;
}
if (token.modifier && i !== tokens.length - 1) {
return `Modifier ${token.modifier} is not allowed on wildcard :${token.name} in ${path6}. Modifiers are only allowed in the last path component`;
}
}
}
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
return `Path ${path6} could not be parsed into regexp: ${message}`;
}
return void 0;
}
var validateAppPaths = (name, app) => {
for (const group of app.routing) {
for (const p of group.paths) {
if (p === "/") {
continue;
}
if (p.endsWith("/")) {
throw new MicrofrontendError(
`Invalid path for application "${name}". ${p} must not end with a slash.`,
{ type: "application", subtype: "invalid_path" }
);
}
if (!p.startsWith("/")) {
throw new MicrofrontendError(
`Invalid path for application "${name}". ${p} must start with a slash.`,
{ type: "application", subtype: "invalid_path" }
);
}
}
}
if (app.assetPrefix) {
if (!VALID_ASSET_PREFIX_REGEXP.test(app.assetPrefix)) {
throw new MicrofrontendError(
`Invalid asset prefix for application "${name}". ${app.assetPrefix} must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens.`,
{ type: "application", subtype: "invalid_asset_prefix" }
);
}
if (app.assetPrefix !== `vc-ap-${name}` && !app.routing.some(
(group) => group.paths.includes(`/${app.assetPrefix}/:path*`) && !group.flag
)) {
throw new MicrofrontendError(
`When \`assetPrefix\` is specified, \`/${app.assetPrefix}/:path*\` must be added the routing paths for the application. Changing the asset prefix is not a forwards and backwards compatible change, and the custom asset prefix should be added to \`paths\` and deployed before setting the \`assetPrefix\` field.`,
{ type: "application", subtype: "invalid_asset_prefix" }
);
}
}
};
var validateConfigDefaultApplication = (applicationConfigsById) => {
if (!applicationConfigsById) {
return;
}
const applicationsWithoutRouting = Object.entries(
applicationConfigsById
).filter(([, app]) => isDefaultApp(app));
const numApplicationsWithoutRouting = applicationsWithoutRouting.reduce(
(acc) => {
return acc + 1;
},
0
);
if (numApplicationsWithoutRouting === 0) {
throw new MicrofrontendError(
"No default application found. At least one application needs to be the default by omitting routing.",
{ type: "config", subtype: "no_default_application" }
);
}
if (numApplicationsWithoutRouting > 1) {
const applicationNamesMissingRouting = applicationsWithoutRouting.map(
([name]) => name
);
throw new MicrofrontendError(
`All applications except for the default app must contain the "routing" field. Applications that are missing routing: ${LIST_FORMATTER.format(applicationNamesMissingRouting)}.`,
{ type: "config", subtype: "multiple_default_applications" }
);
}
};
// src/config/microfrontends-config/isomorphic/utils/hash-application-name.ts
var import_md5 = __toESM(require("md5"), 1);
function hashApplicationName(name) {
if (!name) {
throw new Error("Application name is required to generate hash");
}
return (0, import_md5.default)(name).substring(0, 6).padStart(6, "0");
}
// src/config/microfrontends-config/isomorphic/utils/generate-asset-prefix.ts
var PREFIX = "vc-ap";
function generateAssetPrefixFromName({
name
}) {
if (!name) {
throw new Error("Name is required to generate an asset prefix");
}
return `${PREFIX}-${hashApplicationName(name)}`;
}
// src/config/microfrontends-config/isomorphic/utils/generate-port.ts
function generatePortFromName({
name,
minPort = 3e3,
maxPort = 8e3
}) {
if (!name) {
throw new Error("Name is required to generate a port");
}
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = (hash << 5) - hash + name.charCodeAt(i);
hash |= 0;
}
hash = Math.abs(hash);
const range = maxPort - minPort;
const port = minPort + hash % range;
return port;
}
// src/config/microfrontends-config/isomorphic/host.ts
var Host = class {
constructor(hostConfig, options) {
if (typeof hostConfig === "string") {
({
protocol: this.protocol,
host: this.host,
port: this.port
} = Host.parseUrl(hostConfig));
} else {
const { protocol = "https", host, port } = hostConfig;
this.protocol = protocol;
this.host = host;
this.port = port;
}
this.local = options?.isLocal;
}
static parseUrl(url, defaultProtocol = "https") {
let hostToParse = url;
if (!/^https?:\/\//.exec(hostToParse)) {
hostToParse = `${defaultProtocol}://${hostToParse}`;
}
const parsed = new URL(hostToParse);
if (!parsed.hostname) {
throw new Error(Host.getMicrofrontendsError(url, "requires a host"));
}
if (parsed.hash) {
throw new Error(
Host.getMicrofrontendsError(url, "cannot have a fragment")
);
}
if (parsed.username || parsed.password) {
throw new Error(
Host.getMicrofrontendsError(
url,
"cannot have authentication credentials (username and/or password)"
)
);
}
if (parsed.pathname !== "/") {
throw new Error(Host.getMicrofrontendsError(url, "cannot have a path"));
}
if (parsed.search) {
throw new Error(
Host.getMicrofrontendsError(url, "cannot have query parameters")
);
}
const protocol = parsed.protocol.slice(0, -1);
return {
protocol,
host: parsed.hostname,
port: parsed.port ? Number.parseInt(parsed.port) : void 0
};
}
static getMicrofrontendsError(url, message) {
return `Microfrontends configuration error: the URL ${url} in your microfrontends.json ${message}.`;
}
isLocal() {
return this.local || this.host === "localhost" || this.host === "127.0.0.1";
}
toString() {
const url = this.toUrl();
return url.toString().replace(/\/$/, "");
}
toUrl() {
const url = `${this.protocol}://${this.host}${this.port ? `:${this.port}` : ""}`;
return new URL(url);
}
};
var LocalHost = class extends Host {
constructor({
appName,
local
}) {
let protocol;
let host;
let port;
if (typeof local === "number") {
port = local;
} else if (typeof local === "string") {
if (/^\d+$/.test(local)) {
port = Number.parseInt(local);
} else {
const parsed = Host.parseUrl(local, "http");
protocol = parsed.protocol;
host = parsed.host;
port = parsed.port;
}
} else if (local) {
protocol = local.protocol;
host = local.host;
port = local.port;
}
super({
protocol: protocol ?? "http",
host: host ?? "localhost",
port: port ?? generatePortFromName({ name: appName })
});
}
};
// src/config/microfrontends-config/isomorphic/utils/generate-automation-bypass-env-var-name.ts
function generateAutomationBypassEnvVarName({
name
}) {
return `AUTOMATION_BYPASS_${name.toUpperCase().replace(/[^a-zA-Z0-9]/g, "_")}`;
}
// src/config/microfrontends-config/isomorphic/application.ts
var Application = class {
constructor(name, {
app,
overrides,
isDefault
}) {
this.name = name;
this.development = {
local: new LocalHost({
appName: name,
local: app.development?.local
}),
fallback: app.development?.fallback ? new Host(app.development.fallback) : void 0
};
if (app.development?.fallback) {
this.fallback = new Host(app.development.fallback);
}
this.packageName = app.packageName;
this.overrides = overrides?.environment ? {
environment: new Host(overrides.environment)
} : void 0;
this.default = isDefault ?? false;
this.serialized = app;
}
isDefault() {
return this.default;
}
getAssetPrefix() {
const generatedAssetPrefix = generateAssetPrefixFromName({
name: this.name
});
if ("assetPrefix" in this.serialized) {
return this.serialized.assetPrefix ?? generatedAssetPrefix;
}
return generatedAssetPrefix;
}
getAutomationBypassEnvVarName() {
return generateAutomationBypassEnvVarName({ name: this.name });
}
serialize() {
return this.serialized;
}
};
var DefaultApplication = class extends Application {
constructor(name, {
app,
overrides
}) {
super(name, {
app,
overrides,
isDefault: true
});
this.default = true;
this.fallback = new Host(app.development.fallback);
}
getAssetPrefix() {
return "";
}
};
var ChildApplication = class extends Application {
constructor(name, {
app,
overrides
}) {
ChildApplication.validate(name, app);
super(name, {
app,
overrides,
isDefault: false
});
this.default = false;
this.routing = app.routing;
}
static validate(name, app) {
validateAppPaths(name, app);
}
};
// src/config/microfrontends-config/isomorphic/constants.ts
var DEFAULT_LOCAL_PROXY_PORT = 3024;
// src/config/microfrontends-config/isomorphic/index.ts
var MicrofrontendConfigIsomorphic = class {
constructor({
config,
overrides
}) {
this.childApplications = {};
MicrofrontendConfigIsomorphic.validate(config);
const disableOverrides = config.options?.disableOverrides ?? false;
this.overrides = overrides && !disableOverrides ? overrides : void 0;
let defaultApplication;
for (const [appId, appConfig] of Object.entries(config.applications)) {
const appOverrides = !disableOverrides ? this.overrides?.applications[appId] : void 0;
if (isDefaultApp(appConfig)) {
defaultApplication = new DefaultApplication(appId, {
app: appConfig,
overrides: appOverrides
});
} else {
this.childApplications[appId] = new ChildApplication(appId, {
app: appConfig,
overrides: appOverrides
});
}
}
if (!defaultApplication) {
throw new MicrofrontendError(
"Could not find default application in microfrontends configuration",
{
type: "application",
subtype: "not_found"
}
);
}
this.defaultApplication = defaultApplication;
this.config = config;
this.options = config.options;
this.serialized = {
config,
overrides
};
}
static validate(config) {
const c = typeof config === "string" ? (0, import_jsonc_parser2.parse)(config) : config;
validateConfigPaths(c.applications);
validateConfigDefaultApplication(c.applications);
return c;
}
static fromEnv({
cookies
}) {
return new MicrofrontendConfigIsomorphic({
config: (0, import_jsonc_parser2.parse)(getConfigStringFromEnv()),
overrides: parseOverrides(cookies ?? [])
});
}
isOverridesDisabled() {
return this.options?.disableOverrides ?? false;
}
getConfig() {
return this.config;
}
getApplicationsByType() {
return {
defaultApplication: this.defaultApplication,
applications: Object.values(this.childApplications)
};
}
getChildApplications() {
return Object.values(this.childApplications);
}
getAllApplications() {
return [
this.defaultApplication,
...Object.values(this.childApplications)
].filter(Boolean);
}
getApplication(name) {
if (this.defaultApplication.name === name || this.defaultApplication.packageName === name) {
return this.defaultApplication;
}
const app = this.childApplications[name] || Object.values(this.childApplications).find(
(child) => child.packageName === name
);
if (!app) {
throw new MicrofrontendError(
`Could not find microfrontends configuration for application "${name}". If the name in package.json differs from your Vercel Project name, set the \`packageName\` field for the application in \`microfrontends.json\` to ensure that the configuration can be found locally.`,
{
type: "application",
subtype: "not_found"
}
);
}
return app;
}
hasApplication(name) {
try {
this.getApplication(name);
return true;
} catch {
return false;
}
}
getApplicationByProjectName(projectName) {
if (this.defaultApplication.name === projectName) {
return this.defaultApplication;
}
return Object.values(this.childApplications).find(
(app) => app.name === projectName
);
}
/**
* Returns the default application.
*/
getDefaultApplication() {
return this.defaultApplication;
}
/**
* Returns the configured port for the local proxy
*/
getLocalProxyPort() {
return this.config.options?.localProxyPort ?? DEFAULT_LOCAL_PROXY_PORT;
}
toClientConfig(options) {
const applications = Object.fromEntries(
Object.entries(this.childApplications).map(([name, application]) => [
hashApplicationName(name),
{
default: false,
routing: application.routing
}
])
);
applications[hashApplicationName(this.defaultApplication.name)] = {
default: true
};
return new MicrofrontendConfigClient(
{
applications
},
{
removeFlaggedPaths: options?.removeFlaggedPaths
}
);
}
/**
* Serializes the class back to the Schema type.
*
* NOTE: This is used when writing the config to disk and must always match the input Schema
*/
toSchemaJson() {
return this.serialized.config;
}
serialize() {
return this.serialized;
}
};
// src/config/microfrontends/utils/get-application-context.ts
var import_node_fs6 = __toESM(require("fs"), 1);
var import_node_path6 = __toESM(require("path"), 1);
function getApplicationContext(opts) {
if (opts?.appName) {
return { name: opts.appName };
}
if (process.env.VERCEL_PROJECT_NAME) {
return {
name: process.env.VERCEL_PROJECT_NAME,
projectName: process.env.VERCEL_PROJECT_NAME
};
}
if (process.env.NX_TASK_TARGET_PROJECT) {
return {
name: process.env.NX_TASK_TARGET_PROJECT,
packageJsonName: process.env.NX_TASK_TARGET_PROJECT
};
}
try {
const vercelProjectJsonPath = import_node_fs6.default.readFileSync(
import_node_path6.default.join(opts?.packageRoot || ".", ".vercel", "project.json"),
"utf-8"
);
const projectJson = JSON.parse(vercelProjectJsonPath);
if (projectJson.projectName) {
return {
name: projectJson.projectName,
projectName: projectJson.projectName
};
}
} catch (_) {
}
try {
const packageJsonString = import_node_fs6.default.readFileSync(
import_node_path6.default.join(opts?.packageRoot || ".", "package.json"),
"utf-8"
);
const packageJson = JSON.parse(packageJsonString);
if (!packageJson.name) {
throw new MicrofrontendError(
`package.json file missing required field "name"`,
{
type: "packageJson",
subtype: "missing_field_name",
source: "@vercel/microfrontends/next"
}
);
}
return { name: packageJson.name, packageJsonName: packageJson.name };
} catch (err) {
throw MicrofrontendError.handle(err, {
fileName: "package.json"
});
}
}
// src/config/microfrontends/server/utils/get-output-file-path.ts
var import_node_path7 = __toESM(require("path"), 1);
// src/config/microfrontends/server/constants.ts
var MFE_CONFIG_DEFAULT_FILE_PATH = "microfrontends";
var MFE_CONFIG_DEFAULT_FILE_NAME = "microfrontends.json";
// src/config/microfrontends/server/utils/get-output-file-path.ts
function getOutputFilePath() {
return import_node_path7.default.join(MFE_CONFIG_DEFAULT_FILE_PATH, MFE_CONFIG_DEFAULT_FILE_NAME);
}
// src/config/microfrontends/server/validation.ts
var import_jsonc_parser3 = require("jsonc-parser");
var import_ajv = require("ajv");
// schema/schema.json
var schema_default = {
$schema: "http://json-schema.org/draft-07/schema#",
$ref: "#/definitions/Config",
definitions: {
Config: {
type: "object",
properties: {
$schema: {
type: "string"
},
version: {
type: "string",
const: "1"
},
options: {
$ref: "#/definitions/Options"
},
applications: {
$ref: "#/definitions/ApplicationRouting",
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"
}
},
required: [
"applications"
],
additionalProperties: false
},
Options: {
type: "object",
properties: {
disableOverrides: {
type: "boolean",
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."
},
localProxyPort: {
type: "number",
description: "The port number used by the local proxy server.\n\nThe default is `3024`."
}
},
additionalProperties: false
},
ApplicationRouting: {
type: "object",
additionalProperties: {
$ref: "#/definitions/Application"
},
propertyNames: {
description: "The unique identifier for a Microfrontend Application.\n\nMust match the Vercel project name.\n\nNote: If this name does not also match the name used to run the application, (e.g. the `name` from the `package.json`), then the `packageName` field should be set."
}
},
Application: {
anyOf: [
{
$ref: "#/definitions/DefaultApplication"
},
{
$ref: "#/definitions/ChildApplication"
}
]
},
DefaultApplication: {
type: "object",
properties: {
packageName: {
type: "string",
description: "The name used to run the application, e.g. the `name` field in the `package.json`.\n\nThis is used by the local proxy to map the application config to the locally running app.\n\nThis is only necessary when the application name does not match the `name` used in `package.json`."
},
development: {
$ref: "#/definitions/DefaultDevelopment",
description: "Development configuration for the default application."
}
},
required: [
"development"
],
additionalProperties: false
},
DefaultDevelopment: {
type: "object",
properties: {
local: {
type: [
"number",
"string"
],
description: "A local port number or host string that this application runs on when it is running locally. If passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTP. If omitted, the port defaults to a unique, but stable (based on the application name) number.\n\nExamples of valid values:\n- 8080\n- my.localhost.me\n- my.localhost.me:8080\n- https://my.localhost.me\n- https://my.localhost.me:8080"
},
task: {
type: "string",
description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
},
fallback: {
type: "string",
description: "Fallback for local development, could point to any environment. This is required for the default app. This value is used as the fallback for child apps as well if they do not have a fallback.\n\nIf passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTPS. If omitted, the port defaults to `80` for HTTP and `443` for HTTPS."
}
},
required: [
"fallback"
],
additionalProperties: false
},
ChildApplication: {
type: "object",
properties: {
packageName: {
type: "string",
description: "The name used to run the application, e.g. the `name` field in the `package.json`.\n\nThis is used by the local proxy to map the application config to the locally running app.\n\nThis is only necessary when the application name does not match the `name` used in `package.json`."
},
development: {
$ref: "#/definitions/ChildDevelopment",
description: "Development configuration for the child application."
},
routing: {
$ref: "#/definitions/Routing",
description: "Groups of path expressions that are routed to this application."
},
assetPrefix: {
type: "string",
description: "The name of the asset prefix to use instead of the auto-generated name.\n\nThe asset prefix is used to prefix all paths to static assets, such as JS, CSS, or images that are served by a specific application. It is necessary to ensure there are no conflicts with other applications on the same domain.\n\nAn auto-generated asset prefix of the form `vc-ap-<hash>` is used when this field is not provided.\n\nWhen this field is provided, `/${assetPrefix}/:path*` must also be added to the list of paths in the `routing` field. Changing the asset prefix after a microfrontend application has already been deployed is not a forwards and backwards compatible change, and the asset prefix should be added to the `routing` field and deployed before setting the `assetPrefix` field."
}
},
required: [
"routing"
],
additionalProperties: false
},
ChildDevelopment: {
type: "object",
properties: {
local: {
type: [
"number",
"string"
],
description: "A local port number or host string that this application runs on when it is running locally. If passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTP. If omitted, the port defaults to a unique, but stable (based on the application name) number.\n\nExamples of valid values:\n- 8080\n- my.localhost.me\n- my.localhost.me:8080\n- https://my.localhost.me\n- https://my.localhost.me:8080"
},
task: {
type: "string",
description: "Optional task to run when starting the development server. Should reference a script in the package.json of the application."
},
fallback: {
type: "string",
description: "Fallback for local development, could point to any environment. This is optional for child apps. If not provided, the fallback of the default app will be used.\n\nIf passing a string, include the protocol (optional), host (required) and port (optional). For example: `https://this.ismyhost:8080`. If omitted, the protocol defaults to HTTPS. If omitted, the port defaults to `80` for HTTP and `443` for HTTPS."
}
},
additionalProperties: false
},
Routing: {
type: "array",
items: {
$ref: "#/definitions/PathGroup"
}
},
PathGroup: {
type: "object",
properties: {
group: {
type: "string",
description: "Optional group name for the paths"
},
flag: {
type: "string",
description: "flag name that can be used to enable/disable all paths in the group"
},
paths: {
type: "array",
items: {
type: "string"
}
}
},
required: [
"paths"
],
additionalProperties: false
}
}
};
// src/config/schema/utils/load.ts
var SCHEMA = schema_default;
// src/config/microfrontends/server/validation.ts
var LIST_FORMATTER2 = new Intl.ListFormat("en", {
style: "long",
type: "disjunction"
});
function formatAjvErrors(errors) {
if (!errors) {
return [];
}
const errorMessages = [];
for (const error of errors) {
if (error.instancePath === "" && (error.keyword === "anyOf" || error.keyword === "required" && error.params.missingProperty === "partOf")) {
continue;
}
const instancePath = error.instancePath.slice(1);
const formattedInstancePath = instancePath === "" ? "at the root" : `in field ${instancePath}`;
if (error.keyword === "required" && error.params.missingProperty === "routing" && instancePath.split("/").length === 2) {
errorMessages.push(
`Unable to infer if ${instancePath} is the default app or a child app. This usually means that there is another error in the configuration.`
);
} else if (error.keyword === "anyOf" && instancePath.split("/").length > 2) {
const anyOfErrors = errors.filter(
(e) => e.instancePath === error.instancePath && e.keyword !== "anyOf"
);
if (anyOfErrors.every((e) => e.keyword === "type")) {
const allowedTypes = LIST_FORMATTER2.format(
anyOfErrors.map((e) => {
return e.keyword === "type" ? String(e.params.type) : "unknown";
})
);
errorMessages.push(
`Incorrect type for ${instancePath}. Must be one of ${allowedTypes}`
);
} else {
errorMessages.push(
`Invalid field for ${instancePath}. Possible error messages are ${LIST_FORMATTER2.format(anyOfErrors.map((e) => e.message ?? ""))}`
);
}
} else if (error.keyword === "additionalProperties" && !(error.params.additionalProperty === "routing" && instancePath.split("/").length === 2)) {
errorMessages.push(
`Property '${error.params.additionalProperty}' is not allowed ${formattedInstancePath}`
);
} else if (error.keyword === "required") {
errorMessages.push(
`Property '${error.params.missingProperty}' is required ${formattedInstancePath}`
);
}
}
return errorMessages;
}
function validateSchema(configString) {
const parsedConfig = (0, import_jsonc_parser3.parse)(configString);
const ajv = new import_ajv.Ajv({ allowUnionTypes: true });
const validate = ajv.compile(SCHEMA);
const isValid = validate(parsedConfig);
if (!isValid) {
throw new MicrofrontendError(
`Invalid microfrontends config:${formatAjvErrors(validate.errors).map((error) => `
- ${error}`).join(
""
)}
See https://openapi.vercel.sh/microfrontends.json for the schema.`,
{ type: "config", subtype: "does_not_match_schema" }
);
}
return parsedConfig;
}
// src/config/microfrontends/server/index.ts
var MicrofrontendsServer = class {
constructor({
config,
overrides
}) {
this.config = new MicrofrontendConfigIsomorphic({ config, overrides });
}
/**
* Writes the configuration to a file.
*/
writeConfig(opts = {
pretty: true
}) {
const outputPath = getOutputFilePath();
import_node_fs7.default.mkdirSync((0, import_node_path8.dirname)(outputPath), { recursive: true });
import_node_fs7.default.writeFileSync(
outputPath,
JSON.stringify(
this.config.toSchemaJson(),
null,
opts.pretty ?? true ? 2 : void 0
)
);
}
// --------- Static Methods ---------
/**
* Generates a MicrofrontendsServer instance from an unknown object.
*/
static fromUnknown({
config,
cookies
}) {
const overrides = cookies ? parseOverrides(cookies) : void 0;
if (typeof config === "string") {
return new MicrofrontendsServer({
config: MicrofrontendsServer.validate(config),
overrides
});
}
if (typeof config === "object") {
return new MicrofrontendsServer({
config,
overrides
});
}
throw new MicrofrontendError(
"Invalid config: must be a string or an object",
{ type: "config", subtype: "does_not_match_schema" }
);
}
/**
* Generates a MicrofrontendsServer instance from the environment.
* Uses additional validation that is only available when in a node runtime
*/
static fromEnv({
cookies
}) {
return new MicrofrontendsServer({
config: MicrofrontendsServer.validate(getConfigStringFromEnv()),
overrides: parseOverrides(cookies)
});
}
/**
* Validates the configuration against the JSON schema
*/
static validate(config) {
if (typeof config === "string") {
const c = validateSchema(config);
return c;
}
return config;
}
/**
* Looks up the configuration by inferring the package root and looking for a microfrontends config file. If a file is not found,
* it will look for a package in the repository with a microfrontends file that contains the current application
* and use that configuration.
*
* This can return either a Child or Main configuration.
*/
static infer({
appName,
directory,
filePath,
cookies
} = {}) {
if (filePath) {
return MicrofrontendsServer.fromFile({
filePath,
cookies
});
}
try {
const packageRoot = findPackageRoot(directory);
const applic