/** * Is the project's committed admin import map older than the config? * * ipalKit registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components * through the import map file, and a path that is not in it renders NOTHING: the 2FA screen comes * back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where * `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file * by itself; a production build uses the committed one. This check makes that state loud: an * error in the server log at start, and a notice on the 2FA screens (TotpRedirectProvider) — * shown next to the screen, never instead of it, because the check can be wrong (see * `missingImportMapEntries`). `twoFactor.importMapCheck: false` turns it off. */ type ConfigLike = { admin?: { importMap?: { baseDir?: string; importMapFile?: string } }; routes?: { admin?: string } } /** The file Payload reads the import map from — the same places Payload itself looks in. Null when not found. */ export async function findImportMapFile(config: ConfigLike, cwd = process.cwd()): Promise { try { const fs = await import('node:fs/promises') const path = await import('node:path') const exists = (file: string) => fs.access(file).then(() => true, () => false) const explicit = config.admin?.importMap?.importMapFile if (explicit) {return (await exists(explicit)) ? explicit : null} const rootDir = config.admin?.importMap?.baseDir ?? cwd // Next.js writes %5F for route segments that begin with an underscore const adminFolder = (config.routes?.admin ?? '/admin').replace(/(^|\/)_/g, '$1%5F') for (const base of [`app/(payload)${adminFolder}`, `src/app/(payload)${adminFolder}`]) { const file = path.resolve(rootDir, base, 'importMap.js') if (await exists(file)) {return file} } } catch { /* no file system (or not Node): nothing to check */ } return null } /** * The entries of `needed` that are not written in the import map file. An empty list when the * file is not found or cannot be read. * * This is a text search of the file ON DISK, and a hint, not a fact: the map the running build * uses is in the bundle. The two differ when the map is generated inside the build and the * running image carries the repository's file (a Dockerfile runner stage with its own COPY), and * the search misses a map that re-exports or builds its keys another way. So a caller may warn * on the result, and must never block on it. */ export async function missingImportMapEntries(config: ConfigLike, needed: string[], cwd?: string): Promise<{ file: null | string; missing: string[] }> { const file = await findImportMapFile(config, cwd) if (!file) {return { file: null, missing: [] }} try { const fs = await import('node:fs/promises') const text = await fs.readFile(file, 'utf8') return { file, missing: needed.filter((entry) => !text.includes(`"${entry}"`) && !text.includes(`'${entry}'`)) } } catch { return { file, missing: [] } } }