|
| 1 | +import path from 'path' |
| 2 | +import fse from 'fs-extra' |
| 3 | +import { execa } from 'execa' |
| 4 | +import { MultiThemePluginOptions } from '@/utils/optionsUtils' |
| 5 | +import { type Config as TailwindConfig } from 'tailwindcss' |
| 6 | +import { |
| 7 | + CommandOptions, |
| 8 | + defineRepoInstance, |
| 9 | + StartServerOptions, |
| 10 | + ServerStarted, |
| 11 | + StartServerResult, |
| 12 | + StopServerCallback |
| 13 | +} from './repo_instance' |
| 14 | +import serialize from 'serialize-javascript' |
| 15 | +import getPort from 'get-port' |
| 16 | +import { getRepoPaths, RepoPaths } from './paths' |
| 17 | + |
| 18 | +export interface OpenOptions { |
| 19 | + baseTailwindConfig?: { theme: TailwindConfig['theme'] } |
| 20 | + themerConfig: MultiThemePluginOptions |
| 21 | + instanceId: string |
| 22 | +} |
| 23 | + |
| 24 | +export interface Driver { |
| 25 | + install: () => Promise<void> |
| 26 | + cleanup: () => Promise<void> |
| 27 | + open: ( |
| 28 | + options: OpenOptions |
| 29 | + ) => Promise<{ url: string; stop: StopServerCallback }> |
| 30 | +} |
| 31 | + |
| 32 | +export const resolveDriver = async (repo: string): Promise<Driver> => { |
| 33 | + const repoPaths = getRepoPaths(repo) |
| 34 | + try { |
| 35 | + const module = (await import(repoPaths.driverFilePath)) as unknown |
| 36 | + |
| 37 | + if ( |
| 38 | + !module || |
| 39 | + typeof module !== 'object' || |
| 40 | + !('default' in module) || |
| 41 | + !module.default || |
| 42 | + typeof module.default !== 'object' |
| 43 | + ) { |
| 44 | + throw new Error( |
| 45 | + `Module ${repoPaths.driverFilePath} does not export a default driver options object` |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + return new DriverImpl({ |
| 50 | + ...(module.default as DriverOptions), |
| 51 | + repoPaths |
| 52 | + }) |
| 53 | + } catch (error) { |
| 54 | + console.error(`Failed to import or use driver for repo: ${repo}`, error) |
| 55 | + throw error // Fail the test if the driver fails to load |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +export type { StopServerCallback } |
| 60 | + |
| 61 | +export interface DriverOptions { |
| 62 | + repoPaths: RepoPaths |
| 63 | + installCommand: CommandOptions |
| 64 | + getBuildCommand: ({ |
| 65 | + tailwindConfigFilePath, |
| 66 | + buildDirPath |
| 67 | + }: { |
| 68 | + tailwindConfigFilePath: string |
| 69 | + buildDirPath: string |
| 70 | + }) => CommandOptions |
| 71 | + getStartServerOptions: ({ |
| 72 | + port, |
| 73 | + buildDir |
| 74 | + }: { |
| 75 | + port: number |
| 76 | + buildDir: string |
| 77 | + }) => StartServerOptions |
| 78 | +} |
| 79 | + |
| 80 | +// Quality of life helper to define driver options |
| 81 | +export const defineDriver = <T extends Omit<DriverOptions, 'repoPaths'>>( |
| 82 | + options: T |
| 83 | +): T => options |
| 84 | + |
| 85 | +class DriverImpl implements Driver { |
| 86 | + constructor(private driverOptions: DriverOptions) {} |
| 87 | + async install() { |
| 88 | + const nodeModulesPath = path.join( |
| 89 | + this.driverOptions.repoPaths.repoDirPath, |
| 90 | + 'node_modules' |
| 91 | + ) |
| 92 | + if (!(await fse.exists(nodeModulesPath))) { |
| 93 | + await execa( |
| 94 | + this.driverOptions.installCommand.command[0], |
| 95 | + this.driverOptions.installCommand.command[1], |
| 96 | + { |
| 97 | + cwd: this.driverOptions.repoPaths.repoDirPath, |
| 98 | + env: this.driverOptions.installCommand.env |
| 99 | + } |
| 100 | + ) |
| 101 | + } |
| 102 | + } |
| 103 | + async cleanup() { |
| 104 | + await fse.rm(this.driverOptions.repoPaths.tmpDirPath, { |
| 105 | + recursive: true, |
| 106 | + force: true |
| 107 | + }) |
| 108 | + } |
| 109 | + async open(openOptions: OpenOptions) { |
| 110 | + const { instance, isAlreadyInitialized } = await defineRepoInstance({ |
| 111 | + repoDirPath: this.driverOptions.repoPaths.repoDirPath, |
| 112 | + instanceDirPath: path.join( |
| 113 | + this.driverOptions.repoPaths.tmpDirPath, |
| 114 | + openOptions.instanceId |
| 115 | + ) |
| 116 | + }) |
| 117 | + |
| 118 | + if (!isAlreadyInitialized) { |
| 119 | + const classesToPreventPurging = this.#parseClasses( |
| 120 | + openOptions.themerConfig |
| 121 | + ) |
| 122 | + |
| 123 | + const tailwindConfig: TailwindConfig = { |
| 124 | + content: ['./src/**/*.{js,jsx,ts,tsx}'], |
| 125 | + safelist: classesToPreventPurging, |
| 126 | + theme: openOptions.baseTailwindConfig?.theme ?? { |
| 127 | + extend: {} |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + const { filePath: tailwindConfigFilePath } = await instance.writeFile( |
| 132 | + 'tailwind.config.js', |
| 133 | + `module.exports = { |
| 134 | + ...${JSON.stringify(tailwindConfig)}, |
| 135 | + plugins: [require('tailwindcss-themer')(${serialize( |
| 136 | + openOptions.themerConfig |
| 137 | + )})] |
| 138 | + }` |
| 139 | + ) |
| 140 | + |
| 141 | + const buildCommandOptions = this.driverOptions.getBuildCommand({ |
| 142 | + tailwindConfigFilePath, |
| 143 | + buildDirPath: instance.buildDirPath |
| 144 | + }) |
| 145 | + await instance.execute(buildCommandOptions) |
| 146 | + } |
| 147 | + |
| 148 | + const { url, stop } = await this.#startServerWithRetry({ |
| 149 | + maxAttempts: 2, |
| 150 | + startServer: async () => { |
| 151 | + const port = await getPort() |
| 152 | + const startServerOptions = this.driverOptions.getStartServerOptions({ |
| 153 | + port, |
| 154 | + buildDir: instance.buildDirPath |
| 155 | + }) |
| 156 | + return await instance.startServer(startServerOptions) |
| 157 | + } |
| 158 | + }) |
| 159 | + |
| 160 | + return { |
| 161 | + url, |
| 162 | + stop |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + async #startServerWithRetry({ |
| 167 | + maxAttempts, |
| 168 | + startServer |
| 169 | + }: { |
| 170 | + maxAttempts: number |
| 171 | + startServer: () => Promise<StartServerResult> |
| 172 | + }): Promise<ServerStarted> { |
| 173 | + let attemptNumber = 0 |
| 174 | + let failedReason = 'unknown' |
| 175 | + while (attemptNumber <= maxAttempts) { |
| 176 | + attemptNumber++ |
| 177 | + if (attemptNumber > 1) { |
| 178 | + console.log( |
| 179 | + `Retrying (attempt ${attemptNumber}) starting the server because: ${failedReason}` |
| 180 | + ) |
| 181 | + } |
| 182 | + |
| 183 | + const result = await startServer() |
| 184 | + |
| 185 | + if (result.started) { |
| 186 | + return result |
| 187 | + } else { |
| 188 | + failedReason = result.reason |
| 189 | + } |
| 190 | + } |
| 191 | + throw new Error( |
| 192 | + `Attempted to start server ${attemptNumber} times but couldn't start the server\n\n${failedReason}` |
| 193 | + ) |
| 194 | + } |
| 195 | + |
| 196 | + #parseClasses(config: MultiThemePluginOptions): string[] { |
| 197 | + const themeNameClasses = [ |
| 198 | + 'defaultTheme', |
| 199 | + ...(config.themes?.map(x => x.name) ?? []) |
| 200 | + ] |
| 201 | + // Preventing purging of these styles makes writing tests with arbitrary classes |
| 202 | + // easier since otherwise they'd have to define the styles they use when opening |
| 203 | + // the repo instance |
| 204 | + const stylesToKeep = [ |
| 205 | + 'bg-primary', |
| 206 | + 'bg-primary/75', |
| 207 | + 'bg-primary-DEFAULT-500', |
| 208 | + 'font-title', |
| 209 | + 'text-textColor', |
| 210 | + 'text-textColor/50' |
| 211 | + ] |
| 212 | + const preloadedVariantStyles = themeNameClasses.flatMap(themeName => |
| 213 | + stylesToKeep.map(style => `${themeName}:${style}`) |
| 214 | + ) |
| 215 | + const mediaQueries = |
| 216 | + config.themes?.map(x => x.mediaQuery ?? '')?.filter(x => !!x) ?? [] |
| 217 | + const selectors = config.themes?.flatMap(x => x.selectors ?? []) ?? [] |
| 218 | + return [ |
| 219 | + ...themeNameClasses, |
| 220 | + ...preloadedVariantStyles, |
| 221 | + ...mediaQueries, |
| 222 | + ...selectors, |
| 223 | + ...stylesToKeep |
| 224 | + ] |
| 225 | + } |
| 226 | +} |
0 commit comments