import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { ForgeTemplate, PossibleModule } from '@electron-forge/shared-types'; import debug from 'debug'; const d = debug('electron-forge:init:find-template'); export interface ForgeTemplateDetails { name: string; path: string; template: ForgeTemplate; } export const findTemplate = async ( template: string, ): Promise => { let foundTemplate: Omit | null = null; // Convert absolute paths to file URLs for cross-platform compatibility. // import.meta.resolve() doesn't recognize Windows-style paths like "D:\..." // and needs them as file URLs (e.g., "file:///D:/..."). // When a path is absolute, we skip the prefixed package name lookups. const isAbsolutePath = path.isAbsolute(template); const templatePath = isAbsolutePath ? pathToFileURL(template).href : template; const resolveTemplateTypes = isAbsolutePath ? [templatePath] : ([ `electron-forge-template-${template}`, `@electron-forge/template-${template}`, template, ] as const); for (const moduleName of resolveTemplateTypes) { try { d(`Trying template: ${moduleName}`); foundTemplate = { path: import.meta.resolve(moduleName), name: moduleName, }; break; } catch (err) { d(`Error: ${err instanceof Error ? err.message : err}`); } } if (!foundTemplate) { // Only the bundled `vite`/`webpack` templates were unified behind the // `--typescript` flag, so only redirect the old short-form names. Skip // absolute paths and third-party templates, which don't honor the flag. if ( !isAbsolutePath && (template === 'vite-typescript' || template === 'webpack-typescript') ) { const bundler = template.replace(/-typescript$/, ''); throw new Error( `The "${template}" template no longer exists. Use "--template ${bundler} --typescript" instead.`, ); } throw new Error(`Failed to locate custom template: "${template}".`); } else { d(`found template module at: ${foundTemplate.path}`); const templateModule: PossibleModule = await import( foundTemplate.path ); const tmpl = templateModule.default ?? templateModule; return { ...foundTemplate, template: tmpl, }; } };