@vercel/microfrontends 2.2.2 → 2.3.1
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.
- package/CHANGELOG.md +12 -0
- package/dist/bin/cli.cjs +263 -263
- package/dist/config.cjs +23 -23
- package/dist/config.cjs.map +1 -1
- package/dist/config.js +23 -23
- package/dist/config.js.map +1 -1
- package/dist/experimental/sveltekit.cjs +260 -260
- package/dist/experimental/sveltekit.cjs.map +1 -1
- package/dist/experimental/sveltekit.js +240 -240
- package/dist/experimental/sveltekit.js.map +1 -1
- package/dist/experimental/vite.cjs +260 -260
- package/dist/experimental/vite.cjs.map +1 -1
- package/dist/experimental/vite.js +240 -240
- package/dist/experimental/vite.js.map +1 -1
- package/dist/microfrontends/server.cjs +260 -260
- package/dist/microfrontends/server.cjs.map +1 -1
- package/dist/microfrontends/server.js +240 -240
- package/dist/microfrontends/server.js.map +1 -1
- package/dist/microfrontends/utils.cjs +22 -0
- package/dist/microfrontends/utils.cjs.map +1 -1
- package/dist/microfrontends/utils.d.ts +5 -1
- package/dist/microfrontends/utils.js +21 -0
- package/dist/microfrontends/utils.js.map +1 -1
- package/dist/next/client.cjs.map +1 -1
- package/dist/next/client.js.map +1 -1
- package/dist/next/config.cjs +260 -260
- package/dist/next/config.cjs.map +1 -1
- package/dist/next/config.js +240 -240
- package/dist/next/config.js.map +1 -1
- package/dist/next/middleware.cjs +23 -23
- package/dist/next/middleware.cjs.map +1 -1
- package/dist/next/middleware.js +23 -23
- package/dist/next/middleware.js.map +1 -1
- package/dist/next/testing.cjs +23 -23
- package/dist/next/testing.cjs.map +1 -1
- package/dist/next/testing.js +23 -23
- package/dist/next/testing.js.map +1 -1
- package/dist/utils/mfe-port.cjs +260 -260
- package/dist/utils/mfe-port.cjs.map +1 -1
- package/dist/utils/mfe-port.js +240 -240
- package/dist/utils/mfe-port.js.map +1 -1
- package/package.json +2 -2
|
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var utils_exports = {};
|
|
32
32
|
__export(utils_exports, {
|
|
33
33
|
findConfig: () => findConfig,
|
|
34
|
+
generateDefaultAssetPrefixFromName: () => generateDefaultAssetPrefixFromName,
|
|
34
35
|
getPossibleConfigurationFilenames: () => getPossibleConfigurationFilenames,
|
|
35
36
|
inferMicrofrontendsLocation: () => inferMicrofrontendsLocation
|
|
36
37
|
});
|
|
@@ -77,6 +78,26 @@ function findConfig({
|
|
|
77
78
|
return null;
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
// src/config/microfrontends/utils/hash-application-name.ts
|
|
82
|
+
var import_md5 = __toESM(require("md5"), 1);
|
|
83
|
+
function hashApplicationName(name) {
|
|
84
|
+
if (!name) {
|
|
85
|
+
throw new Error("Application name is required to generate hash");
|
|
86
|
+
}
|
|
87
|
+
return (0, import_md5.default)(name).substring(0, 6).padStart(6, "0");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/config/microfrontends/utils/generate-default-asset-prefix.ts
|
|
91
|
+
var PREFIX = "vc-ap";
|
|
92
|
+
function generateDefaultAssetPrefixFromName({
|
|
93
|
+
name
|
|
94
|
+
}) {
|
|
95
|
+
if (!name) {
|
|
96
|
+
throw new Error("Name is required to generate an asset prefix");
|
|
97
|
+
}
|
|
98
|
+
return `${PREFIX}-${hashApplicationName(name)}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
80
101
|
// src/config/microfrontends/utils/infer-microfrontends-location.ts
|
|
81
102
|
var import_node_fs2 = require("fs");
|
|
82
103
|
var import_node_path2 = require("path");
|
|
@@ -368,6 +389,7 @@ function doesApplicationExistInConfig(microfrontendsJsonPath, applicationName) {
|
|
|
368
389
|
// Annotate the CommonJS export names for ESM import in node:
|
|
369
390
|
0 && (module.exports = {
|
|
370
391
|
findConfig,
|
|
392
|
+
generateDefaultAssetPrefixFromName,
|
|
371
393
|
getPossibleConfigurationFilenames,
|
|
372
394
|
inferMicrofrontendsLocation
|
|
373
395
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/microfrontends/utils/index.ts","../../src/config/microfrontends/utils/find-config.ts","../../src/config/microfrontends/utils/get-config-file-name.ts","../../src/config/microfrontends/utils/infer-microfrontends-location.ts","../../src/bin/logger.ts","../../src/config/errors.ts"],"sourcesContent":["export { findConfig } from './find-config';\nexport { getPossibleConfigurationFilenames } from './get-config-file-name';\nexport { inferMicrofrontendsLocation } from './infer-microfrontends-location';\n","import fs from 'node:fs';\nimport { join } from 'node:path';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\nexport function findConfig({\n dir,\n customConfigFilename,\n}: {\n dir: string;\n customConfigFilename: string | undefined;\n}): string | null {\n for (const filename of getPossibleConfigurationFilenames({\n customConfigFilename,\n })) {\n const maybeConfig = join(dir, filename);\n if (fs.existsSync(maybeConfig)) {\n return maybeConfig;\n }\n }\n\n return null;\n}\n","// ordered by most likely to be the correct one\nconst DEFAULT_CONFIGURATION_FILENAMES = [\n 'microfrontends.json',\n 'microfrontends.jsonc',\n] as const;\n\nexport function getPossibleConfigurationFilenames({\n customConfigFilename,\n}: {\n // from env\n customConfigFilename: string | undefined;\n}) {\n if (customConfigFilename) {\n if (\n !customConfigFilename.endsWith('.json') &&\n !customConfigFilename.endsWith('.jsonc')\n ) {\n throw new Error(\n `Found VC_MICROFRONTENDS_CONFIG_FILE_NAME but the name is invalid. Received: ${customConfigFilename}.` +\n ` The file name must end with '.json' or '.jsonc'.` +\n ` It's also possible for the env var to include the path, eg microfrontends-dev.json or /path/to/microfrontends-dev.json.`,\n );\n }\n return Array.from(\n new Set([customConfigFilename, ...DEFAULT_CONFIGURATION_FILENAMES]),\n );\n }\n return DEFAULT_CONFIGURATION_FILENAMES;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport fg from 'fast-glob';\nimport { parse } from 'jsonc-parser';\nimport { logger } from '../../../bin/logger';\nimport { MicrofrontendError } from '../../errors';\nimport type { Config } from '../../schema/types';\nimport type { ApplicationContext } from './get-application-context';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\n// cache the path to default configuration to avoid having to walk the file system multiple times\nconst configCache: Record<string, string> = {};\n\ninterface FindDefaultMicrofrontendPackageArgs {\n repositoryRoot: string;\n applicationContext: ApplicationContext;\n customConfigFilename: string | undefined;\n}\n\n/**\n * Given a repository root and a package name, find the path to the package.json file with the\n * given name.\n *\n * This method uses globby to find all package.json files and then reads them in parallel\n */\nfunction findPackageWithMicrofrontendsConfig({\n repositoryRoot,\n applicationContext,\n customConfigFilename,\n}: FindDefaultMicrofrontendPackageArgs): string | null {\n const applicationName = applicationContext.name;\n logger.debug(\n '[MFE Config] Searching repository for configs containing application:',\n applicationName,\n );\n\n try {\n const microfrontendsJsonPaths = fg.globSync(\n `**/{${getPossibleConfigurationFilenames({ customConfigFilename }).join(',')}}`,\n {\n cwd: repositoryRoot,\n absolute: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n ignore: ['**/node_modules/**', '**/.git/**'],\n },\n );\n\n logger.debug(\n '[MFE Config] Found',\n microfrontendsJsonPaths.length,\n 'config file(s) in repository',\n );\n\n const matchingPaths: string[] = [];\n for (const microfrontendsJsonPath of microfrontendsJsonPaths) {\n if (\n doesApplicationExistInConfig(microfrontendsJsonPath, applicationName)\n ) {\n matchingPaths.push(microfrontendsJsonPath);\n }\n }\n\n logger.debug(\n '[MFE Config] Total matching config files:',\n matchingPaths.length,\n );\n\n if (matchingPaths.length > 1) {\n throw new MicrofrontendError(\n `Found multiple \\`microfrontends.json\\` files in the repository referencing the application \"${applicationName}\", but only one is allowed.\\n${matchingPaths.join('\\n • ')}`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n if (matchingPaths.length === 0) {\n if (\n repositoryRoot &&\n doesMisplacedConfigExist(\n repositoryRoot,\n applicationName,\n customConfigFilename,\n )\n ) {\n logger.debug(\n '[MFE Config] Found misplaced config in wrong .vercel directory in repository',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n throw new MicrofrontendError(\n `Unable to automatically infer the location of the \\`microfrontends.json\\` file.\\n\\n` +\n `A microfrontends config was found in the \\`.vercel\\` directory at the repository root: ${misplacedConfigPath}\\n` +\n `However, in a monorepo, the config file should be placed in the \\`.vercel\\` directory in your application directory instead.\\n\\n` +\n `To fix this:\\n` +\n `1. If using \\`vercel link\\`, run it with \\`vercel link --repo\\` to handle monorepos, or run \\`vercel microfrontends pull --cwd=<application-directory>\\` to make sure it pulls the \\`microfrontends.json\\` file to the correct location\\n` +\n `2. If manually defined, move the config file to the \\`.vercel\\` directory in your application\\n` +\n `3. Alternatively, set the VC_MICROFRONTENDS_CONFIG environment variable to the correct path\\n\\n` +\n `For more information, see: https://vercel.com/docs/cli/project-linking`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n let additionalErrorMessage = '';\n if (microfrontendsJsonPaths.length > 0) {\n if (!applicationContext.projectName) {\n additionalErrorMessage = `\\n\\nIf 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.`;\n } else {\n additionalErrorMessage = `\\n\\nNames of applications in \\`microfrontends.json\\` must match the Vercel Project name (${applicationContext.projectName}).`;\n }\n }\n throw new MicrofrontendError(\n `Could not find a \\`microfrontends.json\\` file in the repository that contains the \"${applicationName}\" application.${additionalErrorMessage}\\n\\n` +\n `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.\\n\\n` +\n `If your Vercel Microfrontends configuration has a custom name, ensure the VC_MICROFRONTENDS_CONFIG_FILE_NAME environment variable is set, you can pull the vercel project environment variables using the \"vercel env pull\" command.\\n\\n` +\n `If you suspect this is thrown in error, please reach out to the Vercel team.`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n const [packageJsonPath] = matchingPaths as [string];\n return dirname(packageJsonPath);\n } catch (error) {\n if (error instanceof MicrofrontendError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Given a repository root and a package name, find the path to the package directory with\n * a microfrontends config that contains the given name in its applications.\n */\nexport function inferMicrofrontendsLocation(\n opts: FindDefaultMicrofrontendPackageArgs,\n): string {\n // cache this with name to support multiple configurations in the same repository\n const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}${opts.customConfigFilename ? `-${opts.customConfigFilename}` : ''}`;\n\n // Check if we have a cached result\n if (configCache[cacheKey]) {\n return configCache[cacheKey];\n }\n\n const result = findPackageWithMicrofrontendsConfig(opts);\n\n if (!result) {\n throw new MicrofrontendError(\n `Could not infer the location of the \\`microfrontends.json\\` file for application \"${opts.applicationContext.name}\" starting in directory \"${opts.repositoryRoot}\".`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n // Cache the result\n configCache[cacheKey] = result;\n return result;\n}\n\nfunction existsSync(path: string): boolean {\n try {\n statSync(path);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nfunction doesMisplacedConfigExist(\n repositoryRoot: string,\n applicationName: string,\n customConfigFilename: string | undefined,\n): boolean {\n logger.debug(\n '[MFE Config] Looking for misplaced config in wrong .vercel directory',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n return (\n existsSync(misplacedConfigPath) &&\n doesApplicationExistInConfig(misplacedConfigPath, applicationName)\n );\n}\n\nfunction doesApplicationExistInConfig(\n microfrontendsJsonPath: string,\n applicationName: string,\n): boolean {\n try {\n const microfrontendsJsonContent = readFileSync(\n microfrontendsJsonPath,\n 'utf-8',\n );\n const microfrontendsJson = parse(microfrontendsJsonContent) as Config;\n\n if (microfrontendsJson.applications[applicationName]) {\n logger.debug(\n '[MFE Config] Found application in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n\n for (const [_, app] of Object.entries(microfrontendsJson.applications)) {\n if (app.packageName === applicationName) {\n logger.debug(\n '[MFE Config] Found application via packageName in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n }\n } catch (error) {\n logger.debug('[MFE Config] Error checking application in config:', error);\n // malformed json most likely, skip this file\n }\n return false;\n}\n","/* eslint-disable no-console */\n\nfunction debug(...args: unknown[]): void {\n if (process.env.MFE_DEBUG) {\n console.log(...args);\n }\n}\n\nfunction info(...args: unknown[]): void {\n console.log(...args);\n}\n\nfunction warn(...args: unknown[]): void {\n console.warn(...args);\n}\n\nfunction error(...args: unknown[]): void {\n console.error(...args);\n}\n\nexport const logger = {\n debug,\n info,\n warn,\n error,\n};\n","export type MicrofrontendErrorType =\n | 'config'\n | 'packageJson'\n | 'vercelJson'\n | 'application'\n | 'unknown';\n\nexport type MicrofrontendErrorSubtype =\n | 'not_found'\n | 'inference_failed'\n | 'not_found_in_env'\n | 'invalid_asset_prefix'\n | 'invalid_main_path'\n | 'does_not_match_schema'\n | 'unable_to_read_file'\n | 'unsupported_validation_env'\n | 'unsupported_version'\n | 'invalid_path'\n | 'invalid_permissions'\n | 'invalid_syntax'\n | 'missing_microfrontend_config_path'\n | 'unsupported_operation';\n\n// A mapping of error types to their subtypes.\ninterface TypeToSubtype {\n application:\n | 'invalid_asset_prefix'\n | 'invalid_path'\n | 'multiple_package_managers'\n | 'not_found';\n config:\n | 'conflicting_paths'\n | 'depcrecated_field'\n | 'does_not_match_schema'\n | 'invalid_main_path'\n | 'invalid_preview_deployment_suffix'\n | 'multiple_default_applications'\n | 'no_default_application'\n | 'not_found_in_env'\n | 'not_found'\n | 'inference_failed'\n | 'unable_to_read_file'\n | 'invalid_syntax'\n | 'invalid_permissions'\n | 'unsupported_operation'\n | 'unsupported_validation_env'\n | 'unsupported_version';\n packageJson:\n | 'missing_field_name'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n vercelJson:\n | 'missing_field_microfrontend_config_path'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n unknown: never;\n}\n\nexport type MicrofrontendErrorSource =\n | '@vercel/microfrontends'\n | '@vercel/microfrontends/next'\n | 'fs'\n | 'ajv';\n\nexport interface MicrofrontendErrorOptions<T extends MicrofrontendErrorType> {\n cause?: unknown;\n source?: MicrofrontendErrorSource;\n type?: T;\n subtype?: TypeToSubtype[T];\n}\n\ninterface HandleOptions {\n fileName?: string;\n}\n\nexport class MicrofrontendError<\n T extends MicrofrontendErrorType = 'unknown',\n> extends Error {\n public source: MicrofrontendErrorSource;\n public type: T;\n public subtype?: TypeToSubtype[T];\n\n constructor(message: string, opts?: MicrofrontendErrorOptions<T>) {\n super(message, { cause: opts?.cause });\n this.name = 'MicrofrontendsError';\n this.source = opts?.source ?? '@vercel/microfrontends';\n this.type = opts?.type ?? ('unknown' as T);\n this.subtype = opts?.subtype;\n Error.captureStackTrace(this, MicrofrontendError);\n }\n\n isKnown(): boolean {\n return this.type !== 'unknown';\n }\n\n isUnknown(): boolean {\n return !this.isKnown();\n }\n\n /**\n * Converts an error to a MicrofrontendsError.\n * @param original - The original error to convert.\n * @returns The converted MicrofrontendsError.\n */\n static convert(\n original: Error,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (opts?.fileName) {\n const err = MicrofrontendError.convertFSError(original, opts.fileName);\n if (err) {\n return err;\n }\n }\n\n if (\n original.message.includes(\n 'Code generation from strings disallowed for this context',\n )\n ) {\n return new MicrofrontendError(original.message, {\n type: 'config',\n subtype: 'unsupported_validation_env',\n source: 'ajv',\n });\n }\n\n // unknown catch-all\n return new MicrofrontendError(original.message);\n }\n\n static convertFSError(\n original: Error,\n fileName: string,\n ): MicrofrontendError<MicrofrontendErrorType> | null {\n if (original instanceof Error && 'code' in original) {\n if (original.code === 'ENOENT') {\n return new MicrofrontendError(`Could not find \"${fileName}\"`, {\n type: 'config',\n subtype: 'unable_to_read_file',\n source: 'fs',\n });\n }\n if (original.code === 'EACCES') {\n return new MicrofrontendError(\n `Permission denied while accessing \"${fileName}\"`,\n {\n type: 'config',\n subtype: 'invalid_permissions',\n source: 'fs',\n },\n );\n }\n }\n\n if (original instanceof SyntaxError) {\n return new MicrofrontendError(\n `Failed to parse \"${fileName}\": Invalid JSON format.`,\n {\n type: 'config',\n subtype: 'invalid_syntax',\n source: 'fs',\n },\n );\n }\n\n return null;\n }\n\n /**\n * Handles an unknown error and returns a MicrofrontendsError instance.\n * @param err - The error to handle.\n * @returns A MicrofrontendsError instance.\n */\n static handle(\n err: unknown,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (err instanceof MicrofrontendError) {\n return err as MicrofrontendError<MicrofrontendErrorType>;\n }\n\n // handle Error instances\n if (err instanceof Error) {\n return MicrofrontendError.convert(err, opts);\n }\n\n // handle object errors\n if (typeof err === 'object' && err !== null) {\n if ('message' in err && typeof err.message === 'string') {\n return MicrofrontendError.convert(new Error(err.message), opts);\n }\n }\n\n return new MicrofrontendError('An unknown error occurred');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAAe;AACf,uBAAqB;;;ACArB,IAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAEO,SAAS,kCAAkC;AAAA,EAChD;AACF,GAGG;AACD,MAAI,sBAAsB;AACxB,QACE,CAAC,qBAAqB,SAAS,OAAO,KACtC,CAAC,qBAAqB,SAAS,QAAQ,GACvC;AACA,YAAM,IAAI;AAAA,QACR,+EAA+E;AAAA,MAGjF;AAAA,IACF;AACA,WAAO,MAAM;AAAA,MACX,oBAAI,IAAI,CAAC,sBAAsB,GAAG,+BAA+B,CAAC;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;;;ADxBO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AACF,GAGkB;AAChB,aAAW,YAAY,kCAAkC;AAAA,IACvD;AAA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T,MAAI;AACF,UAAM,gCAA4B;AAAA,MAChC;AAAA,MACA;AAAA,IACF;AACA,UAAM,yBAAqB,2BAAM,yBAAyB;AAE1D,QAAI,mBAAmB,aAAa,eAAe,GAAG;AACpD,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,eAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,mBAAmB,YAAY,GAAG;AACtE,UAAI,IAAI,gBAAgB,iBAAiB;AACvC,eAAO;AAAA,UACL;AAAA,UACA;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,SAASA,QAAP;AACA,WAAO,MAAM,sDAAsDA,MAAK;AAAA,EAE1E;AACA,SAAO;AACT;","names":["fs","import_node_fs","import_node_path","fg","error"]}
|
|
1
|
+
{"version":3,"sources":["../../src/config/microfrontends/utils/index.ts","../../src/config/microfrontends/utils/find-config.ts","../../src/config/microfrontends/utils/get-config-file-name.ts","../../src/config/microfrontends/utils/hash-application-name.ts","../../src/config/microfrontends/utils/generate-default-asset-prefix.ts","../../src/config/microfrontends/utils/infer-microfrontends-location.ts","../../src/bin/logger.ts","../../src/config/errors.ts"],"sourcesContent":["export { findConfig } from './find-config';\nexport { generateDefaultAssetPrefixFromName } from './generate-default-asset-prefix';\nexport { getPossibleConfigurationFilenames } from './get-config-file-name';\nexport { inferMicrofrontendsLocation } from './infer-microfrontends-location';\n","import fs from 'node:fs';\nimport { join } from 'node:path';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\nexport function findConfig({\n dir,\n customConfigFilename,\n}: {\n dir: string;\n customConfigFilename: string | undefined;\n}): string | null {\n for (const filename of getPossibleConfigurationFilenames({\n customConfigFilename,\n })) {\n const maybeConfig = join(dir, filename);\n if (fs.existsSync(maybeConfig)) {\n return maybeConfig;\n }\n }\n\n return null;\n}\n","// ordered by most likely to be the correct one\nconst DEFAULT_CONFIGURATION_FILENAMES = [\n 'microfrontends.json',\n 'microfrontends.jsonc',\n] as const;\n\nexport function getPossibleConfigurationFilenames({\n customConfigFilename,\n}: {\n // from env\n customConfigFilename: string | undefined;\n}) {\n if (customConfigFilename) {\n if (\n !customConfigFilename.endsWith('.json') &&\n !customConfigFilename.endsWith('.jsonc')\n ) {\n throw new Error(\n `Found VC_MICROFRONTENDS_CONFIG_FILE_NAME but the name is invalid. Received: ${customConfigFilename}.` +\n ` The file name must end with '.json' or '.jsonc'.` +\n ` It's also possible for the env var to include the path, eg microfrontends-dev.json or /path/to/microfrontends-dev.json.`,\n );\n }\n return Array.from(\n new Set([customConfigFilename, ...DEFAULT_CONFIGURATION_FILENAMES]),\n );\n }\n return DEFAULT_CONFIGURATION_FILENAMES;\n}\n","import md5 from 'md5';\n\nexport function hashApplicationName(name: string): string {\n if (!name) {\n throw new Error('Application name is required to generate hash');\n }\n\n return md5(name).substring(0, 6).padStart(6, '0');\n}\n","import { hashApplicationName } from './hash-application-name';\n\nconst PREFIX = 'vc-ap';\n\nexport function generateDefaultAssetPrefixFromName({\n name,\n}: {\n name: string;\n}): string {\n if (!name) {\n throw new Error('Name is required to generate an asset prefix');\n }\n\n return `${PREFIX}-${hashApplicationName(name)}`;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport fg from 'fast-glob';\nimport { parse } from 'jsonc-parser';\nimport { logger } from '../../../bin/logger';\nimport { MicrofrontendError } from '../../errors';\nimport type { Config } from '../../schema/types';\nimport type { ApplicationContext } from './get-application-context';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\n// cache the path to default configuration to avoid having to walk the file system multiple times\nconst configCache: Record<string, string> = {};\n\ninterface FindDefaultMicrofrontendPackageArgs {\n repositoryRoot: string;\n applicationContext: ApplicationContext;\n customConfigFilename: string | undefined;\n}\n\n/**\n * Given a repository root and a package name, find the path to the package.json file with the\n * given name.\n *\n * This method uses globby to find all package.json files and then reads them in parallel\n */\nfunction findPackageWithMicrofrontendsConfig({\n repositoryRoot,\n applicationContext,\n customConfigFilename,\n}: FindDefaultMicrofrontendPackageArgs): string | null {\n const applicationName = applicationContext.name;\n logger.debug(\n '[MFE Config] Searching repository for configs containing application:',\n applicationName,\n );\n\n try {\n const microfrontendsJsonPaths = fg.globSync(\n `**/{${getPossibleConfigurationFilenames({ customConfigFilename }).join(',')}}`,\n {\n cwd: repositoryRoot,\n absolute: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n ignore: ['**/node_modules/**', '**/.git/**'],\n },\n );\n\n logger.debug(\n '[MFE Config] Found',\n microfrontendsJsonPaths.length,\n 'config file(s) in repository',\n );\n\n const matchingPaths: string[] = [];\n for (const microfrontendsJsonPath of microfrontendsJsonPaths) {\n if (\n doesApplicationExistInConfig(microfrontendsJsonPath, applicationName)\n ) {\n matchingPaths.push(microfrontendsJsonPath);\n }\n }\n\n logger.debug(\n '[MFE Config] Total matching config files:',\n matchingPaths.length,\n );\n\n if (matchingPaths.length > 1) {\n throw new MicrofrontendError(\n `Found multiple \\`microfrontends.json\\` files in the repository referencing the application \"${applicationName}\", but only one is allowed.\\n${matchingPaths.join('\\n • ')}`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n if (matchingPaths.length === 0) {\n if (\n repositoryRoot &&\n doesMisplacedConfigExist(\n repositoryRoot,\n applicationName,\n customConfigFilename,\n )\n ) {\n logger.debug(\n '[MFE Config] Found misplaced config in wrong .vercel directory in repository',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n throw new MicrofrontendError(\n `Unable to automatically infer the location of the \\`microfrontends.json\\` file.\\n\\n` +\n `A microfrontends config was found in the \\`.vercel\\` directory at the repository root: ${misplacedConfigPath}\\n` +\n `However, in a monorepo, the config file should be placed in the \\`.vercel\\` directory in your application directory instead.\\n\\n` +\n `To fix this:\\n` +\n `1. If using \\`vercel link\\`, run it with \\`vercel link --repo\\` to handle monorepos, or run \\`vercel microfrontends pull --cwd=<application-directory>\\` to make sure it pulls the \\`microfrontends.json\\` file to the correct location\\n` +\n `2. If manually defined, move the config file to the \\`.vercel\\` directory in your application\\n` +\n `3. Alternatively, set the VC_MICROFRONTENDS_CONFIG environment variable to the correct path\\n\\n` +\n `For more information, see: https://vercel.com/docs/cli/project-linking`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n let additionalErrorMessage = '';\n if (microfrontendsJsonPaths.length > 0) {\n if (!applicationContext.projectName) {\n additionalErrorMessage = `\\n\\nIf 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.`;\n } else {\n additionalErrorMessage = `\\n\\nNames of applications in \\`microfrontends.json\\` must match the Vercel Project name (${applicationContext.projectName}).`;\n }\n }\n throw new MicrofrontendError(\n `Could not find a \\`microfrontends.json\\` file in the repository that contains the \"${applicationName}\" application.${additionalErrorMessage}\\n\\n` +\n `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.\\n\\n` +\n `If your Vercel Microfrontends configuration has a custom name, ensure the VC_MICROFRONTENDS_CONFIG_FILE_NAME environment variable is set, you can pull the vercel project environment variables using the \"vercel env pull\" command.\\n\\n` +\n `If you suspect this is thrown in error, please reach out to the Vercel team.`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n const [packageJsonPath] = matchingPaths as [string];\n return dirname(packageJsonPath);\n } catch (error) {\n if (error instanceof MicrofrontendError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Given a repository root and a package name, find the path to the package directory with\n * a microfrontends config that contains the given name in its applications.\n */\nexport function inferMicrofrontendsLocation(\n opts: FindDefaultMicrofrontendPackageArgs,\n): string {\n // cache this with name to support multiple configurations in the same repository\n const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}${opts.customConfigFilename ? `-${opts.customConfigFilename}` : ''}`;\n\n // Check if we have a cached result\n if (configCache[cacheKey]) {\n return configCache[cacheKey];\n }\n\n const result = findPackageWithMicrofrontendsConfig(opts);\n\n if (!result) {\n throw new MicrofrontendError(\n `Could not infer the location of the \\`microfrontends.json\\` file for application \"${opts.applicationContext.name}\" starting in directory \"${opts.repositoryRoot}\".`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n // Cache the result\n configCache[cacheKey] = result;\n return result;\n}\n\nfunction existsSync(path: string): boolean {\n try {\n statSync(path);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nfunction doesMisplacedConfigExist(\n repositoryRoot: string,\n applicationName: string,\n customConfigFilename: string | undefined,\n): boolean {\n logger.debug(\n '[MFE Config] Looking for misplaced config in wrong .vercel directory',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n return (\n existsSync(misplacedConfigPath) &&\n doesApplicationExistInConfig(misplacedConfigPath, applicationName)\n );\n}\n\nfunction doesApplicationExistInConfig(\n microfrontendsJsonPath: string,\n applicationName: string,\n): boolean {\n try {\n const microfrontendsJsonContent = readFileSync(\n microfrontendsJsonPath,\n 'utf-8',\n );\n const microfrontendsJson = parse(microfrontendsJsonContent) as Config;\n\n if (microfrontendsJson.applications[applicationName]) {\n logger.debug(\n '[MFE Config] Found application in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n\n for (const [_, app] of Object.entries(microfrontendsJson.applications)) {\n if (app.packageName === applicationName) {\n logger.debug(\n '[MFE Config] Found application via packageName in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n }\n } catch (error) {\n logger.debug('[MFE Config] Error checking application in config:', error);\n // malformed json most likely, skip this file\n }\n return false;\n}\n","/* eslint-disable no-console */\n\nfunction debug(...args: unknown[]): void {\n if (process.env.MFE_DEBUG) {\n console.log(...args);\n }\n}\n\nfunction info(...args: unknown[]): void {\n console.log(...args);\n}\n\nfunction warn(...args: unknown[]): void {\n console.warn(...args);\n}\n\nfunction error(...args: unknown[]): void {\n console.error(...args);\n}\n\nexport const logger = {\n debug,\n info,\n warn,\n error,\n};\n","export type MicrofrontendErrorType =\n | 'config'\n | 'packageJson'\n | 'vercelJson'\n | 'application'\n | 'unknown';\n\nexport type MicrofrontendErrorSubtype =\n | 'not_found'\n | 'inference_failed'\n | 'not_found_in_env'\n | 'invalid_asset_prefix'\n | 'invalid_main_path'\n | 'does_not_match_schema'\n | 'unable_to_read_file'\n | 'unsupported_validation_env'\n | 'unsupported_version'\n | 'invalid_path'\n | 'invalid_permissions'\n | 'invalid_syntax'\n | 'missing_microfrontend_config_path'\n | 'unsupported_operation';\n\n// A mapping of error types to their subtypes.\ninterface TypeToSubtype {\n application:\n | 'invalid_asset_prefix'\n | 'invalid_path'\n | 'multiple_package_managers'\n | 'not_found';\n config:\n | 'conflicting_paths'\n | 'depcrecated_field'\n | 'does_not_match_schema'\n | 'invalid_main_path'\n | 'invalid_preview_deployment_suffix'\n | 'multiple_default_applications'\n | 'no_default_application'\n | 'not_found_in_env'\n | 'not_found'\n | 'inference_failed'\n | 'unable_to_read_file'\n | 'invalid_syntax'\n | 'invalid_permissions'\n | 'unsupported_operation'\n | 'unsupported_validation_env'\n | 'unsupported_version';\n packageJson:\n | 'missing_field_name'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n vercelJson:\n | 'missing_field_microfrontend_config_path'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n unknown: never;\n}\n\nexport type MicrofrontendErrorSource =\n | '@vercel/microfrontends'\n | '@vercel/microfrontends/next'\n | 'fs'\n | 'ajv';\n\nexport interface MicrofrontendErrorOptions<T extends MicrofrontendErrorType> {\n cause?: unknown;\n source?: MicrofrontendErrorSource;\n type?: T;\n subtype?: TypeToSubtype[T];\n}\n\ninterface HandleOptions {\n fileName?: string;\n}\n\nexport class MicrofrontendError<\n T extends MicrofrontendErrorType = 'unknown',\n> extends Error {\n public source: MicrofrontendErrorSource;\n public type: T;\n public subtype?: TypeToSubtype[T];\n\n constructor(message: string, opts?: MicrofrontendErrorOptions<T>) {\n super(message, { cause: opts?.cause });\n this.name = 'MicrofrontendsError';\n this.source = opts?.source ?? '@vercel/microfrontends';\n this.type = opts?.type ?? ('unknown' as T);\n this.subtype = opts?.subtype;\n Error.captureStackTrace(this, MicrofrontendError);\n }\n\n isKnown(): boolean {\n return this.type !== 'unknown';\n }\n\n isUnknown(): boolean {\n return !this.isKnown();\n }\n\n /**\n * Converts an error to a MicrofrontendsError.\n * @param original - The original error to convert.\n * @returns The converted MicrofrontendsError.\n */\n static convert(\n original: Error,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (opts?.fileName) {\n const err = MicrofrontendError.convertFSError(original, opts.fileName);\n if (err) {\n return err;\n }\n }\n\n if (\n original.message.includes(\n 'Code generation from strings disallowed for this context',\n )\n ) {\n return new MicrofrontendError(original.message, {\n type: 'config',\n subtype: 'unsupported_validation_env',\n source: 'ajv',\n });\n }\n\n // unknown catch-all\n return new MicrofrontendError(original.message);\n }\n\n static convertFSError(\n original: Error,\n fileName: string,\n ): MicrofrontendError<MicrofrontendErrorType> | null {\n if (original instanceof Error && 'code' in original) {\n if (original.code === 'ENOENT') {\n return new MicrofrontendError(`Could not find \"${fileName}\"`, {\n type: 'config',\n subtype: 'unable_to_read_file',\n source: 'fs',\n });\n }\n if (original.code === 'EACCES') {\n return new MicrofrontendError(\n `Permission denied while accessing \"${fileName}\"`,\n {\n type: 'config',\n subtype: 'invalid_permissions',\n source: 'fs',\n },\n );\n }\n }\n\n if (original instanceof SyntaxError) {\n return new MicrofrontendError(\n `Failed to parse \"${fileName}\": Invalid JSON format.`,\n {\n type: 'config',\n subtype: 'invalid_syntax',\n source: 'fs',\n },\n );\n }\n\n return null;\n }\n\n /**\n * Handles an unknown error and returns a MicrofrontendsError instance.\n * @param err - The error to handle.\n * @returns A MicrofrontendsError instance.\n */\n static handle(\n err: unknown,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (err instanceof MicrofrontendError) {\n return err as MicrofrontendError<MicrofrontendErrorType>;\n }\n\n // handle Error instances\n if (err instanceof Error) {\n return MicrofrontendError.convert(err, opts);\n }\n\n // handle object errors\n if (typeof err === 'object' && err !== null) {\n if ('message' in err && typeof err.message === 'string') {\n return MicrofrontendError.convert(new Error(err.message), opts);\n }\n }\n\n return new MicrofrontendError('An unknown error occurred');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAAe;AACf,uBAAqB;;;ACArB,IAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAEO,SAAS,kCAAkC;AAAA,EAChD;AACF,GAGG;AACD,MAAI,sBAAsB;AACxB,QACE,CAAC,qBAAqB,SAAS,OAAO,KACtC,CAAC,qBAAqB,SAAS,QAAQ,GACvC;AACA,YAAM,IAAI;AAAA,QACR,+EAA+E;AAAA,MAGjF;AAAA,IACF;AACA,WAAO,MAAM;AAAA,MACX,oBAAI,IAAI,CAAC,sBAAsB,GAAG,+BAA+B,CAAC;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;;;ADxBO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AACF,GAGkB;AAChB,aAAW,YAAY,kCAAkC;AAAA,IACvD;AAAA,EACF,CAAC,GAAG;AACF,UAAM,kBAAc,uBAAK,KAAK,QAAQ;AACtC,QAAI,eAAAA,QAAG,WAAW,WAAW,GAAG;AAC9B,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;;;AErBA,iBAAgB;AAET,SAAS,oBAAoB,MAAsB;AACxD,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,+CAA+C;AAAA,EACjE;AAEA,aAAO,WAAAC,SAAI,IAAI,EAAE,UAAU,GAAG,CAAC,EAAE,SAAS,GAAG,GAAG;AAClD;;;ACNA,IAAM,SA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S;AACT,MAAI;AACF,UAAM,gCAA4B;AAAA,MAChC;AAAA,MACA;AAAA,IACF;AACA,UAAM,yBAAqB,2BAAM,yBAAyB;AAE1D,QAAI,mBAAmB,aAAa,eAAe,GAAG;AACpD,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,eAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,mBAAmB,YAAY,GAAG;AACtE,UAAI,IAAI,gBAAgB,iBAAiB;AACvC,eAAO;AAAA,UACL;AAAA,UACA;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,SAASA,QAAP;AACA,WAAO,MAAM,sDAAsDA,MAAK;AAAA,EAE1E;AACA,SAAO;AACT;","names":["fs","md5","import_node_fs","import_node_path","fg","error"]}
|
|
@@ -5,6 +5,10 @@ declare function findConfig({ dir, customConfigFilename, }: {
|
|
|
5
5
|
customConfigFilename: string | undefined;
|
|
6
6
|
}): string | null;
|
|
7
7
|
|
|
8
|
+
declare function generateDefaultAssetPrefixFromName({ name, }: {
|
|
9
|
+
name: string;
|
|
10
|
+
}): string;
|
|
11
|
+
|
|
8
12
|
declare function getPossibleConfigurationFilenames({ customConfigFilename, }: {
|
|
9
13
|
customConfigFilename: string | undefined;
|
|
10
14
|
}): string[] | readonly ["microfrontends.json", "microfrontends.jsonc"];
|
|
@@ -20,4 +24,4 @@ interface FindDefaultMicrofrontendPackageArgs {
|
|
|
20
24
|
*/
|
|
21
25
|
declare function inferMicrofrontendsLocation(opts: FindDefaultMicrofrontendPackageArgs): string;
|
|
22
26
|
|
|
23
|
-
export { findConfig, getPossibleConfigurationFilenames, inferMicrofrontendsLocation };
|
|
27
|
+
export { findConfig, generateDefaultAssetPrefixFromName, getPossibleConfigurationFilenames, inferMicrofrontendsLocation };
|
|
@@ -39,6 +39,26 @@ function findConfig({
|
|
|
39
39
|
return null;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
// src/config/microfrontends/utils/hash-application-name.ts
|
|
43
|
+
import md5 from "md5";
|
|
44
|
+
function hashApplicationName(name) {
|
|
45
|
+
if (!name) {
|
|
46
|
+
throw new Error("Application name is required to generate hash");
|
|
47
|
+
}
|
|
48
|
+
return md5(name).substring(0, 6).padStart(6, "0");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/config/microfrontends/utils/generate-default-asset-prefix.ts
|
|
52
|
+
var PREFIX = "vc-ap";
|
|
53
|
+
function generateDefaultAssetPrefixFromName({
|
|
54
|
+
name
|
|
55
|
+
}) {
|
|
56
|
+
if (!name) {
|
|
57
|
+
throw new Error("Name is required to generate an asset prefix");
|
|
58
|
+
}
|
|
59
|
+
return `${PREFIX}-${hashApplicationName(name)}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
42
62
|
// src/config/microfrontends/utils/infer-microfrontends-location.ts
|
|
43
63
|
import { readFileSync, statSync } from "node:fs";
|
|
44
64
|
import { dirname, join as join2 } from "node:path";
|
|
@@ -329,6 +349,7 @@ function doesApplicationExistInConfig(microfrontendsJsonPath, applicationName) {
|
|
|
329
349
|
}
|
|
330
350
|
export {
|
|
331
351
|
findConfig,
|
|
352
|
+
generateDefaultAssetPrefixFromName,
|
|
332
353
|
getPossibleConfigurationFilenames,
|
|
333
354
|
inferMicrofrontendsLocation
|
|
334
355
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/microfrontends/utils/find-config.ts","../../src/config/microfrontends/utils/get-config-file-name.ts","../../src/config/microfrontends/utils/infer-microfrontends-location.ts","../../src/bin/logger.ts","../../src/config/errors.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { join } from 'node:path';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\nexport function findConfig({\n dir,\n customConfigFilename,\n}: {\n dir: string;\n customConfigFilename: string | undefined;\n}): string | null {\n for (const filename of getPossibleConfigurationFilenames({\n customConfigFilename,\n })) {\n const maybeConfig = join(dir, filename);\n if (fs.existsSync(maybeConfig)) {\n return maybeConfig;\n }\n }\n\n return null;\n}\n","// ordered by most likely to be the correct one\nconst DEFAULT_CONFIGURATION_FILENAMES = [\n 'microfrontends.json',\n 'microfrontends.jsonc',\n] as const;\n\nexport function getPossibleConfigurationFilenames({\n customConfigFilename,\n}: {\n // from env\n customConfigFilename: string | undefined;\n}) {\n if (customConfigFilename) {\n if (\n !customConfigFilename.endsWith('.json') &&\n !customConfigFilename.endsWith('.jsonc')\n ) {\n throw new Error(\n `Found VC_MICROFRONTENDS_CONFIG_FILE_NAME but the name is invalid. Received: ${customConfigFilename}.` +\n ` The file name must end with '.json' or '.jsonc'.` +\n ` It's also possible for the env var to include the path, eg microfrontends-dev.json or /path/to/microfrontends-dev.json.`,\n );\n }\n return Array.from(\n new Set([customConfigFilename, ...DEFAULT_CONFIGURATION_FILENAMES]),\n );\n }\n return DEFAULT_CONFIGURATION_FILENAMES;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport fg from 'fast-glob';\nimport { parse } from 'jsonc-parser';\nimport { logger } from '../../../bin/logger';\nimport { MicrofrontendError } from '../../errors';\nimport type { Config } from '../../schema/types';\nimport type { ApplicationContext } from './get-application-context';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\n// cache the path to default configuration to avoid having to walk the file system multiple times\nconst configCache: Record<string, string> = {};\n\ninterface FindDefaultMicrofrontendPackageArgs {\n repositoryRoot: string;\n applicationContext: ApplicationContext;\n customConfigFilename: string | undefined;\n}\n\n/**\n * Given a repository root and a package name, find the path to the package.json file with the\n * given name.\n *\n * This method uses globby to find all package.json files and then reads them in parallel\n */\nfunction findPackageWithMicrofrontendsConfig({\n repositoryRoot,\n applicationContext,\n customConfigFilename,\n}: FindDefaultMicrofrontendPackageArgs): string | null {\n const applicationName = applicationContext.name;\n logger.debug(\n '[MFE Config] Searching repository for configs containing application:',\n applicationName,\n );\n\n try {\n const microfrontendsJsonPaths = fg.globSync(\n `**/{${getPossibleConfigurationFilenames({ customConfigFilename }).join(',')}}`,\n {\n cwd: repositoryRoot,\n absolute: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n ignore: ['**/node_modules/**', '**/.git/**'],\n },\n );\n\n logger.debug(\n '[MFE Config] Found',\n microfrontendsJsonPaths.length,\n 'config file(s) in repository',\n );\n\n const matchingPaths: string[] = [];\n for (const microfrontendsJsonPath of microfrontendsJsonPaths) {\n if (\n doesApplicationExistInConfig(microfrontendsJsonPath, applicationName)\n ) {\n matchingPaths.push(microfrontendsJsonPath);\n }\n }\n\n logger.debug(\n '[MFE Config] Total matching config files:',\n matchingPaths.length,\n );\n\n if (matchingPaths.length > 1) {\n throw new MicrofrontendError(\n `Found multiple \\`microfrontends.json\\` files in the repository referencing the application \"${applicationName}\", but only one is allowed.\\n${matchingPaths.join('\\n • ')}`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n if (matchingPaths.length === 0) {\n if (\n repositoryRoot &&\n doesMisplacedConfigExist(\n repositoryRoot,\n applicationName,\n customConfigFilename,\n )\n ) {\n logger.debug(\n '[MFE Config] Found misplaced config in wrong .vercel directory in repository',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n throw new MicrofrontendError(\n `Unable to automatically infer the location of the \\`microfrontends.json\\` file.\\n\\n` +\n `A microfrontends config was found in the \\`.vercel\\` directory at the repository root: ${misplacedConfigPath}\\n` +\n `However, in a monorepo, the config file should be placed in the \\`.vercel\\` directory in your application directory instead.\\n\\n` +\n `To fix this:\\n` +\n `1. If using \\`vercel link\\`, run it with \\`vercel link --repo\\` to handle monorepos, or run \\`vercel microfrontends pull --cwd=<application-directory>\\` to make sure it pulls the \\`microfrontends.json\\` file to the correct location\\n` +\n `2. If manually defined, move the config file to the \\`.vercel\\` directory in your application\\n` +\n `3. Alternatively, set the VC_MICROFRONTENDS_CONFIG environment variable to the correct path\\n\\n` +\n `For more information, see: https://vercel.com/docs/cli/project-linking`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n let additionalErrorMessage = '';\n if (microfrontendsJsonPaths.length > 0) {\n if (!applicationContext.projectName) {\n additionalErrorMessage = `\\n\\nIf 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.`;\n } else {\n additionalErrorMessage = `\\n\\nNames of applications in \\`microfrontends.json\\` must match the Vercel Project name (${applicationContext.projectName}).`;\n }\n }\n throw new MicrofrontendError(\n `Could not find a \\`microfrontends.json\\` file in the repository that contains the \"${applicationName}\" application.${additionalErrorMessage}\\n\\n` +\n `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.\\n\\n` +\n `If your Vercel Microfrontends configuration has a custom name, ensure the VC_MICROFRONTENDS_CONFIG_FILE_NAME environment variable is set, you can pull the vercel project environment variables using the \"vercel env pull\" command.\\n\\n` +\n `If you suspect this is thrown in error, please reach out to the Vercel team.`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n const [packageJsonPath] = matchingPaths as [string];\n return dirname(packageJsonPath);\n } catch (error) {\n if (error instanceof MicrofrontendError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Given a repository root and a package name, find the path to the package directory with\n * a microfrontends config that contains the given name in its applications.\n */\nexport function inferMicrofrontendsLocation(\n opts: FindDefaultMicrofrontendPackageArgs,\n): string {\n // cache this with name to support multiple configurations in the same repository\n const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}${opts.customConfigFilename ? `-${opts.customConfigFilename}` : ''}`;\n\n // Check if we have a cached result\n if (configCache[cacheKey]) {\n return configCache[cacheKey];\n }\n\n const result = findPackageWithMicrofrontendsConfig(opts);\n\n if (!result) {\n throw new MicrofrontendError(\n `Could not infer the location of the \\`microfrontends.json\\` file for application \"${opts.applicationContext.name}\" starting in directory \"${opts.repositoryRoot}\".`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n // Cache the result\n configCache[cacheKey] = result;\n return result;\n}\n\nfunction existsSync(path: string): boolean {\n try {\n statSync(path);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nfunction doesMisplacedConfigExist(\n repositoryRoot: string,\n applicationName: string,\n customConfigFilename: string | undefined,\n): boolean {\n logger.debug(\n '[MFE Config] Looking for misplaced config in wrong .vercel directory',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n return (\n existsSync(misplacedConfigPath) &&\n doesApplicationExistInConfig(misplacedConfigPath, applicationName)\n );\n}\n\nfunction doesApplicationExistInConfig(\n microfrontendsJsonPath: string,\n applicationName: string,\n): boolean {\n try {\n const microfrontendsJsonContent = readFileSync(\n microfrontendsJsonPath,\n 'utf-8',\n );\n const microfrontendsJson = parse(microfrontendsJsonContent) as Config;\n\n if (microfrontendsJson.applications[applicationName]) {\n logger.debug(\n '[MFE Config] Found application in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n\n for (const [_, app] of Object.entries(microfrontendsJson.applications)) {\n if (app.packageName === applicationName) {\n logger.debug(\n '[MFE Config] Found application via packageName in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n }\n } catch (error) {\n logger.debug('[MFE Config] Error checking application in config:', error);\n // malformed json most likely, skip this file\n }\n return false;\n}\n","/* eslint-disable no-console */\n\nfunction debug(...args: unknown[]): void {\n if (process.env.MFE_DEBUG) {\n console.log(...args);\n }\n}\n\nfunction info(...args: unknown[]): void {\n console.log(...args);\n}\n\nfunction warn(...args: unknown[]): void {\n console.warn(...args);\n}\n\nfunction error(...args: unknown[]): void {\n console.error(...args);\n}\n\nexport const logger = {\n debug,\n info,\n warn,\n error,\n};\n","export type MicrofrontendErrorType =\n | 'config'\n | 'packageJson'\n | 'vercelJson'\n | 'application'\n | 'unknown';\n\nexport type MicrofrontendErrorSubtype =\n | 'not_found'\n | 'inference_failed'\n | 'not_found_in_env'\n | 'invalid_asset_prefix'\n | 'invalid_main_path'\n | 'does_not_match_schema'\n | 'unable_to_read_file'\n | 'unsupported_validation_env'\n | 'unsupported_version'\n | 'invalid_path'\n | 'invalid_permissions'\n | 'invalid_syntax'\n | 'missing_microfrontend_config_path'\n | 'unsupported_operation';\n\n// A mapping of error types to their subtypes.\ninterface TypeToSubtype {\n application:\n | 'invalid_asset_prefix'\n | 'invalid_path'\n | 'multiple_package_managers'\n | 'not_found';\n config:\n | 'conflicting_paths'\n | 'depcrecated_field'\n | 'does_not_match_schema'\n | 'invalid_main_path'\n | 'invalid_preview_deployment_suffix'\n | 'multiple_default_applications'\n | 'no_default_application'\n | 'not_found_in_env'\n | 'not_found'\n | 'inference_failed'\n | 'unable_to_read_file'\n | 'invalid_syntax'\n | 'invalid_permissions'\n | 'unsupported_operation'\n | 'unsupported_validation_env'\n | 'unsupported_version';\n packageJson:\n | 'missing_field_name'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n vercelJson:\n | 'missing_field_microfrontend_config_path'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n unknown: never;\n}\n\nexport type MicrofrontendErrorSource =\n | '@vercel/microfrontends'\n | '@vercel/microfrontends/next'\n | 'fs'\n | 'ajv';\n\nexport interface MicrofrontendErrorOptions<T extends MicrofrontendErrorType> {\n cause?: unknown;\n source?: MicrofrontendErrorSource;\n type?: T;\n subtype?: TypeToSubtype[T];\n}\n\ninterface HandleOptions {\n fileName?: string;\n}\n\nexport class MicrofrontendError<\n T extends MicrofrontendErrorType = 'unknown',\n> extends Error {\n public source: MicrofrontendErrorSource;\n public type: T;\n public subtype?: TypeToSubtype[T];\n\n constructor(message: string, opts?: MicrofrontendErrorOptions<T>) {\n super(message, { cause: opts?.cause });\n this.name = 'MicrofrontendsError';\n this.source = opts?.source ?? '@vercel/microfrontends';\n this.type = opts?.type ?? ('unknown' as T);\n this.subtype = opts?.subtype;\n Error.captureStackTrace(this, MicrofrontendError);\n }\n\n isKnown(): boolean {\n return this.type !== 'unknown';\n }\n\n isUnknown(): boolean {\n return !this.isKnown();\n }\n\n /**\n * Converts an error to a MicrofrontendsError.\n * @param original - The original error to convert.\n * @returns The converted MicrofrontendsError.\n */\n static convert(\n original: Error,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (opts?.fileName) {\n const err = MicrofrontendError.convertFSError(original, opts.fileName);\n if (err) {\n return err;\n }\n }\n\n if (\n original.message.includes(\n 'Code generation from strings disallowed for this context',\n )\n ) {\n return new MicrofrontendError(original.message, {\n type: 'config',\n subtype: 'unsupported_validation_env',\n source: 'ajv',\n });\n }\n\n // unknown catch-all\n return new MicrofrontendError(original.message);\n }\n\n static convertFSError(\n original: Error,\n fileName: string,\n ): MicrofrontendError<MicrofrontendErrorType> | null {\n if (original instanceof Error && 'code' in original) {\n if (original.code === 'ENOENT') {\n return new MicrofrontendError(`Could not find \"${fileName}\"`, {\n type: 'config',\n subtype: 'unable_to_read_file',\n source: 'fs',\n });\n }\n if (original.code === 'EACCES') {\n return new MicrofrontendError(\n `Permission denied while accessing \"${fileName}\"`,\n {\n type: 'config',\n subtype: 'invalid_permissions',\n source: 'fs',\n },\n );\n }\n }\n\n if (original instanceof SyntaxError) {\n return new MicrofrontendError(\n `Failed to parse \"${fileName}\": Invalid JSON format.`,\n {\n type: 'config',\n subtype: 'invalid_syntax',\n source: 'fs',\n },\n );\n }\n\n return null;\n }\n\n /**\n * Handles an unknown error and returns a MicrofrontendsError instance.\n * @param err - The error to handle.\n * @returns A MicrofrontendsError instance.\n */\n static handle(\n err: unknown,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (err instanceof MicrofrontendError) {\n return err as MicrofrontendError<MicrofrontendErrorType>;\n }\n\n // handle Error instances\n if (err instanceof Error) {\n return MicrofrontendError.convert(err, opts);\n }\n\n // handle object errors\n if (typeof err === 'object' && err !== null) {\n if ('message' in err && typeof err.message === 'string') {\n return MicrofrontendError.convert(new Error(err.message), opts);\n }\n }\n\n return new MicrofrontendError('An unknown error occurred');\n }\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,SAAS,YAAY;;;ACArB,IAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAEO,SAAS,kCAAkC;AAAA,EAChD;AACF,GAGG;AACD,MAAI,sBAAsB;AACxB,QACE,CAAC,qBAAqB,SAAS,OAAO,KACtC,CAAC,qBAAqB,SAAS,QAAQ,GACvC;AACA,YAAM,IAAI;AAAA,QACR,+EAA+E;AAAA,MAGjF;AAAA,IACF;AACA,WAAO,MAAM;AAAA,MACX,oBAAI,IAAI,CAAC,sBAAsB,GAAG,+BAA+B,CAAC;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;;;ADxBO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AACF,GAGkB;AAChB,aAAW,YAAY,kCAAkC;AAAA,IACvD;AAAA,EACF,CAAC,GAAG;AACF,UAAM,cAAc,KAAK,KAAK,QAAQ;AACtC,QAAI,GAAG,WAAW,WAAW,GAAG;AAC9B,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;;;AErBA,SAAS,cAAc,gBAAgB;AACvC,SAAS,SAAS,QAAAA,aAAY;AAC9B,OAAO,QAAQ;AACf,SAAS,aAAa;;;ACDtB,SAAS,SAAS,MAAuB;AACvC,MAAI,QAAQ,IAAI,WAAW;AACzB,YAAQ,IAAI,GAAG,IAAI;AAAA,EACrB;AACF;AAEA,SAAS,QAAQ,MAAuB;AACtC,UAAQ,IAAI,GAAG,IAAI;AACrB;AAEA,SAAS,QAAQ,MAAuB;AACtC,UAAQ,KAAK,GAAG,IAAI;AACtB;AAEA,SAAS,SAAS,MAAuB;AACvC,UAAQ,MAAM,GAAG,IAAI;AACvB;AAEO,IAAM,SAAS;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACoD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ACzB,WAAO,YAAY,QAAQ;AAAA,EAC7B;AAEA,QAAM,SAAS,oCAAoC,IAAI;AAEvD,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,qFAAqF,KAAK,mBAAmB,gCAAgC,KAAK;AAAA,MAClJ,EAAE,MAAM,UAAU,SAAS,mBAAmB;AAAA,IAChD;AAAA,EACF;AAGA,cAAY,QAAQ,IAAI;AACxB,SAAO;AACT;AAEA,SAAS,WAAW,MAAuB;AACzC,MAAI;AACF,aAAS,IAAI;AACb,WAAO;AAAA,EACT,SAAS,GAAP;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,yBACP,gBACA,iBACA,sBACS;AACT,SAAO;AAAA,IACL;AAAA,EACF;AACA,QAAM,sBAAsBD;AAAA,IAC1B;AAAA,IACA;AAAA,IACA,wBAAwB;AAAA,EAC1B;AACA,SACE,WAAW,mBAAmB,KAC9B,6BAA6B,qBAAqB,eAAe;AAErE;AAEA,SAAS,6BACP,wBACA,iBACS;AACT,MAAI;AACF,UAAM,4BAA4B;AAAA,MAChC;AAAA,MACA;AAAA,IACF;AACA,UAAM,qBAAqB,MAAM,yBAAyB;AAE1D,QAAI,mBAAmB,aAAa,eAAe,GAAG;AACpD,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,eAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,mBAAmB,YAAY,GAAG;AACtE,UAAI,IAAI,gBAAgB,iBAAiB;AACvC,eAAO;AAAA,UACL;AAAA,UACA;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,SAASC,QAAP;AACA,WAAO,MAAM,sDAAsDA,MAAK;AAAA,EAE1E;AACA,SAAO;AACT;","names":["join","join","error"]}
|
|
1
|
+
{"version":3,"sources":["../../src/config/microfrontends/utils/find-config.ts","../../src/config/microfrontends/utils/get-config-file-name.ts","../../src/config/microfrontends/utils/hash-application-name.ts","../../src/config/microfrontends/utils/generate-default-asset-prefix.ts","../../src/config/microfrontends/utils/infer-microfrontends-location.ts","../../src/bin/logger.ts","../../src/config/errors.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { join } from 'node:path';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\nexport function findConfig({\n dir,\n customConfigFilename,\n}: {\n dir: string;\n customConfigFilename: string | undefined;\n}): string | null {\n for (const filename of getPossibleConfigurationFilenames({\n customConfigFilename,\n })) {\n const maybeConfig = join(dir, filename);\n if (fs.existsSync(maybeConfig)) {\n return maybeConfig;\n }\n }\n\n return null;\n}\n","// ordered by most likely to be the correct one\nconst DEFAULT_CONFIGURATION_FILENAMES = [\n 'microfrontends.json',\n 'microfrontends.jsonc',\n] as const;\n\nexport function getPossibleConfigurationFilenames({\n customConfigFilename,\n}: {\n // from env\n customConfigFilename: string | undefined;\n}) {\n if (customConfigFilename) {\n if (\n !customConfigFilename.endsWith('.json') &&\n !customConfigFilename.endsWith('.jsonc')\n ) {\n throw new Error(\n `Found VC_MICROFRONTENDS_CONFIG_FILE_NAME but the name is invalid. Received: ${customConfigFilename}.` +\n ` The file name must end with '.json' or '.jsonc'.` +\n ` It's also possible for the env var to include the path, eg microfrontends-dev.json or /path/to/microfrontends-dev.json.`,\n );\n }\n return Array.from(\n new Set([customConfigFilename, ...DEFAULT_CONFIGURATION_FILENAMES]),\n );\n }\n return DEFAULT_CONFIGURATION_FILENAMES;\n}\n","import md5 from 'md5';\n\nexport function hashApplicationName(name: string): string {\n if (!name) {\n throw new Error('Application name is required to generate hash');\n }\n\n return md5(name).substring(0, 6).padStart(6, '0');\n}\n","import { hashApplicationName } from './hash-application-name';\n\nconst PREFIX = 'vc-ap';\n\nexport function generateDefaultAssetPrefixFromName({\n name,\n}: {\n name: string;\n}): string {\n if (!name) {\n throw new Error('Name is required to generate an asset prefix');\n }\n\n return `${PREFIX}-${hashApplicationName(name)}`;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport fg from 'fast-glob';\nimport { parse } from 'jsonc-parser';\nimport { logger } from '../../../bin/logger';\nimport { MicrofrontendError } from '../../errors';\nimport type { Config } from '../../schema/types';\nimport type { ApplicationContext } from './get-application-context';\nimport { getPossibleConfigurationFilenames } from './get-config-file-name';\n\n// cache the path to default configuration to avoid having to walk the file system multiple times\nconst configCache: Record<string, string> = {};\n\ninterface FindDefaultMicrofrontendPackageArgs {\n repositoryRoot: string;\n applicationContext: ApplicationContext;\n customConfigFilename: string | undefined;\n}\n\n/**\n * Given a repository root and a package name, find the path to the package.json file with the\n * given name.\n *\n * This method uses globby to find all package.json files and then reads them in parallel\n */\nfunction findPackageWithMicrofrontendsConfig({\n repositoryRoot,\n applicationContext,\n customConfigFilename,\n}: FindDefaultMicrofrontendPackageArgs): string | null {\n const applicationName = applicationContext.name;\n logger.debug(\n '[MFE Config] Searching repository for configs containing application:',\n applicationName,\n );\n\n try {\n const microfrontendsJsonPaths = fg.globSync(\n `**/{${getPossibleConfigurationFilenames({ customConfigFilename }).join(',')}}`,\n {\n cwd: repositoryRoot,\n absolute: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n ignore: ['**/node_modules/**', '**/.git/**'],\n },\n );\n\n logger.debug(\n '[MFE Config] Found',\n microfrontendsJsonPaths.length,\n 'config file(s) in repository',\n );\n\n const matchingPaths: string[] = [];\n for (const microfrontendsJsonPath of microfrontendsJsonPaths) {\n if (\n doesApplicationExistInConfig(microfrontendsJsonPath, applicationName)\n ) {\n matchingPaths.push(microfrontendsJsonPath);\n }\n }\n\n logger.debug(\n '[MFE Config] Total matching config files:',\n matchingPaths.length,\n );\n\n if (matchingPaths.length > 1) {\n throw new MicrofrontendError(\n `Found multiple \\`microfrontends.json\\` files in the repository referencing the application \"${applicationName}\", but only one is allowed.\\n${matchingPaths.join('\\n • ')}`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n if (matchingPaths.length === 0) {\n if (\n repositoryRoot &&\n doesMisplacedConfigExist(\n repositoryRoot,\n applicationName,\n customConfigFilename,\n )\n ) {\n logger.debug(\n '[MFE Config] Found misplaced config in wrong .vercel directory in repository',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n throw new MicrofrontendError(\n `Unable to automatically infer the location of the \\`microfrontends.json\\` file.\\n\\n` +\n `A microfrontends config was found in the \\`.vercel\\` directory at the repository root: ${misplacedConfigPath}\\n` +\n `However, in a monorepo, the config file should be placed in the \\`.vercel\\` directory in your application directory instead.\\n\\n` +\n `To fix this:\\n` +\n `1. If using \\`vercel link\\`, run it with \\`vercel link --repo\\` to handle monorepos, or run \\`vercel microfrontends pull --cwd=<application-directory>\\` to make sure it pulls the \\`microfrontends.json\\` file to the correct location\\n` +\n `2. If manually defined, move the config file to the \\`.vercel\\` directory in your application\\n` +\n `3. Alternatively, set the VC_MICROFRONTENDS_CONFIG environment variable to the correct path\\n\\n` +\n `For more information, see: https://vercel.com/docs/cli/project-linking`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n let additionalErrorMessage = '';\n if (microfrontendsJsonPaths.length > 0) {\n if (!applicationContext.projectName) {\n additionalErrorMessage = `\\n\\nIf 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.`;\n } else {\n additionalErrorMessage = `\\n\\nNames of applications in \\`microfrontends.json\\` must match the Vercel Project name (${applicationContext.projectName}).`;\n }\n }\n throw new MicrofrontendError(\n `Could not find a \\`microfrontends.json\\` file in the repository that contains the \"${applicationName}\" application.${additionalErrorMessage}\\n\\n` +\n `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.\\n\\n` +\n `If your Vercel Microfrontends configuration has a custom name, ensure the VC_MICROFRONTENDS_CONFIG_FILE_NAME environment variable is set, you can pull the vercel project environment variables using the \"vercel env pull\" command.\\n\\n` +\n `If you suspect this is thrown in error, please reach out to the Vercel team.`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n const [packageJsonPath] = matchingPaths as [string];\n return dirname(packageJsonPath);\n } catch (error) {\n if (error instanceof MicrofrontendError) {\n throw error;\n }\n return null;\n }\n}\n\n/**\n * Given a repository root and a package name, find the path to the package directory with\n * a microfrontends config that contains the given name in its applications.\n */\nexport function inferMicrofrontendsLocation(\n opts: FindDefaultMicrofrontendPackageArgs,\n): string {\n // cache this with name to support multiple configurations in the same repository\n const cacheKey = `${opts.repositoryRoot}-${opts.applicationContext.name}${opts.customConfigFilename ? `-${opts.customConfigFilename}` : ''}`;\n\n // Check if we have a cached result\n if (configCache[cacheKey]) {\n return configCache[cacheKey];\n }\n\n const result = findPackageWithMicrofrontendsConfig(opts);\n\n if (!result) {\n throw new MicrofrontendError(\n `Could not infer the location of the \\`microfrontends.json\\` file for application \"${opts.applicationContext.name}\" starting in directory \"${opts.repositoryRoot}\".`,\n { type: 'config', subtype: 'inference_failed' },\n );\n }\n\n // Cache the result\n configCache[cacheKey] = result;\n return result;\n}\n\nfunction existsSync(path: string): boolean {\n try {\n statSync(path);\n return true;\n } catch (_) {\n return false;\n }\n}\n\nfunction doesMisplacedConfigExist(\n repositoryRoot: string,\n applicationName: string,\n customConfigFilename: string | undefined,\n): boolean {\n logger.debug(\n '[MFE Config] Looking for misplaced config in wrong .vercel directory',\n );\n const misplacedConfigPath = join(\n repositoryRoot,\n '.vercel',\n customConfigFilename || 'microfrontends.json',\n );\n return (\n existsSync(misplacedConfigPath) &&\n doesApplicationExistInConfig(misplacedConfigPath, applicationName)\n );\n}\n\nfunction doesApplicationExistInConfig(\n microfrontendsJsonPath: string,\n applicationName: string,\n): boolean {\n try {\n const microfrontendsJsonContent = readFileSync(\n microfrontendsJsonPath,\n 'utf-8',\n );\n const microfrontendsJson = parse(microfrontendsJsonContent) as Config;\n\n if (microfrontendsJson.applications[applicationName]) {\n logger.debug(\n '[MFE Config] Found application in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n\n for (const [_, app] of Object.entries(microfrontendsJson.applications)) {\n if (app.packageName === applicationName) {\n logger.debug(\n '[MFE Config] Found application via packageName in config:',\n microfrontendsJsonPath,\n );\n return true;\n }\n }\n } catch (error) {\n logger.debug('[MFE Config] Error checking application in config:', error);\n // malformed json most likely, skip this file\n }\n return false;\n}\n","/* eslint-disable no-console */\n\nfunction debug(...args: unknown[]): void {\n if (process.env.MFE_DEBUG) {\n console.log(...args);\n }\n}\n\nfunction info(...args: unknown[]): void {\n console.log(...args);\n}\n\nfunction warn(...args: unknown[]): void {\n console.warn(...args);\n}\n\nfunction error(...args: unknown[]): void {\n console.error(...args);\n}\n\nexport const logger = {\n debug,\n info,\n warn,\n error,\n};\n","export type MicrofrontendErrorType =\n | 'config'\n | 'packageJson'\n | 'vercelJson'\n | 'application'\n | 'unknown';\n\nexport type MicrofrontendErrorSubtype =\n | 'not_found'\n | 'inference_failed'\n | 'not_found_in_env'\n | 'invalid_asset_prefix'\n | 'invalid_main_path'\n | 'does_not_match_schema'\n | 'unable_to_read_file'\n | 'unsupported_validation_env'\n | 'unsupported_version'\n | 'invalid_path'\n | 'invalid_permissions'\n | 'invalid_syntax'\n | 'missing_microfrontend_config_path'\n | 'unsupported_operation';\n\n// A mapping of error types to their subtypes.\ninterface TypeToSubtype {\n application:\n | 'invalid_asset_prefix'\n | 'invalid_path'\n | 'multiple_package_managers'\n | 'not_found';\n config:\n | 'conflicting_paths'\n | 'depcrecated_field'\n | 'does_not_match_schema'\n | 'invalid_main_path'\n | 'invalid_preview_deployment_suffix'\n | 'multiple_default_applications'\n | 'no_default_application'\n | 'not_found_in_env'\n | 'not_found'\n | 'inference_failed'\n | 'unable_to_read_file'\n | 'invalid_syntax'\n | 'invalid_permissions'\n | 'unsupported_operation'\n | 'unsupported_validation_env'\n | 'unsupported_version';\n packageJson:\n | 'missing_field_name'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n vercelJson:\n | 'missing_field_microfrontend_config_path'\n | 'unable_to_read_file'\n | 'invalid_permissions'\n | 'invalid_syntax';\n unknown: never;\n}\n\nexport type MicrofrontendErrorSource =\n | '@vercel/microfrontends'\n | '@vercel/microfrontends/next'\n | 'fs'\n | 'ajv';\n\nexport interface MicrofrontendErrorOptions<T extends MicrofrontendErrorType> {\n cause?: unknown;\n source?: MicrofrontendErrorSource;\n type?: T;\n subtype?: TypeToSubtype[T];\n}\n\ninterface HandleOptions {\n fileName?: string;\n}\n\nexport class MicrofrontendError<\n T extends MicrofrontendErrorType = 'unknown',\n> extends Error {\n public source: MicrofrontendErrorSource;\n public type: T;\n public subtype?: TypeToSubtype[T];\n\n constructor(message: string, opts?: MicrofrontendErrorOptions<T>) {\n super(message, { cause: opts?.cause });\n this.name = 'MicrofrontendsError';\n this.source = opts?.source ?? '@vercel/microfrontends';\n this.type = opts?.type ?? ('unknown' as T);\n this.subtype = opts?.subtype;\n Error.captureStackTrace(this, MicrofrontendError);\n }\n\n isKnown(): boolean {\n return this.type !== 'unknown';\n }\n\n isUnknown(): boolean {\n return !this.isKnown();\n }\n\n /**\n * Converts an error to a MicrofrontendsError.\n * @param original - The original error to convert.\n * @returns The converted MicrofrontendsError.\n */\n static convert(\n original: Error,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (opts?.fileName) {\n const err = MicrofrontendError.convertFSError(original, opts.fileName);\n if (err) {\n return err;\n }\n }\n\n if (\n original.message.includes(\n 'Code generation from strings disallowed for this context',\n )\n ) {\n return new MicrofrontendError(original.message, {\n type: 'config',\n subtype: 'unsupported_validation_env',\n source: 'ajv',\n });\n }\n\n // unknown catch-all\n return new MicrofrontendError(original.message);\n }\n\n static convertFSError(\n original: Error,\n fileName: string,\n ): MicrofrontendError<MicrofrontendErrorType> | null {\n if (original instanceof Error && 'code' in original) {\n if (original.code === 'ENOENT') {\n return new MicrofrontendError(`Could not find \"${fileName}\"`, {\n type: 'config',\n subtype: 'unable_to_read_file',\n source: 'fs',\n });\n }\n if (original.code === 'EACCES') {\n return new MicrofrontendError(\n `Permission denied while accessing \"${fileName}\"`,\n {\n type: 'config',\n subtype: 'invalid_permissions',\n source: 'fs',\n },\n );\n }\n }\n\n if (original instanceof SyntaxError) {\n return new MicrofrontendError(\n `Failed to parse \"${fileName}\": Invalid JSON format.`,\n {\n type: 'config',\n subtype: 'invalid_syntax',\n source: 'fs',\n },\n );\n }\n\n return null;\n }\n\n /**\n * Handles an unknown error and returns a MicrofrontendsError instance.\n * @param err - The error to handle.\n * @returns A MicrofrontendsError instance.\n */\n static handle(\n err: unknown,\n opts?: HandleOptions,\n ): MicrofrontendError<MicrofrontendErrorType> {\n if (err instanceof MicrofrontendError) {\n return err as MicrofrontendError<MicrofrontendErrorType>;\n }\n\n // handle Error instances\n if (err instanceof Error) {\n return MicrofrontendError.convert(err, opts);\n }\n\n // handle object errors\n if (typeof err === 'object' && err !== null) {\n if ('message' in err && typeof err.message === 'string') {\n return MicrofrontendError.convert(new Error(err.message), opts);\n }\n }\n\n return new MicrofrontendError('An unknown error occurred');\n }\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,SAAS,YAAY;;;ACArB,IAAM,kCAAkC;AAAA,EACtC;AAAA,EACA;AACF;AAEO,SAAS,kCAAkC;AAAA,EAChD;AACF,GAGG;AACD,MAAI,sBAAsB;AACxB,QACE,CAAC,qBAAqB,SAAS,OAAO,KACtC,CAAC,qBAAqB,SAAS,QAAQ,GACvC;AACA,YAAM,IAAI;AAAA,QACR,+EAA+E;AAAA,MAGjF;AAAA,IACF;AACA,WAAO,MAAM;AAAA,MACX,oBAAI,IAAI,CAAC,sBAAsB,GAAG,+BAA+B,CAAC;AAAA,IACpE;AAAA,EACF;AACA,SAAO;AACT;;;ADxBO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AACF,GAGkB;AAChB,aAAW,YAAY,kCAAkC;AAAA,IACvD;A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IAAI;AACxB,SAAO;AACT;AAEA,SAAS,WAAW,MAAuB;AACzC,MAAI;AACF,aAAS,IAAI;AACb,WAAO;AAAA,EACT,SAAS,GAAP;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,yBACP,gBACA,iBACA,sBACS;AACT,SAAO;AAAA,IACL;AAAA,EACF;AACA,QAAM,sBAAsBD;AAAA,IAC1B;AAAA,IACA;AAAA,IACA,wBAAwB;AAAA,EAC1B;AACA,SACE,WAAW,mBAAmB,KAC9B,6BAA6B,qBAAqB,eAAe;AAErE;AAEA,SAAS,6BACP,wBACA,iBACS;AACT,MAAI;AACF,UAAM,4BAA4B;AAAA,MAChC;AAAA,MACA;AAAA,IACF;AACA,UAAM,qBAAqB,MAAM,yBAAyB;AAE1D,QAAI,mBAAmB,aAAa,eAAe,GAAG;AACpD,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,eAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,mBAAmB,YAAY,GAAG;AACtE,UAAI,IAAI,gBAAgB,iBAAiB;AACvC,eAAO;AAAA,UACL;AAAA,UACA;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF,SAASC,QAAP;AACA,WAAO,MAAM,sDAAsDA,MAAK;AAAA,EAE1E;AACA,SAAO;AACT;","names":["join","join","error"]}
|
package/dist/next/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/client/index.ts","../../src/next/client/link/microfrontends-link.tsx","../../src/config/react/use-client-config.ts","../../src/config/microfrontends-config/client/index.ts","../../src/next/client/prefetch/prefetch-cross-zone-links.tsx","../../src/next/client/prefetch/prefetch-cross-zone-links-context.tsx"],"sourcesContent":["export * from './link';\nexport * from './prefetch';\n","import NextLink, {\n type LinkProps as ExternalNextLinkProps,\n} from 'next/link.js';\nimport type { AnchorHTMLAttributes } from 'react';\nimport { forwardRef, useContext, useMemo } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\nimport { PrefetchCrossZoneLinksContext } from '../prefetch';\n\ninterface BaseProps {\n children: React.ReactNode;\n href: string;\n}\n\n// fix for tsc inlining LinkProps from next\n// https://github.com/microsoft/TypeScript/issues/37151#issuecomment-756232934\ninterface NextLinkProps extends ExternalNextLinkProps {}\nexport type LinkProps = BaseProps &\n Omit<NextLinkProps, keyof BaseProps> &\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof BaseProps>;\n\nconst CURRENT_ZONE_HASH = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION_HASH;\n\nexport function useZoneForHref(href: LinkProps['href'] | undefined): {\n zoneOfHref: string | null;\n isDifferentZone: boolean;\n isLoading: boolean;\n} {\n const { clientConfig, isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const { isRelativePath, zoneOfHref } = useMemo(() => {\n const isRelative = typeof href === 'string' && href.startsWith('/');\n return {\n isRelativePath: isRelative,\n zoneOfHref: isRelative\n ? clientConfig.getApplicationNameForPath(href)\n : null,\n };\n }, [clientConfig, href]);\n\n if (typeof href === 'string' && !href.length) {\n return {\n zoneOfHref: null,\n isDifferentZone: false,\n isLoading: false,\n };\n }\n const isDifferentZone =\n !isRelativePath || (zoneOfHref ? CURRENT_ZONE_HASH !== zoneOfHref : false);\n return { zoneOfHref, isDifferentZone, isLoading };\n}\n\n/**\n * A Link component that works with microfrontend set-ups and will prefetch the\n * cross zone links automatically.\n */\nexport const Link = forwardRef<HTMLAnchorElement, LinkProps>(\n ({ children, ...props }, ref): JSX.Element => {\n const { prefetchHref } = useContext(PrefetchCrossZoneLinksContext);\n const { zoneOfHref, isDifferentZone, isLoading } = useZoneForHref(\n props.href,\n );\n\n function onHoverPrefetch(): void {\n if (!props.href) {\n return;\n }\n prefetchHref(props.href);\n }\n\n if (isDifferentZone && zoneOfHref !== null) {\n const { prefetch: _, ...rest } = props;\n return (\n <a\n {...rest}\n data-zone={zoneOfHref}\n onFocus={props.prefetch !== false ? onHoverPrefetch : undefined}\n onMouseOver={props.prefetch !== false ? onHoverPrefetch : undefined}\n >\n {children}\n </a>\n );\n }\n\n return (\n <NextLink\n {...props}\n data-zone={!zoneOfHref ? 'null' : 'same'}\n prefetch={props.prefetch ?? (isLoading ? false : undefined)}\n ref={ref}\n >\n {children}\n </NextLink>\n );\n },\n);\nLink.displayName = 'MicrofrontendsLink';\n","'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { MicrofrontendConfigClient } from '../microfrontends-config/client';\nimport type { WellKnownClientData } from '../well-known/types';\n\nconst clientCache = new Map<string, MicrofrontendConfigClient>();\nconst cachedHasDynamicPaths = new Map<string, boolean>();\n\nconst getClient = (config: string | undefined) => {\n const existing = clientCache.get(config || '');\n if (existing) {\n return existing;\n }\n\n const client = MicrofrontendConfigClient.fromEnv(config);\n clientCache.set(config || '', client);\n return client;\n};\n\nlet cachedServerClientConfigPromise: Promise<MicrofrontendConfigClient | null> | null =\n null;\n\nlet cachedServerClient: MicrofrontendConfigClient | null = null;\n\nasync function fetchClientConfigFromServer(): Promise<MicrofrontendConfigClient | null> {\n try {\n const response = await fetch(\n '/.well-known/vercel/microfrontends/client-config',\n );\n if (response.status !== 200) {\n return null;\n }\n const responseJson = (await response.json()) as WellKnownClientData;\n const client = new MicrofrontendConfigClient(responseJson.config);\n cachedServerClient = client;\n return client;\n } catch (err) {\n return null;\n }\n}\n\n/**\n * Hook to use the client microfrontends configuration. This hook will resolve\n * dynamic paths by fetching the configuration from the server if necessary,\n * allowing the server to specify the values for dynamic paths.\n */\nexport function useClientConfig(config: string | undefined): {\n clientConfig: MicrofrontendConfigClient;\n isLoading: boolean;\n} {\n const [clientConfig, setClientConfig] = useState<MicrofrontendConfigClient>(\n () => cachedServerClient ?? getClient(config),\n );\n const canLoad = useMemo(() => {\n if (\n process.env.NODE_ENV === 'test' &&\n process.env.MFE_FORCE_CLIENT_CONFIG_FROM_SERVER !== '1'\n ) {\n return false;\n }\n // If we've already fetched the server config and it's resolved, we don't need\n // to enter the loading state at all\n if (cachedServerClient) return false;\n // If we've already checked this config for dynamic paths, we can use the\n // cached result from before instead of reevaluating.\n const existing = cachedHasDynamicPaths.get(config || '');\n if (existing !== undefined) return existing;\n // Get the original client config to determine if the config has any\n // dynamic paths.\n const originalClientConfig = getClient(config);\n // As an optimization, only fetch the config from the server if the\n // microfrontends configuration has any dynamic paths. If it doesn't,\n // then the server won't return any different values.\n const hasDynamicPaths = originalClientConfig.hasFlaggedPaths;\n cachedHasDynamicPaths.set(config || '', hasDynamicPaths);\n if (!hasDynamicPaths) {\n return false;\n }\n return true;\n }, [config]);\n const [isLoading, setIsLoading] = useState(canLoad);\n useEffect(() => {\n if (!canLoad) return;\n if (!cachedServerClientConfigPromise) {\n cachedServerClientConfigPromise = fetchClientConfigFromServer();\n }\n void cachedServerClientConfigPromise\n .then((newConfig) => {\n if (newConfig) {\n setClientConfig((prevConfig) => {\n return prevConfig.isEqual(newConfig) ? prevConfig : newConfig;\n });\n }\n })\n .finally(() => {\n setIsLoading(false);\n });\n }, [canLoad]);\n\n return { clientConfig, isLoading };\n}\n\nexport function resetCachedServerClientConfigPromise(): void {\n cachedServerClientConfigPromise = null;\n}\n","import { pathToRegexp } from 'path-to-regexp';\nimport type { ClientConfig } from './types';\n\nexport interface MicrofrontendConfigClientOptions {\n removeFlaggedPaths?: boolean;\n}\n\nconst regexpCache = new Map<string, RegExp>();\nconst getRegexp = (path: string): RegExp => {\n const existing = regexpCache.get(path);\n if (existing) {\n return existing;\n }\n\n const regexp = pathToRegexp(path);\n regexpCache.set(path, regexp);\n return regexp;\n};\n\nexport class MicrofrontendConfigClient {\n applications: ClientConfig['applications'];\n hasFlaggedPaths: boolean;\n pathCache: Record<string, string> = {};\n private readonly serialized: ClientConfig;\n\n constructor(config: ClientConfig, opts?: MicrofrontendConfigClientOptions) {\n this.hasFlaggedPaths = config.hasFlaggedPaths ?? false;\n for (const app of Object.values(config.applications)) {\n if (app.routing) {\n if (app.routing.some((match) => match.flag)) {\n this.hasFlaggedPaths = true;\n }\n const newRouting = [];\n const pathsWithoutFlags = [];\n for (const group of app.routing) {\n if (group.flag) {\n if (opts?.removeFlaggedPaths) {\n continue;\n }\n if (group.group) {\n delete group.group;\n }\n newRouting.push(group);\n } else {\n pathsWithoutFlags.push(...group.paths);\n }\n }\n if (pathsWithoutFlags.length > 0) {\n newRouting.push({ paths: pathsWithoutFlags });\n }\n app.routing = newRouting;\n }\n }\n this.serialized = config;\n if (this.hasFlaggedPaths) {\n this.serialized.hasFlaggedPaths = this.hasFlaggedPaths;\n }\n this.applications = config.applications;\n }\n\n /**\n * Create a new `MicrofrontendConfigClient` from a JSON string.\n * Config must be passed in to remain framework agnostic\n */\n static fromEnv(config: string | undefined): MicrofrontendConfigClient {\n if (!config) {\n throw new Error(\n 'Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`? Is the local proxy running and this application is being accessed via the proxy port? See https://vercel.com/docs/microfrontends/local-development#setting-up-microfrontends-proxy',\n );\n }\n return new MicrofrontendConfigClient(JSON.parse(config) as ClientConfig);\n }\n\n isEqual(other: MicrofrontendConfigClient): boolean {\n return (\n this === other ||\n JSON.stringify(this.applications) === JSON.stringify(other.applications)\n );\n }\n\n getApplicationNameForPath(path: string): string | null {\n if (!path.startsWith('/')) {\n throw new Error(`Path must start with a /`);\n }\n\n if (this.pathCache[path]) {\n return this.pathCache[path];\n }\n\n const pathname = new URL(path, 'https://example.com').pathname;\n for (const [name, application] of Object.entries(this.applications)) {\n if (application.routing) {\n for (const group of application.routing) {\n for (const childPath of group.paths) {\n const regexp = getRegexp(childPath);\n if (regexp.test(pathname)) {\n this.pathCache[path] = name;\n return name;\n }\n }\n }\n }\n }\n const defaultApplication = Object.entries(this.applications).find(\n ([, application]) => application.default,\n );\n if (!defaultApplication) {\n return null;\n }\n\n this.pathCache[path] = defaultApplication[0];\n return defaultApplication[0];\n }\n\n serialize(): ClientConfig {\n return this.serialized;\n }\n}\n","import Script from 'next/script.js';\nimport { useEffect, useState } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\n\nconst PREFETCH_ATTR = 'data-prefetch';\nconst DATA_ATTR_SELECTORS = {\n anyZone: '[data-zone]',\n external: '[data-zone=\"null\"]',\n sameZone: '[data-zone=\"same\"]',\n prefetch: `[${PREFETCH_ATTR}]`,\n} as const;\n\nconst PREFETCH_ON_HOVER_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n ],\n};\n\nconst PREFETCH_WHEN_VISIBLE_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n { selector_matches: DATA_ATTR_SELECTORS.prefetch },\n ],\n};\n\nfunction checkVisibility(element: Element | null): boolean {\n if (!element) return true;\n\n if ('checkVisibility' in element) {\n return element.checkVisibility({ opacityProperty: true });\n }\n\n // hack to get around TS thinking element is never;\n const el = element as Element;\n const style = window.getComputedStyle(el);\n\n if (\n style.display === 'none' ||\n style.visibility === 'hidden' ||\n style.opacity === '0'\n ) {\n return false;\n }\n\n return checkVisibility(el.parentElement);\n}\n\ninterface PrefetchCrossZoneLinksProps {\n /**\n * This attributes controls how eager the browser should be in prerendering\n * cross-zone links. Prerendering downloads the HTML and subresources of the page\n * and starts to render the page in the background. This consumes more resources\n * but provides a faster user experience if the user decides to visit that page.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/speculationrules#eagerness\n * for more information.\n *\n * Default value is 'conservative'.\n */\n prerenderEagerness?: 'immediate' | 'eager' | 'moderate' | 'conservative';\n}\n\nexport function PrefetchCrossZoneLinks({\n prerenderEagerness = 'conservative',\n}: PrefetchCrossZoneLinksProps): JSX.Element | null {\n const { isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const [links, setLinks] = useState<HTMLAnchorElement[]>([]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Intersection observer to add the data-prefetch attribute to cross-zone\n * links that have yet to be prefetched and are visible.\n */\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n if (\n entry.isIntersecting &&\n !entry.target.hasAttribute(PREFETCH_ATTR) &&\n // lazy perform the visibility check for nodes that are intersecting the viewport\n // and have not been prefetched.\n checkVisibility(entry.target)\n ) {\n entry.target.setAttribute(PREFETCH_ATTR, 'true');\n }\n });\n },\n {\n root: null,\n rootMargin: '0px',\n threshold: 0.1,\n },\n );\n\n links.forEach((link) => observer.observe(link));\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading, links]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Mutation observer to notify when new nodes have entered/exited the document\n * or an href has changed.\n */\n const observer = new MutationObserver((mutations) => {\n const hasChanged = mutations.some((mutation) => {\n return (\n (mutation.type === 'childList' && mutation.addedNodes.length > 0) ||\n (mutation.type === 'attributes' && mutation.attributeName === 'href')\n );\n });\n\n if (hasChanged) {\n // Whenever there's a change, add all cross-zone links that haven't been\n // prefetched.\n setLinks(\n Array.from(\n document.querySelectorAll<HTMLAnchorElement>(\n `a${DATA_ATTR_SELECTORS.anyZone}:not(${DATA_ATTR_SELECTORS.prefetch}):not(${DATA_ATTR_SELECTORS.sameZone}):not(${DATA_ATTR_SELECTORS.external})`,\n ),\n ),\n );\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['href'],\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading]);\n\n // Wait till the zone-config loads to take into consideration any\n // flagged routes.\n if (isLoading) {\n return null;\n }\n\n // Prefetch links with moderate eagerness by default, immediately when marked \"data-prefetch\".\n // Prerender links with conservative eagerness by default, immediately when marked \"data-prefetch\".\n const speculationRules = {\n prefetch: [\n {\n eagerness: 'moderate',\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n {\n eagerness: 'immediate',\n where: PREFETCH_WHEN_VISIBLE_PREDICATES,\n },\n ],\n prerender: [\n {\n eagerness: prerenderEagerness,\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n ],\n };\n\n return (\n <Script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Safe - injecting JSON speculation rules, not HTML\n dangerouslySetInnerHTML={{\n __html: JSON.stringify(speculationRules),\n }}\n id=\"prefetch-zones-links\"\n type=\"speculationrules\"\n />\n );\n}\n","import type React from 'react';\nimport {\n createContext,\n startTransition,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nexport interface PrefetchCrossZoneLinksContext {\n prefetchHref: (href: string) => void;\n}\n\nexport const PrefetchCrossZoneLinksContext =\n createContext<PrefetchCrossZoneLinksContext>({\n prefetchHref: () => {},\n });\n\nexport function PrefetchCrossZoneLinksProvider({\n children,\n}: {\n children: React.ReactNode;\n}): JSX.Element | null {\n const [seenHrefs, setSeenHrefs] = useState(new Set<string>());\n const isSafariOrFirefox = useRef(\n typeof navigator !== 'undefined' &&\n (navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome'))),\n );\n\n // This useCallback must not have any dependencies because if it changes\n // its value, every component that uses this context will rerender.\n const prefetchHref = useCallback((href: string): void => {\n // It's not critical that we render the new preload `<link>` elements\n // immediately. We want to batch together `prefetchHref` calls that\n // occur in one synchronous pass and only render once after they've all\n // called this callback.\n startTransition(() => {\n setSeenHrefs((prevHrefs) => {\n if (prevHrefs.has(href)) return prevHrefs;\n return new Set(prevHrefs).add(href);\n });\n });\n }, []);\n\n const value = useMemo(() => ({ prefetchHref }), [prefetchHref]);\n\n if (!isSafariOrFirefox.current) {\n return <>{children}</>;\n }\n\n return (\n <PrefetchCrossZoneLinksContext.Provider value={value}>\n {children}\n {[...seenHrefs].map((href) => (\n <link as=\"fetch\" href={href} key={href} rel=\"preload\" />\n ))}\n </PrefetchCrossZoneLinksContext.Provider>\n );\n}\n"],"mappings":";0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,2BAAAC,EAAA,kCAAAC,EAAA,mCAAAC,EAAA,mBAAAC,IAAA,eAAAC,EAAAP,GCAA,IAAAQ,EAEO,6BAEPC,EAAgD,iBCFhD,IAAAC,EAA6C,iBCF7C,IAAAC,EAA6B,0BAOvBC,EAAc,IAAI,IAClBC,EAAaC,GAAyB,CAC1C,IAAMC,EAAWH,EAAY,IAAIE,CAAI,EACrC,GAAIC,EACF,OAAOA,EAGT,IAAMC,KAAS,gBAAaF,CAAI,EAChC,OAAAF,EAAY,IAAIE,EAAME,CAAM,EACrBA,CACT,EAEaC,EAAN,KAAgC,CAMrC,YAAYC,EAAsBC,EAAyC,CAH3E,eAAoC,CAAC,EAInC,KAAK,gBAAkBD,EAAO,iBAAmB,GACjD,QAAWE,KAAO,OAAO,OAAOF,EAAO,YAAY,EACjD,GAAIE,EAAI,QAAS,CACXA,EAAI,QAAQ,KAAMC,GAAUA,EAAM,IAAI,IACxC,KAAK,gBAAkB,IAEzB,IAAMC,EAAa,CAAC,EACdC,EAAoB,CAAC,EAC3B,QAAWC,KAASJ,EAAI,QACtB,GAAII,EAAM,KAAM,CACd,GAAIL,GAAM,mBACR,SAEEK,EAAM,OACR,OAAOA,EAAM,MAEfF,EAAW,KAAKE,CAAK,OAErBD,EAAkB,KAAK,GAAGC,EAAM,KAAK,EAGrCD,EAAkB,OAAS,GAC7BD,EAAW,KAAK,CAAE,MAAOC,CAAkB,CAAC,EAE9CH,EAAI,QAAUE,EAGlB,KAAK,WAAaJ,EACd,KAAK,kBACP,KAAK,WAAW,gBAAkB,KAAK,iBAEzC,KAAK,aAAeA,EAAO,YAC7B,CAMA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ACjC,SACE,OAAC,KACE,GAAGO,EACJ,YAAWX,EACX,QAASI,EAAM,WAAa,GAAQK,EAAkB,OACtD,YAAaL,EAAM,WAAa,GAAQK,EAAkB,OAEzD,SAAAN,EACH,EAIJ,SACE,OAAC,EAAAS,QAAA,CACE,GAAGR,EACJ,YAAYJ,EAAsB,OAAT,OACzB,SAAUI,EAAM,WAAaP,EAAY,GAAQ,QACjD,IAAKQ,EAEJ,SAAAF,EACH,CAEJ,CACF,EACAD,EAAK,YAAc","names":["client_exports","__export","Link","PrefetchCrossZoneLinks","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","useZoneForHref","__toCommonJS","import_link","import_react","import_react","import_path_to_regexp","regexpCache","getRegexp","path","existing","regexp","MicrofrontendConfigClient","config","opts","app","match","newRouting","pathsWithoutFlags","group","other","pathname","name","application","childPath","defaultApplication","clientCache","cachedHasDynamicPaths","getClient","config","existing","client","MicrofrontendConfigClient","cachedServerClientConfigPromise","cachedServerClient","fetchClientConfigFromServer","response","responseJson","useClientConfig","clientConfig","setClientConfig","canLoad","hasDynamicPaths","isLoading","setIsLoading","newConfig","prevConfig","import_script","import_react","import_jsx_runtime","PREFETCH_ATTR","DATA_ATTR_SELECTORS","PREFETCH_ON_HOVER_PREDICATES","PREFETCH_WHEN_VISIBLE_PREDICATES","checkVisibility","element","el","style","PrefetchCrossZoneLinks","prerenderEagerness","isLoading","useClientConfig","links","setLinks","observer","entries","entry","link","mutations","mutation","Script","import_react","import_jsx_runtime","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","children","seenHrefs","setSeenHrefs","isSafariOrFirefox","prefetchHref","href","prevHrefs","value","import_jsx_runtime","CURRENT_ZONE_HASH","useZoneForHref","href","clientConfig","isLoading","useClientConfig","isRelativePath","zoneOfHref","isRelative","Link","children","props","ref","prefetchHref","PrefetchCrossZoneLinksContext","isDifferentZone","onHoverPrefetch","_","rest","NextLink"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/client/index.ts","../../src/next/client/link/microfrontends-link.tsx","../../src/config/react/use-client-config.ts","../../src/config/microfrontends-config/client/index.ts","../../src/next/client/prefetch/prefetch-cross-zone-links.tsx","../../src/next/client/prefetch/prefetch-cross-zone-links-context.tsx"],"sourcesContent":["export * from './link';\nexport * from './prefetch';\n","import NextLink, {\n type LinkProps as ExternalNextLinkProps,\n} from 'next/link.js';\nimport type { AnchorHTMLAttributes } from 'react';\nimport { forwardRef, useContext, useMemo } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\nimport { PrefetchCrossZoneLinksContext } from '../prefetch';\n\ninterface BaseProps {\n children: React.ReactNode;\n href: string;\n}\n\n// fix for tsc inlining LinkProps from next\n// https://github.com/microsoft/TypeScript/issues/37151#issuecomment-756232934\ninterface NextLinkProps extends ExternalNextLinkProps {}\nexport type LinkProps = BaseProps &\n Omit<NextLinkProps, keyof BaseProps> &\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof BaseProps>;\n\nconst CURRENT_ZONE_HASH = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION_HASH;\n\nexport function useZoneForHref(href: LinkProps['href'] | undefined): {\n zoneOfHref: string | null;\n isDifferentZone: boolean;\n isLoading: boolean;\n} {\n const { clientConfig, isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const { isRelativePath, zoneOfHref } = useMemo(() => {\n const isRelative = typeof href === 'string' && href.startsWith('/');\n return {\n isRelativePath: isRelative,\n zoneOfHref: isRelative\n ? clientConfig.getApplicationNameForPath(href)\n : null,\n };\n }, [clientConfig, href]);\n\n if (typeof href === 'string' && !href.length) {\n return {\n zoneOfHref: null,\n isDifferentZone: false,\n isLoading: false,\n };\n }\n const isDifferentZone =\n !isRelativePath || (zoneOfHref ? CURRENT_ZONE_HASH !== zoneOfHref : false);\n return { zoneOfHref, isDifferentZone, isLoading };\n}\n\n/**\n * A Link component that works with microfrontend set-ups and will prefetch the\n * cross zone links automatically.\n */\nexport const Link = forwardRef<HTMLAnchorElement, LinkProps>(\n ({ children, ...props }, ref): JSX.Element => {\n const { prefetchHref } = useContext(PrefetchCrossZoneLinksContext);\n const { zoneOfHref, isDifferentZone, isLoading } = useZoneForHref(\n props.href,\n );\n\n function onHoverPrefetch(): void {\n if (!props.href) {\n return;\n }\n prefetchHref(props.href);\n }\n\n if (isDifferentZone && zoneOfHref !== null) {\n const { prefetch: _, ...rest } = props;\n return (\n <a\n {...rest}\n data-zone={zoneOfHref}\n onFocus={props.prefetch !== false ? onHoverPrefetch : undefined}\n onMouseOver={props.prefetch !== false ? onHoverPrefetch : undefined}\n >\n {children}\n </a>\n );\n }\n\n return (\n <NextLink\n {...props}\n data-zone={!zoneOfHref ? 'null' : 'same'}\n prefetch={props.prefetch ?? (isLoading ? false : undefined)}\n ref={ref}\n >\n {children}\n </NextLink>\n );\n },\n);\nLink.displayName = 'MicrofrontendsLink';\n","'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { MicrofrontendConfigClient } from '../microfrontends-config/client';\nimport type { WellKnownClientData } from '../well-known/types';\n\nconst clientCache = new Map<string, MicrofrontendConfigClient>();\nconst cachedHasDynamicPaths = new Map<string, boolean>();\n\nconst getClient = (config: string | undefined) => {\n const existing = clientCache.get(config || '');\n if (existing) {\n return existing;\n }\n\n const client = MicrofrontendConfigClient.fromEnv(config);\n clientCache.set(config || '', client);\n return client;\n};\n\nlet cachedServerClientConfigPromise: Promise<MicrofrontendConfigClient | null> | null =\n null;\n\nlet cachedServerClient: MicrofrontendConfigClient | null = null;\n\nasync function fetchClientConfigFromServer(): Promise<MicrofrontendConfigClient | null> {\n try {\n const response = await fetch(\n '/.well-known/vercel/microfrontends/client-config',\n );\n if (response.status !== 200) {\n return null;\n }\n const responseJson = (await response.json()) as WellKnownClientData;\n const client = new MicrofrontendConfigClient(responseJson.config);\n cachedServerClient = client;\n return client;\n } catch {\n return null;\n }\n}\n\n/**\n * Hook to use the client microfrontends configuration. This hook will resolve\n * dynamic paths by fetching the configuration from the server if necessary,\n * allowing the server to specify the values for dynamic paths.\n */\nexport function useClientConfig(config: string | undefined): {\n clientConfig: MicrofrontendConfigClient;\n isLoading: boolean;\n} {\n const [clientConfig, setClientConfig] = useState<MicrofrontendConfigClient>(\n () => cachedServerClient ?? getClient(config),\n );\n const canLoad = useMemo(() => {\n if (\n process.env.NODE_ENV === 'test' &&\n process.env.MFE_FORCE_CLIENT_CONFIG_FROM_SERVER !== '1'\n ) {\n return false;\n }\n // If we've already fetched the server config and it's resolved, we don't need\n // to enter the loading state at all\n if (cachedServerClient) return false;\n // If we've already checked this config for dynamic paths, we can use the\n // cached result from before instead of reevaluating.\n const existing = cachedHasDynamicPaths.get(config || '');\n if (existing !== undefined) return existing;\n // Get the original client config to determine if the config has any\n // dynamic paths.\n const originalClientConfig = getClient(config);\n // As an optimization, only fetch the config from the server if the\n // microfrontends configuration has any dynamic paths. If it doesn't,\n // then the server won't return any different values.\n const hasDynamicPaths = originalClientConfig.hasFlaggedPaths;\n cachedHasDynamicPaths.set(config || '', hasDynamicPaths);\n if (!hasDynamicPaths) {\n return false;\n }\n return true;\n }, [config]);\n const [isLoading, setIsLoading] = useState(canLoad);\n useEffect(() => {\n if (!canLoad) return;\n if (!cachedServerClientConfigPromise) {\n cachedServerClientConfigPromise = fetchClientConfigFromServer();\n }\n void cachedServerClientConfigPromise\n .then((newConfig) => {\n if (newConfig) {\n setClientConfig((prevConfig) => {\n return prevConfig.isEqual(newConfig) ? prevConfig : newConfig;\n });\n }\n })\n .finally(() => {\n setIsLoading(false);\n });\n }, [canLoad]);\n\n return { clientConfig, isLoading };\n}\n\nexport function resetCachedServerClientConfigPromise(): void {\n cachedServerClientConfigPromise = null;\n}\n","import { pathToRegexp } from 'path-to-regexp';\nimport type { ClientConfig } from './types';\n\nexport interface MicrofrontendConfigClientOptions {\n removeFlaggedPaths?: boolean;\n}\n\nconst regexpCache = new Map<string, RegExp>();\nconst getRegexp = (path: string): RegExp => {\n const existing = regexpCache.get(path);\n if (existing) {\n return existing;\n }\n\n const regexp = pathToRegexp(path);\n regexpCache.set(path, regexp);\n return regexp;\n};\n\nexport class MicrofrontendConfigClient {\n applications: ClientConfig['applications'];\n hasFlaggedPaths: boolean;\n pathCache: Record<string, string> = {};\n private readonly serialized: ClientConfig;\n\n constructor(config: ClientConfig, opts?: MicrofrontendConfigClientOptions) {\n this.hasFlaggedPaths = config.hasFlaggedPaths ?? false;\n for (const app of Object.values(config.applications)) {\n if (app.routing) {\n if (app.routing.some((match) => match.flag)) {\n this.hasFlaggedPaths = true;\n }\n const newRouting = [];\n const pathsWithoutFlags = [];\n for (const group of app.routing) {\n if (group.flag) {\n if (opts?.removeFlaggedPaths) {\n continue;\n }\n if (group.group) {\n delete group.group;\n }\n newRouting.push(group);\n } else {\n pathsWithoutFlags.push(...group.paths);\n }\n }\n if (pathsWithoutFlags.length > 0) {\n newRouting.push({ paths: pathsWithoutFlags });\n }\n app.routing = newRouting;\n }\n }\n this.serialized = config;\n if (this.hasFlaggedPaths) {\n this.serialized.hasFlaggedPaths = this.hasFlaggedPaths;\n }\n this.applications = config.applications;\n }\n\n /**\n * Create a new `MicrofrontendConfigClient` from a JSON string.\n * Config must be passed in to remain framework agnostic\n */\n static fromEnv(config: string | undefined): MicrofrontendConfigClient {\n if (!config) {\n throw new Error(\n 'Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`? Is the local proxy running and this application is being accessed via the proxy port? See https://vercel.com/docs/microfrontends/local-development#setting-up-microfrontends-proxy',\n );\n }\n return new MicrofrontendConfigClient(JSON.parse(config) as ClientConfig);\n }\n\n isEqual(other: MicrofrontendConfigClient): boolean {\n return (\n this === other ||\n JSON.stringify(this.applications) === JSON.stringify(other.applications)\n );\n }\n\n getApplicationNameForPath(path: string): string | null {\n if (!path.startsWith('/')) {\n throw new Error(`Path must start with a /`);\n }\n\n if (this.pathCache[path]) {\n return this.pathCache[path];\n }\n\n const pathname = new URL(path, 'https://example.com').pathname;\n for (const [name, application] of Object.entries(this.applications)) {\n if (application.routing) {\n for (const group of application.routing) {\n for (const childPath of group.paths) {\n const regexp = getRegexp(childPath);\n if (regexp.test(pathname)) {\n this.pathCache[path] = name;\n return name;\n }\n }\n }\n }\n }\n const defaultApplication = Object.entries(this.applications).find(\n ([, application]) => application.default,\n );\n if (!defaultApplication) {\n return null;\n }\n\n this.pathCache[path] = defaultApplication[0];\n return defaultApplication[0];\n }\n\n serialize(): ClientConfig {\n return this.serialized;\n }\n}\n","import Script from 'next/script.js';\nimport { useEffect, useState } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\n\nconst PREFETCH_ATTR = 'data-prefetch';\nconst DATA_ATTR_SELECTORS = {\n anyZone: '[data-zone]',\n external: '[data-zone=\"null\"]',\n sameZone: '[data-zone=\"same\"]',\n prefetch: `[${PREFETCH_ATTR}]`,\n} as const;\n\nconst PREFETCH_ON_HOVER_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n ],\n};\n\nconst PREFETCH_WHEN_VISIBLE_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n { selector_matches: DATA_ATTR_SELECTORS.prefetch },\n ],\n};\n\nfunction checkVisibility(element: Element | null): boolean {\n if (!element) return true;\n\n if ('checkVisibility' in element) {\n return element.checkVisibility({ opacityProperty: true });\n }\n\n // hack to get around TS thinking element is never;\n const el = element as Element;\n const style = window.getComputedStyle(el);\n\n if (\n style.display === 'none' ||\n style.visibility === 'hidden' ||\n style.opacity === '0'\n ) {\n return false;\n }\n\n return checkVisibility(el.parentElement);\n}\n\ninterface PrefetchCrossZoneLinksProps {\n /**\n * This attributes controls how eager the browser should be in prerendering\n * cross-zone links. Prerendering downloads the HTML and subresources of the page\n * and starts to render the page in the background. This consumes more resources\n * but provides a faster user experience if the user decides to visit that page.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/speculationrules#eagerness\n * for more information.\n *\n * Default value is 'conservative'.\n */\n prerenderEagerness?: 'immediate' | 'eager' | 'moderate' | 'conservative';\n}\n\nexport function PrefetchCrossZoneLinks({\n prerenderEagerness = 'conservative',\n}: PrefetchCrossZoneLinksProps): JSX.Element | null {\n const { isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const [links, setLinks] = useState<HTMLAnchorElement[]>([]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Intersection observer to add the data-prefetch attribute to cross-zone\n * links that have yet to be prefetched and are visible.\n */\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n if (\n entry.isIntersecting &&\n !entry.target.hasAttribute(PREFETCH_ATTR) &&\n // lazy perform the visibility check for nodes that are intersecting the viewport\n // and have not been prefetched.\n checkVisibility(entry.target)\n ) {\n entry.target.setAttribute(PREFETCH_ATTR, 'true');\n }\n });\n },\n {\n root: null,\n rootMargin: '0px',\n threshold: 0.1,\n },\n );\n\n links.forEach((link) => observer.observe(link));\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading, links]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Mutation observer to notify when new nodes have entered/exited the document\n * or an href has changed.\n */\n const observer = new MutationObserver((mutations) => {\n const hasChanged = mutations.some((mutation) => {\n return (\n (mutation.type === 'childList' && mutation.addedNodes.length > 0) ||\n (mutation.type === 'attributes' && mutation.attributeName === 'href')\n );\n });\n\n if (hasChanged) {\n // Whenever there's a change, add all cross-zone links that haven't been\n // prefetched.\n setLinks(\n Array.from(\n document.querySelectorAll<HTMLAnchorElement>(\n `a${DATA_ATTR_SELECTORS.anyZone}:not(${DATA_ATTR_SELECTORS.prefetch}):not(${DATA_ATTR_SELECTORS.sameZone}):not(${DATA_ATTR_SELECTORS.external})`,\n ),\n ),\n );\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['href'],\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading]);\n\n // Wait till the zone-config loads to take into consideration any\n // flagged routes.\n if (isLoading) {\n return null;\n }\n\n // Prefetch links with moderate eagerness by default, immediately when marked \"data-prefetch\".\n // Prerender links with conservative eagerness by default, immediately when marked \"data-prefetch\".\n const speculationRules = {\n prefetch: [\n {\n eagerness: 'moderate',\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n {\n eagerness: 'immediate',\n where: PREFETCH_WHEN_VISIBLE_PREDICATES,\n },\n ],\n prerender: [\n {\n eagerness: prerenderEagerness,\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n ],\n };\n\n return (\n <Script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Safe - injecting JSON speculation rules, not HTML\n dangerouslySetInnerHTML={{\n __html: JSON.stringify(speculationRules),\n }}\n id=\"prefetch-zones-links\"\n type=\"speculationrules\"\n />\n );\n}\n","import type React from 'react';\nimport {\n createContext,\n startTransition,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nexport interface PrefetchCrossZoneLinksContext {\n prefetchHref: (href: string) => void;\n}\n\nexport const PrefetchCrossZoneLinksContext =\n createContext<PrefetchCrossZoneLinksContext>({\n prefetchHref: () => {},\n });\n\nexport function PrefetchCrossZoneLinksProvider({\n children,\n}: {\n children: React.ReactNode;\n}): JSX.Element | null {\n const [seenHrefs, setSeenHrefs] = useState(new Set<string>());\n const isSafariOrFirefox = useRef(\n typeof navigator !== 'undefined' &&\n (navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome'))),\n );\n\n // This useCallback must not have any dependencies because if it changes\n // its value, every component that uses this context will rerender.\n const prefetchHref = useCallback((href: string): void => {\n // It's not critical that we render the new preload `<link>` elements\n // immediately. We want to batch together `prefetchHref` calls that\n // occur in one synchronous pass and only render once after they've all\n // called this callback.\n startTransition(() => {\n setSeenHrefs((prevHrefs) => {\n if (prevHrefs.has(href)) return prevHrefs;\n return new Set(prevHrefs).add(href);\n });\n });\n }, []);\n\n const value = useMemo(() => ({ prefetchHref }), [prefetchHref]);\n\n if (!isSafariOrFirefox.current) {\n return <>{children}</>;\n }\n\n return (\n <PrefetchCrossZoneLinksContext.Provider value={value}>\n {children}\n {[...seenHrefs].map((href) => (\n <link as=\"fetch\" href={href} key={href} rel=\"preload\" />\n ))}\n </PrefetchCrossZoneLinksContext.Provider>\n );\n}\n"],"mappings":";0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,2BAAAC,EAAA,kCAAAC,EAAA,mCAAAC,EAAA,mBAAAC,IAAA,eAAAC,EAAAP,GCAA,IAAAQ,EAEO,6BAEPC,EAAgD,iBCFhD,IAAAC,EAA6C,iBCF7C,IAAAC,EAA6B,0BAOvBC,EAAc,IAAI,IAClBC,EAAaC,GAAyB,CAC1C,IAAMC,EAAWH,EAAY,IAAIE,CAAI,EACrC,GAAIC,EACF,OAAOA,EAGT,IAAMC,KAAS,gBAAaF,CAAI,EAChC,OAAAF,EAAY,IAAIE,EAAME,CAAM,EACrBA,CACT,EAEaC,EAAN,KAAgC,CAMrC,YAAYC,EAAsBC,EAAyC,CAH3E,eAAoC,CAAC,EAInC,KAAK,gBAAkBD,EAAO,iBAAmB,GACjD,QAAWE,KAAO,OAAO,OAAOF,EAAO,YAAY,EACjD,GAAIE,EAAI,QAAS,CACXA,EAAI,QAAQ,KAAMC,GAAUA,EAAM,IAAI,IACxC,KAAK,gBAAkB,IAEzB,IAAMC,EAAa,CAAC,EACdC,EAAoB,CAAC,EAC3B,QAAWC,KAASJ,EAAI,QACtB,GAAII,EAAM,KAAM,CACd,GAAIL,GAAM,mBACR,SAEEK,E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5C,GAAM,CAAE,aAAAC,CAAa,KAAI,cAAWC,CAA6B,EAC3D,CAAE,WAAAP,EAAY,gBAAAQ,EAAiB,UAAAX,CAAU,EAAIH,EACjDU,EAAM,IACR,EAEA,SAASK,GAAwB,CAC1BL,EAAM,MAGXE,EAAaF,EAAM,IAAI,CACzB,CAEA,GAAII,GAAmBR,IAAe,KAAM,CAC1C,GAAM,CAAE,SAAUU,EAAG,GAAGC,CAAK,EAAIP,EACjC,SACE,OAAC,KACE,GAAGO,EACJ,YAAWX,EACX,QAASI,EAAM,WAAa,GAAQK,EAAkB,OACtD,YAAaL,EAAM,WAAa,GAAQK,EAAkB,OAEzD,SAAAN,EACH,EAIJ,SACE,OAAC,EAAAS,QAAA,CACE,GAAGR,EACJ,YAAYJ,EAAsB,OAAT,OACzB,SAAUI,EAAM,WAAaP,EAAY,GAAQ,QACjD,IAAKQ,EAEJ,SAAAF,EACH,CAEJ,CACF,EACAD,EAAK,YAAc","names":["client_exports","__export","Link","PrefetchCrossZoneLinks","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","useZoneForHref","__toCommonJS","import_link","import_react","import_react","import_path_to_regexp","regexpCache","getRegexp","path","existing","regexp","MicrofrontendConfigClient","config","opts","app","match","newRouting","pathsWithoutFlags","group","other","pathname","name","application","childPath","defaultApplication","clientCache","cachedHasDynamicPaths","getClient","config","existing","client","MicrofrontendConfigClient","cachedServerClientConfigPromise","cachedServerClient","fetchClientConfigFromServer","response","responseJson","useClientConfig","clientConfig","setClientConfig","canLoad","hasDynamicPaths","isLoading","setIsLoading","newConfig","prevConfig","import_script","import_react","import_jsx_runtime","PREFETCH_ATTR","DATA_ATTR_SELECTORS","PREFETCH_ON_HOVER_PREDICATES","PREFETCH_WHEN_VISIBLE_PREDICATES","checkVisibility","element","el","style","PrefetchCrossZoneLinks","prerenderEagerness","isLoading","useClientConfig","links","setLinks","observer","entries","entry","link","mutations","mutation","Script","import_react","import_jsx_runtime","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","children","seenHrefs","setSeenHrefs","isSafariOrFirefox","prefetchHref","href","prevHrefs","value","import_jsx_runtime","CURRENT_ZONE_HASH","useZoneForHref","href","clientConfig","isLoading","useClientConfig","isRelativePath","zoneOfHref","isRelative","Link","children","props","ref","prefetchHref","PrefetchCrossZoneLinksContext","isDifferentZone","onHoverPrefetch","_","rest","NextLink"]}
|
package/dist/next/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/client/link/microfrontends-link.tsx","../../src/config/react/use-client-config.ts","../../src/config/microfrontends-config/client/index.ts","../../src/next/client/prefetch/prefetch-cross-zone-links.tsx","../../src/next/client/prefetch/prefetch-cross-zone-links-context.tsx"],"sourcesContent":["import NextLink, {\n type LinkProps as ExternalNextLinkProps,\n} from 'next/link.js';\nimport type { AnchorHTMLAttributes } from 'react';\nimport { forwardRef, useContext, useMemo } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\nimport { PrefetchCrossZoneLinksContext } from '../prefetch';\n\ninterface BaseProps {\n children: React.ReactNode;\n href: string;\n}\n\n// fix for tsc inlining LinkProps from next\n// https://github.com/microsoft/TypeScript/issues/37151#issuecomment-756232934\ninterface NextLinkProps extends ExternalNextLinkProps {}\nexport type LinkProps = BaseProps &\n Omit<NextLinkProps, keyof BaseProps> &\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof BaseProps>;\n\nconst CURRENT_ZONE_HASH = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION_HASH;\n\nexport function useZoneForHref(href: LinkProps['href'] | undefined): {\n zoneOfHref: string | null;\n isDifferentZone: boolean;\n isLoading: boolean;\n} {\n const { clientConfig, isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const { isRelativePath, zoneOfHref } = useMemo(() => {\n const isRelative = typeof href === 'string' && href.startsWith('/');\n return {\n isRelativePath: isRelative,\n zoneOfHref: isRelative\n ? clientConfig.getApplicationNameForPath(href)\n : null,\n };\n }, [clientConfig, href]);\n\n if (typeof href === 'string' && !href.length) {\n return {\n zoneOfHref: null,\n isDifferentZone: false,\n isLoading: false,\n };\n }\n const isDifferentZone =\n !isRelativePath || (zoneOfHref ? CURRENT_ZONE_HASH !== zoneOfHref : false);\n return { zoneOfHref, isDifferentZone, isLoading };\n}\n\n/**\n * A Link component that works with microfrontend set-ups and will prefetch the\n * cross zone links automatically.\n */\nexport const Link = forwardRef<HTMLAnchorElement, LinkProps>(\n ({ children, ...props }, ref): JSX.Element => {\n const { prefetchHref } = useContext(PrefetchCrossZoneLinksContext);\n const { zoneOfHref, isDifferentZone, isLoading } = useZoneForHref(\n props.href,\n );\n\n function onHoverPrefetch(): void {\n if (!props.href) {\n return;\n }\n prefetchHref(props.href);\n }\n\n if (isDifferentZone && zoneOfHref !== null) {\n const { prefetch: _, ...rest } = props;\n return (\n <a\n {...rest}\n data-zone={zoneOfHref}\n onFocus={props.prefetch !== false ? onHoverPrefetch : undefined}\n onMouseOver={props.prefetch !== false ? onHoverPrefetch : undefined}\n >\n {children}\n </a>\n );\n }\n\n return (\n <NextLink\n {...props}\n data-zone={!zoneOfHref ? 'null' : 'same'}\n prefetch={props.prefetch ?? (isLoading ? false : undefined)}\n ref={ref}\n >\n {children}\n </NextLink>\n );\n },\n);\nLink.displayName = 'MicrofrontendsLink';\n","'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { MicrofrontendConfigClient } from '../microfrontends-config/client';\nimport type { WellKnownClientData } from '../well-known/types';\n\nconst clientCache = new Map<string, MicrofrontendConfigClient>();\nconst cachedHasDynamicPaths = new Map<string, boolean>();\n\nconst getClient = (config: string | undefined) => {\n const existing = clientCache.get(config || '');\n if (existing) {\n return existing;\n }\n\n const client = MicrofrontendConfigClient.fromEnv(config);\n clientCache.set(config || '', client);\n return client;\n};\n\nlet cachedServerClientConfigPromise: Promise<MicrofrontendConfigClient | null> | null =\n null;\n\nlet cachedServerClient: MicrofrontendConfigClient | null = null;\n\nasync function fetchClientConfigFromServer(): Promise<MicrofrontendConfigClient | null> {\n try {\n const response = await fetch(\n '/.well-known/vercel/microfrontends/client-config',\n );\n if (response.status !== 200) {\n return null;\n }\n const responseJson = (await response.json()) as WellKnownClientData;\n const client = new MicrofrontendConfigClient(responseJson.config);\n cachedServerClient = client;\n return client;\n } catch (err) {\n return null;\n }\n}\n\n/**\n * Hook to use the client microfrontends configuration. This hook will resolve\n * dynamic paths by fetching the configuration from the server if necessary,\n * allowing the server to specify the values for dynamic paths.\n */\nexport function useClientConfig(config: string | undefined): {\n clientConfig: MicrofrontendConfigClient;\n isLoading: boolean;\n} {\n const [clientConfig, setClientConfig] = useState<MicrofrontendConfigClient>(\n () => cachedServerClient ?? getClient(config),\n );\n const canLoad = useMemo(() => {\n if (\n process.env.NODE_ENV === 'test' &&\n process.env.MFE_FORCE_CLIENT_CONFIG_FROM_SERVER !== '1'\n ) {\n return false;\n }\n // If we've already fetched the server config and it's resolved, we don't need\n // to enter the loading state at all\n if (cachedServerClient) return false;\n // If we've already checked this config for dynamic paths, we can use the\n // cached result from before instead of reevaluating.\n const existing = cachedHasDynamicPaths.get(config || '');\n if (existing !== undefined) return existing;\n // Get the original client config to determine if the config has any\n // dynamic paths.\n const originalClientConfig = getClient(config);\n // As an optimization, only fetch the config from the server if the\n // microfrontends configuration has any dynamic paths. If it doesn't,\n // then the server won't return any different values.\n const hasDynamicPaths = originalClientConfig.hasFlaggedPaths;\n cachedHasDynamicPaths.set(config || '', hasDynamicPaths);\n if (!hasDynamicPaths) {\n return false;\n }\n return true;\n }, [config]);\n const [isLoading, setIsLoading] = useState(canLoad);\n useEffect(() => {\n if (!canLoad) return;\n if (!cachedServerClientConfigPromise) {\n cachedServerClientConfigPromise = fetchClientConfigFromServer();\n }\n void cachedServerClientConfigPromise\n .then((newConfig) => {\n if (newConfig) {\n setClientConfig((prevConfig) => {\n return prevConfig.isEqual(newConfig) ? prevConfig : newConfig;\n });\n }\n })\n .finally(() => {\n setIsLoading(false);\n });\n }, [canLoad]);\n\n return { clientConfig, isLoading };\n}\n\nexport function resetCachedServerClientConfigPromise(): void {\n cachedServerClientConfigPromise = null;\n}\n","import { pathToRegexp } from 'path-to-regexp';\nimport type { ClientConfig } from './types';\n\nexport interface MicrofrontendConfigClientOptions {\n removeFlaggedPaths?: boolean;\n}\n\nconst regexpCache = new Map<string, RegExp>();\nconst getRegexp = (path: string): RegExp => {\n const existing = regexpCache.get(path);\n if (existing) {\n return existing;\n }\n\n const regexp = pathToRegexp(path);\n regexpCache.set(path, regexp);\n return regexp;\n};\n\nexport class MicrofrontendConfigClient {\n applications: ClientConfig['applications'];\n hasFlaggedPaths: boolean;\n pathCache: Record<string, string> = {};\n private readonly serialized: ClientConfig;\n\n constructor(config: ClientConfig, opts?: MicrofrontendConfigClientOptions) {\n this.hasFlaggedPaths = config.hasFlaggedPaths ?? false;\n for (const app of Object.values(config.applications)) {\n if (app.routing) {\n if (app.routing.some((match) => match.flag)) {\n this.hasFlaggedPaths = true;\n }\n const newRouting = [];\n const pathsWithoutFlags = [];\n for (const group of app.routing) {\n if (group.flag) {\n if (opts?.removeFlaggedPaths) {\n continue;\n }\n if (group.group) {\n delete group.group;\n }\n newRouting.push(group);\n } else {\n pathsWithoutFlags.push(...group.paths);\n }\n }\n if (pathsWithoutFlags.length > 0) {\n newRouting.push({ paths: pathsWithoutFlags });\n }\n app.routing = newRouting;\n }\n }\n this.serialized = config;\n if (this.hasFlaggedPaths) {\n this.serialized.hasFlaggedPaths = this.hasFlaggedPaths;\n }\n this.applications = config.applications;\n }\n\n /**\n * Create a new `MicrofrontendConfigClient` from a JSON string.\n * Config must be passed in to remain framework agnostic\n */\n static fromEnv(config: string | undefined): MicrofrontendConfigClient {\n if (!config) {\n throw new Error(\n 'Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`? Is the local proxy running and this application is being accessed via the proxy port? See https://vercel.com/docs/microfrontends/local-development#setting-up-microfrontends-proxy',\n );\n }\n return new MicrofrontendConfigClient(JSON.parse(config) as ClientConfig);\n }\n\n isEqual(other: MicrofrontendConfigClient): boolean {\n return (\n this === other ||\n JSON.stringify(this.applications) === JSON.stringify(other.applications)\n );\n }\n\n getApplicationNameForPath(path: string): string | null {\n if (!path.startsWith('/')) {\n throw new Error(`Path must start with a /`);\n }\n\n if (this.pathCache[path]) {\n return this.pathCache[path];\n }\n\n const pathname = new URL(path, 'https://example.com').pathname;\n for (const [name, application] of Object.entries(this.applications)) {\n if (application.routing) {\n for (const group of application.routing) {\n for (const childPath of group.paths) {\n const regexp = getRegexp(childPath);\n if (regexp.test(pathname)) {\n this.pathCache[path] = name;\n return name;\n }\n }\n }\n }\n }\n const defaultApplication = Object.entries(this.applications).find(\n ([, application]) => application.default,\n );\n if (!defaultApplication) {\n return null;\n }\n\n this.pathCache[path] = defaultApplication[0];\n return defaultApplication[0];\n }\n\n serialize(): ClientConfig {\n return this.serialized;\n }\n}\n","import Script from 'next/script.js';\nimport { useEffect, useState } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\n\nconst PREFETCH_ATTR = 'data-prefetch';\nconst DATA_ATTR_SELECTORS = {\n anyZone: '[data-zone]',\n external: '[data-zone=\"null\"]',\n sameZone: '[data-zone=\"same\"]',\n prefetch: `[${PREFETCH_ATTR}]`,\n} as const;\n\nconst PREFETCH_ON_HOVER_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n ],\n};\n\nconst PREFETCH_WHEN_VISIBLE_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n { selector_matches: DATA_ATTR_SELECTORS.prefetch },\n ],\n};\n\nfunction checkVisibility(element: Element | null): boolean {\n if (!element) return true;\n\n if ('checkVisibility' in element) {\n return element.checkVisibility({ opacityProperty: true });\n }\n\n // hack to get around TS thinking element is never;\n const el = element as Element;\n const style = window.getComputedStyle(el);\n\n if (\n style.display === 'none' ||\n style.visibility === 'hidden' ||\n style.opacity === '0'\n ) {\n return false;\n }\n\n return checkVisibility(el.parentElement);\n}\n\ninterface PrefetchCrossZoneLinksProps {\n /**\n * This attributes controls how eager the browser should be in prerendering\n * cross-zone links. Prerendering downloads the HTML and subresources of the page\n * and starts to render the page in the background. This consumes more resources\n * but provides a faster user experience if the user decides to visit that page.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/speculationrules#eagerness\n * for more information.\n *\n * Default value is 'conservative'.\n */\n prerenderEagerness?: 'immediate' | 'eager' | 'moderate' | 'conservative';\n}\n\nexport function PrefetchCrossZoneLinks({\n prerenderEagerness = 'conservative',\n}: PrefetchCrossZoneLinksProps): JSX.Element | null {\n const { isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const [links, setLinks] = useState<HTMLAnchorElement[]>([]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Intersection observer to add the data-prefetch attribute to cross-zone\n * links that have yet to be prefetched and are visible.\n */\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n if (\n entry.isIntersecting &&\n !entry.target.hasAttribute(PREFETCH_ATTR) &&\n // lazy perform the visibility check for nodes that are intersecting the viewport\n // and have not been prefetched.\n checkVisibility(entry.target)\n ) {\n entry.target.setAttribute(PREFETCH_ATTR, 'true');\n }\n });\n },\n {\n root: null,\n rootMargin: '0px',\n threshold: 0.1,\n },\n );\n\n links.forEach((link) => observer.observe(link));\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading, links]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Mutation observer to notify when new nodes have entered/exited the document\n * or an href has changed.\n */\n const observer = new MutationObserver((mutations) => {\n const hasChanged = mutations.some((mutation) => {\n return (\n (mutation.type === 'childList' && mutation.addedNodes.length > 0) ||\n (mutation.type === 'attributes' && mutation.attributeName === 'href')\n );\n });\n\n if (hasChanged) {\n // Whenever there's a change, add all cross-zone links that haven't been\n // prefetched.\n setLinks(\n Array.from(\n document.querySelectorAll<HTMLAnchorElement>(\n `a${DATA_ATTR_SELECTORS.anyZone}:not(${DATA_ATTR_SELECTORS.prefetch}):not(${DATA_ATTR_SELECTORS.sameZone}):not(${DATA_ATTR_SELECTORS.external})`,\n ),\n ),\n );\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['href'],\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading]);\n\n // Wait till the zone-config loads to take into consideration any\n // flagged routes.\n if (isLoading) {\n return null;\n }\n\n // Prefetch links with moderate eagerness by default, immediately when marked \"data-prefetch\".\n // Prerender links with conservative eagerness by default, immediately when marked \"data-prefetch\".\n const speculationRules = {\n prefetch: [\n {\n eagerness: 'moderate',\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n {\n eagerness: 'immediate',\n where: PREFETCH_WHEN_VISIBLE_PREDICATES,\n },\n ],\n prerender: [\n {\n eagerness: prerenderEagerness,\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n ],\n };\n\n return (\n <Script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Safe - injecting JSON speculation rules, not HTML\n dangerouslySetInnerHTML={{\n __html: JSON.stringify(speculationRules),\n }}\n id=\"prefetch-zones-links\"\n type=\"speculationrules\"\n />\n );\n}\n","import type React from 'react';\nimport {\n createContext,\n startTransition,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nexport interface PrefetchCrossZoneLinksContext {\n prefetchHref: (href: string) => void;\n}\n\nexport const PrefetchCrossZoneLinksContext =\n createContext<PrefetchCrossZoneLinksContext>({\n prefetchHref: () => {},\n });\n\nexport function PrefetchCrossZoneLinksProvider({\n children,\n}: {\n children: React.ReactNode;\n}): JSX.Element | null {\n const [seenHrefs, setSeenHrefs] = useState(new Set<string>());\n const isSafariOrFirefox = useRef(\n typeof navigator !== 'undefined' &&\n (navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome'))),\n );\n\n // This useCallback must not have any dependencies because if it changes\n // its value, every component that uses this context will rerender.\n const prefetchHref = useCallback((href: string): void => {\n // It's not critical that we render the new preload `<link>` elements\n // immediately. We want to batch together `prefetchHref` calls that\n // occur in one synchronous pass and only render once after they've all\n // called this callback.\n startTransition(() => {\n setSeenHrefs((prevHrefs) => {\n if (prevHrefs.has(href)) return prevHrefs;\n return new Set(prevHrefs).add(href);\n });\n });\n }, []);\n\n const value = useMemo(() => ({ prefetchHref }), [prefetchHref]);\n\n if (!isSafariOrFirefox.current) {\n return <>{children}</>;\n }\n\n return (\n <PrefetchCrossZoneLinksContext.Provider value={value}>\n {children}\n {[...seenHrefs].map((href) => (\n <link as=\"fetch\" href={href} key={href} rel=\"preload\" />\n ))}\n </PrefetchCrossZoneLinksContext.Provider>\n );\n}\n"],"mappings":";AAAA,OAAOA,MAEA,eAEP,OAAS,cAAAC,EAAY,cAAAC,EAAY,WAAAC,MAAe,QCFhD,OAAS,aAAAC,EAAW,WAAAC,EAAS,YAAAC,MAAgB,QCF7C,OAAS,gBAAAC,MAAoB,iBAO7B,IAAMC,EAAc,IAAI,IAClBC,EAAaC,GAAyB,CAC1C,IAAMC,EAAWH,EAAY,IAAIE,CAAI,EACrC,GAAIC,EACF,OAAOA,EAGT,IAAMC,EAASL,EAAaG,CAAI,EAChC,OAAAF,EAAY,IAAIE,EAAME,CAAM,EACrBA,CACT,EAEaC,EAAN,KAAgC,CAMrC,YAAYC,EAAsBC,EAAyC,CAH3E,eAAoC,CAAC,EAInC,KAAK,gBAAkBD,EAAO,iBAAmB,GACjD,QAAWE,KAAO,OAAO,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AS,UAAYA,EAAK,WAAW,GAAG,EAClE,MAAO,CACL,eAAgBO,EAChB,WAAYA,EACRN,EAAa,0BAA0BD,CAAI,EAC3C,IACN,CACF,EAAG,CAACC,EAAcD,CAAI,CAAC,EAEvB,OAAI,OAAOA,GAAS,UAAY,CAACA,EAAK,OAC7B,CACL,WAAY,KACZ,gBAAiB,GACjB,UAAW,EACb,EAIK,CAAE,WAAAK,EAAY,gBADnB,CAACD,IAAmBC,EAAaP,IAAsBO,EAAa,IAChC,UAAAH,CAAU,CAClD,CAMO,IAAMM,EAAOC,EAClB,CAAC,CAAE,SAAAC,EAAU,GAAGC,CAAM,EAAGC,IAAqB,CAC5C,GAAM,CAAE,aAAAC,CAAa,EAAIC,EAAWC,CAA6B,EAC3D,CAAE,WAAAV,EAAY,gBAAAW,EAAiB,UAAAd,CAAU,EAAIH,EACjDY,EAAM,IACR,EAEA,SAASM,GAAwB,CAC1BN,EAAM,MAGXE,EAAaF,EAAM,IAAI,CACzB,CAEA,GAAIK,GAAmBX,IAAe,KAAM,CAC1C,GAAM,CAAE,SAAUa,EAAG,GAAGC,CAAK,EAAIR,EACjC,OACEd,EAAC,KACE,GAAGsB,EACJ,YAAWd,EACX,QAASM,EAAM,WAAa,GAAQM,EAAkB,OACtD,YAAaN,EAAM,WAAa,GAAQM,EAAkB,OAEzD,SAAAP,EACH,EAIJ,OACEb,EAACuB,EAAA,CACE,GAAGT,EACJ,YAAYN,EAAsB,OAAT,OACzB,SAAUM,EAAM,WAAaT,EAAY,GAAQ,QACjD,IAAKU,EAEJ,SAAAF,EACH,CAEJ,CACF,EACAF,EAAK,YAAc","names":["NextLink","forwardRef","useContext","useMemo","useEffect","useMemo","useState","pathToRegexp","regexpCache","getRegexp","path","existing","regexp","MicrofrontendConfigClient","config","opts","app","match","newRouting","pathsWithoutFlags","group","other","pathname","name","application","childPath","defaultApplication","clientCache","cachedHasDynamicPaths","getClient","config","existing","client","MicrofrontendConfigClient","cachedServerClientConfigPromise","cachedServerClient","fetchClientConfigFromServer","response","responseJson","useClientConfig","clientConfig","setClientConfig","useState","canLoad","useMemo","hasDynamicPaths","isLoading","setIsLoading","useEffect","newConfig","prevConfig","Script","useEffect","useState","jsx","PREFETCH_ATTR","DATA_ATTR_SELECTORS","PREFETCH_ON_HOVER_PREDICATES","PREFETCH_WHEN_VISIBLE_PREDICATES","checkVisibility","element","el","style","PrefetchCrossZoneLinks","prerenderEagerness","isLoading","useClientConfig","links","setLinks","useState","useEffect","observer","entries","entry","link","mutations","mutation","Script","createContext","startTransition","useCallback","useMemo","useRef","useState","Fragment","jsx","jsxs","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","children","seenHrefs","setSeenHrefs","isSafariOrFirefox","prefetchHref","href","prevHrefs","value","jsx","CURRENT_ZONE_HASH","useZoneForHref","href","clientConfig","isLoading","useClientConfig","isRelativePath","zoneOfHref","useMemo","isRelative","Link","forwardRef","children","props","ref","prefetchHref","useContext","PrefetchCrossZoneLinksContext","isDifferentZone","onHoverPrefetch","_","rest","NextLink"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/client/link/microfrontends-link.tsx","../../src/config/react/use-client-config.ts","../../src/config/microfrontends-config/client/index.ts","../../src/next/client/prefetch/prefetch-cross-zone-links.tsx","../../src/next/client/prefetch/prefetch-cross-zone-links-context.tsx"],"sourcesContent":["import NextLink, {\n type LinkProps as ExternalNextLinkProps,\n} from 'next/link.js';\nimport type { AnchorHTMLAttributes } from 'react';\nimport { forwardRef, useContext, useMemo } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\nimport { PrefetchCrossZoneLinksContext } from '../prefetch';\n\ninterface BaseProps {\n children: React.ReactNode;\n href: string;\n}\n\n// fix for tsc inlining LinkProps from next\n// https://github.com/microsoft/TypeScript/issues/37151#issuecomment-756232934\ninterface NextLinkProps extends ExternalNextLinkProps {}\nexport type LinkProps = BaseProps &\n Omit<NextLinkProps, keyof BaseProps> &\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof BaseProps>;\n\nconst CURRENT_ZONE_HASH = process.env.NEXT_PUBLIC_MFE_CURRENT_APPLICATION_HASH;\n\nexport function useZoneForHref(href: LinkProps['href'] | undefined): {\n zoneOfHref: string | null;\n isDifferentZone: boolean;\n isLoading: boolean;\n} {\n const { clientConfig, isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const { isRelativePath, zoneOfHref } = useMemo(() => {\n const isRelative = typeof href === 'string' && href.startsWith('/');\n return {\n isRelativePath: isRelative,\n zoneOfHref: isRelative\n ? clientConfig.getApplicationNameForPath(href)\n : null,\n };\n }, [clientConfig, href]);\n\n if (typeof href === 'string' && !href.length) {\n return {\n zoneOfHref: null,\n isDifferentZone: false,\n isLoading: false,\n };\n }\n const isDifferentZone =\n !isRelativePath || (zoneOfHref ? CURRENT_ZONE_HASH !== zoneOfHref : false);\n return { zoneOfHref, isDifferentZone, isLoading };\n}\n\n/**\n * A Link component that works with microfrontend set-ups and will prefetch the\n * cross zone links automatically.\n */\nexport const Link = forwardRef<HTMLAnchorElement, LinkProps>(\n ({ children, ...props }, ref): JSX.Element => {\n const { prefetchHref } = useContext(PrefetchCrossZoneLinksContext);\n const { zoneOfHref, isDifferentZone, isLoading } = useZoneForHref(\n props.href,\n );\n\n function onHoverPrefetch(): void {\n if (!props.href) {\n return;\n }\n prefetchHref(props.href);\n }\n\n if (isDifferentZone && zoneOfHref !== null) {\n const { prefetch: _, ...rest } = props;\n return (\n <a\n {...rest}\n data-zone={zoneOfHref}\n onFocus={props.prefetch !== false ? onHoverPrefetch : undefined}\n onMouseOver={props.prefetch !== false ? onHoverPrefetch : undefined}\n >\n {children}\n </a>\n );\n }\n\n return (\n <NextLink\n {...props}\n data-zone={!zoneOfHref ? 'null' : 'same'}\n prefetch={props.prefetch ?? (isLoading ? false : undefined)}\n ref={ref}\n >\n {children}\n </NextLink>\n );\n },\n);\nLink.displayName = 'MicrofrontendsLink';\n","'use client';\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { MicrofrontendConfigClient } from '../microfrontends-config/client';\nimport type { WellKnownClientData } from '../well-known/types';\n\nconst clientCache = new Map<string, MicrofrontendConfigClient>();\nconst cachedHasDynamicPaths = new Map<string, boolean>();\n\nconst getClient = (config: string | undefined) => {\n const existing = clientCache.get(config || '');\n if (existing) {\n return existing;\n }\n\n const client = MicrofrontendConfigClient.fromEnv(config);\n clientCache.set(config || '', client);\n return client;\n};\n\nlet cachedServerClientConfigPromise: Promise<MicrofrontendConfigClient | null> | null =\n null;\n\nlet cachedServerClient: MicrofrontendConfigClient | null = null;\n\nasync function fetchClientConfigFromServer(): Promise<MicrofrontendConfigClient | null> {\n try {\n const response = await fetch(\n '/.well-known/vercel/microfrontends/client-config',\n );\n if (response.status !== 200) {\n return null;\n }\n const responseJson = (await response.json()) as WellKnownClientData;\n const client = new MicrofrontendConfigClient(responseJson.config);\n cachedServerClient = client;\n return client;\n } catch {\n return null;\n }\n}\n\n/**\n * Hook to use the client microfrontends configuration. This hook will resolve\n * dynamic paths by fetching the configuration from the server if necessary,\n * allowing the server to specify the values for dynamic paths.\n */\nexport function useClientConfig(config: string | undefined): {\n clientConfig: MicrofrontendConfigClient;\n isLoading: boolean;\n} {\n const [clientConfig, setClientConfig] = useState<MicrofrontendConfigClient>(\n () => cachedServerClient ?? getClient(config),\n );\n const canLoad = useMemo(() => {\n if (\n process.env.NODE_ENV === 'test' &&\n process.env.MFE_FORCE_CLIENT_CONFIG_FROM_SERVER !== '1'\n ) {\n return false;\n }\n // If we've already fetched the server config and it's resolved, we don't need\n // to enter the loading state at all\n if (cachedServerClient) return false;\n // If we've already checked this config for dynamic paths, we can use the\n // cached result from before instead of reevaluating.\n const existing = cachedHasDynamicPaths.get(config || '');\n if (existing !== undefined) return existing;\n // Get the original client config to determine if the config has any\n // dynamic paths.\n const originalClientConfig = getClient(config);\n // As an optimization, only fetch the config from the server if the\n // microfrontends configuration has any dynamic paths. If it doesn't,\n // then the server won't return any different values.\n const hasDynamicPaths = originalClientConfig.hasFlaggedPaths;\n cachedHasDynamicPaths.set(config || '', hasDynamicPaths);\n if (!hasDynamicPaths) {\n return false;\n }\n return true;\n }, [config]);\n const [isLoading, setIsLoading] = useState(canLoad);\n useEffect(() => {\n if (!canLoad) return;\n if (!cachedServerClientConfigPromise) {\n cachedServerClientConfigPromise = fetchClientConfigFromServer();\n }\n void cachedServerClientConfigPromise\n .then((newConfig) => {\n if (newConfig) {\n setClientConfig((prevConfig) => {\n return prevConfig.isEqual(newConfig) ? prevConfig : newConfig;\n });\n }\n })\n .finally(() => {\n setIsLoading(false);\n });\n }, [canLoad]);\n\n return { clientConfig, isLoading };\n}\n\nexport function resetCachedServerClientConfigPromise(): void {\n cachedServerClientConfigPromise = null;\n}\n","import { pathToRegexp } from 'path-to-regexp';\nimport type { ClientConfig } from './types';\n\nexport interface MicrofrontendConfigClientOptions {\n removeFlaggedPaths?: boolean;\n}\n\nconst regexpCache = new Map<string, RegExp>();\nconst getRegexp = (path: string): RegExp => {\n const existing = regexpCache.get(path);\n if (existing) {\n return existing;\n }\n\n const regexp = pathToRegexp(path);\n regexpCache.set(path, regexp);\n return regexp;\n};\n\nexport class MicrofrontendConfigClient {\n applications: ClientConfig['applications'];\n hasFlaggedPaths: boolean;\n pathCache: Record<string, string> = {};\n private readonly serialized: ClientConfig;\n\n constructor(config: ClientConfig, opts?: MicrofrontendConfigClientOptions) {\n this.hasFlaggedPaths = config.hasFlaggedPaths ?? false;\n for (const app of Object.values(config.applications)) {\n if (app.routing) {\n if (app.routing.some((match) => match.flag)) {\n this.hasFlaggedPaths = true;\n }\n const newRouting = [];\n const pathsWithoutFlags = [];\n for (const group of app.routing) {\n if (group.flag) {\n if (opts?.removeFlaggedPaths) {\n continue;\n }\n if (group.group) {\n delete group.group;\n }\n newRouting.push(group);\n } else {\n pathsWithoutFlags.push(...group.paths);\n }\n }\n if (pathsWithoutFlags.length > 0) {\n newRouting.push({ paths: pathsWithoutFlags });\n }\n app.routing = newRouting;\n }\n }\n this.serialized = config;\n if (this.hasFlaggedPaths) {\n this.serialized.hasFlaggedPaths = this.hasFlaggedPaths;\n }\n this.applications = config.applications;\n }\n\n /**\n * Create a new `MicrofrontendConfigClient` from a JSON string.\n * Config must be passed in to remain framework agnostic\n */\n static fromEnv(config: string | undefined): MicrofrontendConfigClient {\n if (!config) {\n throw new Error(\n 'Could not construct MicrofrontendConfigClient: configuration is empty or undefined. Did you set up your application with `withMicrofrontends`? Is the local proxy running and this application is being accessed via the proxy port? See https://vercel.com/docs/microfrontends/local-development#setting-up-microfrontends-proxy',\n );\n }\n return new MicrofrontendConfigClient(JSON.parse(config) as ClientConfig);\n }\n\n isEqual(other: MicrofrontendConfigClient): boolean {\n return (\n this === other ||\n JSON.stringify(this.applications) === JSON.stringify(other.applications)\n );\n }\n\n getApplicationNameForPath(path: string): string | null {\n if (!path.startsWith('/')) {\n throw new Error(`Path must start with a /`);\n }\n\n if (this.pathCache[path]) {\n return this.pathCache[path];\n }\n\n const pathname = new URL(path, 'https://example.com').pathname;\n for (const [name, application] of Object.entries(this.applications)) {\n if (application.routing) {\n for (const group of application.routing) {\n for (const childPath of group.paths) {\n const regexp = getRegexp(childPath);\n if (regexp.test(pathname)) {\n this.pathCache[path] = name;\n return name;\n }\n }\n }\n }\n }\n const defaultApplication = Object.entries(this.applications).find(\n ([, application]) => application.default,\n );\n if (!defaultApplication) {\n return null;\n }\n\n this.pathCache[path] = defaultApplication[0];\n return defaultApplication[0];\n }\n\n serialize(): ClientConfig {\n return this.serialized;\n }\n}\n","import Script from 'next/script.js';\nimport { useEffect, useState } from 'react';\nimport { useClientConfig } from '../../../config/react/use-client-config';\n\nconst PREFETCH_ATTR = 'data-prefetch';\nconst DATA_ATTR_SELECTORS = {\n anyZone: '[data-zone]',\n external: '[data-zone=\"null\"]',\n sameZone: '[data-zone=\"same\"]',\n prefetch: `[${PREFETCH_ATTR}]`,\n} as const;\n\nconst PREFETCH_ON_HOVER_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n ],\n};\n\nconst PREFETCH_WHEN_VISIBLE_PREDICATES = {\n and: [\n { href_matches: '/*' },\n { selector_matches: DATA_ATTR_SELECTORS.anyZone },\n { not: { selector_matches: DATA_ATTR_SELECTORS.sameZone } },\n { not: { selector_matches: DATA_ATTR_SELECTORS.external } },\n { selector_matches: DATA_ATTR_SELECTORS.prefetch },\n ],\n};\n\nfunction checkVisibility(element: Element | null): boolean {\n if (!element) return true;\n\n if ('checkVisibility' in element) {\n return element.checkVisibility({ opacityProperty: true });\n }\n\n // hack to get around TS thinking element is never;\n const el = element as Element;\n const style = window.getComputedStyle(el);\n\n if (\n style.display === 'none' ||\n style.visibility === 'hidden' ||\n style.opacity === '0'\n ) {\n return false;\n }\n\n return checkVisibility(el.parentElement);\n}\n\ninterface PrefetchCrossZoneLinksProps {\n /**\n * This attributes controls how eager the browser should be in prerendering\n * cross-zone links. Prerendering downloads the HTML and subresources of the page\n * and starts to render the page in the background. This consumes more resources\n * but provides a faster user experience if the user decides to visit that page.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/speculationrules#eagerness\n * for more information.\n *\n * Default value is 'conservative'.\n */\n prerenderEagerness?: 'immediate' | 'eager' | 'moderate' | 'conservative';\n}\n\nexport function PrefetchCrossZoneLinks({\n prerenderEagerness = 'conservative',\n}: PrefetchCrossZoneLinksProps): JSX.Element | null {\n const { isLoading } = useClientConfig(\n process.env.NEXT_PUBLIC_MFE_CLIENT_CONFIG,\n );\n const [links, setLinks] = useState<HTMLAnchorElement[]>([]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Intersection observer to add the data-prefetch attribute to cross-zone\n * links that have yet to be prefetched and are visible.\n */\n const observer = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n if (\n entry.isIntersecting &&\n !entry.target.hasAttribute(PREFETCH_ATTR) &&\n // lazy perform the visibility check for nodes that are intersecting the viewport\n // and have not been prefetched.\n checkVisibility(entry.target)\n ) {\n entry.target.setAttribute(PREFETCH_ATTR, 'true');\n }\n });\n },\n {\n root: null,\n rootMargin: '0px',\n threshold: 0.1,\n },\n );\n\n links.forEach((link) => observer.observe(link));\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading, links]);\n\n useEffect(() => {\n if (isLoading) {\n return;\n }\n\n /**\n * Mutation observer to notify when new nodes have entered/exited the document\n * or an href has changed.\n */\n const observer = new MutationObserver((mutations) => {\n const hasChanged = mutations.some((mutation) => {\n return (\n (mutation.type === 'childList' && mutation.addedNodes.length > 0) ||\n (mutation.type === 'attributes' && mutation.attributeName === 'href')\n );\n });\n\n if (hasChanged) {\n // Whenever there's a change, add all cross-zone links that haven't been\n // prefetched.\n setLinks(\n Array.from(\n document.querySelectorAll<HTMLAnchorElement>(\n `a${DATA_ATTR_SELECTORS.anyZone}:not(${DATA_ATTR_SELECTORS.prefetch}):not(${DATA_ATTR_SELECTORS.sameZone}):not(${DATA_ATTR_SELECTORS.external})`,\n ),\n ),\n );\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['href'],\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isLoading]);\n\n // Wait till the zone-config loads to take into consideration any\n // flagged routes.\n if (isLoading) {\n return null;\n }\n\n // Prefetch links with moderate eagerness by default, immediately when marked \"data-prefetch\".\n // Prerender links with conservative eagerness by default, immediately when marked \"data-prefetch\".\n const speculationRules = {\n prefetch: [\n {\n eagerness: 'moderate',\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n {\n eagerness: 'immediate',\n where: PREFETCH_WHEN_VISIBLE_PREDICATES,\n },\n ],\n prerender: [\n {\n eagerness: prerenderEagerness,\n where: PREFETCH_ON_HOVER_PREDICATES,\n },\n ],\n };\n\n return (\n <Script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Safe - injecting JSON speculation rules, not HTML\n dangerouslySetInnerHTML={{\n __html: JSON.stringify(speculationRules),\n }}\n id=\"prefetch-zones-links\"\n type=\"speculationrules\"\n />\n );\n}\n","import type React from 'react';\nimport {\n createContext,\n startTransition,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nexport interface PrefetchCrossZoneLinksContext {\n prefetchHref: (href: string) => void;\n}\n\nexport const PrefetchCrossZoneLinksContext =\n createContext<PrefetchCrossZoneLinksContext>({\n prefetchHref: () => {},\n });\n\nexport function PrefetchCrossZoneLinksProvider({\n children,\n}: {\n children: React.ReactNode;\n}): JSX.Element | null {\n const [seenHrefs, setSeenHrefs] = useState(new Set<string>());\n const isSafariOrFirefox = useRef(\n typeof navigator !== 'undefined' &&\n (navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome'))),\n );\n\n // This useCallback must not have any dependencies because if it changes\n // its value, every component that uses this context will rerender.\n const prefetchHref = useCallback((href: string): void => {\n // It's not critical that we render the new preload `<link>` elements\n // immediately. We want to batch together `prefetchHref` calls that\n // occur in one synchronous pass and only render once after they've all\n // called this callback.\n startTransition(() => {\n setSeenHrefs((prevHrefs) => {\n if (prevHrefs.has(href)) return prevHrefs;\n return new Set(prevHrefs).add(href);\n });\n });\n }, []);\n\n const value = useMemo(() => ({ prefetchHref }), [prefetchHref]);\n\n if (!isSafariOrFirefox.current) {\n return <>{children}</>;\n }\n\n return (\n <PrefetchCrossZoneLinksContext.Provider value={value}>\n {children}\n {[...seenHrefs].map((href) => (\n <link as=\"fetch\" href={href} key={href} rel=\"preload\" />\n ))}\n </PrefetchCrossZoneLinksContext.Provider>\n );\n}\n"],"mappings":";AAAA,OAAOA,MAEA,eAEP,OAAS,cAAAC,EAAY,cAAAC,EAAY,WAAAC,MAAe,QCFhD,OAAS,aAAAC,EAAW,WAAAC,EAAS,YAAAC,MAAgB,QCF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,EACJ,YAAYN,EAAsB,OAAT,OACzB,SAAUM,EAAM,WAAaT,EAAY,GAAQ,QACjD,IAAKU,EAEJ,SAAAF,EACH,CAEJ,CACF,EACAF,EAAK,YAAc","names":["NextLink","forwardRef","useContext","useMemo","useEffect","useMemo","useState","pathToRegexp","regexpCache","getRegexp","path","existing","regexp","MicrofrontendConfigClient","config","opts","app","match","newRouting","pathsWithoutFlags","group","other","pathname","name","application","childPath","defaultApplication","clientCache","cachedHasDynamicPaths","getClient","config","existing","client","MicrofrontendConfigClient","cachedServerClientConfigPromise","cachedServerClient","fetchClientConfigFromServer","response","responseJson","useClientConfig","clientConfig","setClientConfig","useState","canLoad","useMemo","hasDynamicPaths","isLoading","setIsLoading","useEffect","newConfig","prevConfig","Script","useEffect","useState","jsx","PREFETCH_ATTR","DATA_ATTR_SELECTORS","PREFETCH_ON_HOVER_PREDICATES","PREFETCH_WHEN_VISIBLE_PREDICATES","checkVisibility","element","el","style","PrefetchCrossZoneLinks","prerenderEagerness","isLoading","useClientConfig","links","setLinks","useState","useEffect","observer","entries","entry","link","mutations","mutation","Script","createContext","startTransition","useCallback","useMemo","useRef","useState","Fragment","jsx","jsxs","PrefetchCrossZoneLinksContext","PrefetchCrossZoneLinksProvider","children","seenHrefs","setSeenHrefs","isSafariOrFirefox","prefetchHref","href","prevHrefs","value","jsx","CURRENT_ZONE_HASH","useZoneForHref","href","clientConfig","isLoading","useClientConfig","isRelativePath","zoneOfHref","useMemo","isRelative","Link","forwardRef","children","props","ref","prefetchHref","useContext","PrefetchCrossZoneLinksContext","isDifferentZone","onHoverPrefetch","_","rest","NextLink"]}
|