Initial commit

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
dinlo
2026-05-31 18:44:04 +08:00
commit 436a9631fc
8616 changed files with 1389957 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
import { Configuration } from "../configuration";
import { Framework } from "../Framework";
import { Packager } from "../index";
export type ElectronPlatformName = "darwin" | "linux" | "win32" | "mas";
/**
* Electron distributables branding options.
* @see [Electron BRANDING.json](https://github.com/electron/electron/blob/master/shell/app/BRANDING.json).
*/
export interface ElectronBrandingOptions {
projectName?: string;
productName?: string;
}
export declare function createBrandingOpts(opts: Configuration): Required<ElectronBrandingOptions>;
export interface ElectronDownloadOptions {
version?: string;
/**
* The [cache location](https://github.com/electron-userland/electron-download#cache-location).
*/
cache?: string | null;
/**
* The mirror.
*/
mirror?: string | null;
/** @private */
customDir?: string | null;
/** @private */
customFilename?: string | null;
strictSSL?: boolean;
isVerifyChecksum?: boolean;
platform?: ElectronPlatformName;
arch?: string;
}
export declare function createElectronFrameworkSupport(configuration: Configuration, packager: Packager): Promise<Framework>;
+221
View File
@@ -0,0 +1,221 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBrandingOpts = createBrandingOpts;
exports.createElectronFrameworkSupport = createElectronFrameworkSupport;
const builder_util_1 = require("builder-util");
const fs_extra_1 = require("fs-extra");
const path = require("path");
const tiny_async_pool_1 = require("tiny-async-pool");
const index_1 = require("../index");
const pathManager_1 = require("../util/pathManager");
const resolve_1 = require("../util/resolve");
const electronMac_1 = require("./electronMac");
const electronVersion_1 = require("./electronVersion");
const electronWin_1 = require("./electronWin");
const injectFFMPEG_1 = require("./injectFFMPEG");
function createBrandingOpts(opts) {
var _a, _b;
return {
projectName: ((_a = opts.electronBranding) === null || _a === void 0 ? void 0 : _a.projectName) || "electron",
productName: ((_b = opts.electronBranding) === null || _b === void 0 ? void 0 : _b.productName) || "Electron",
};
}
function createDownloadOpts(opts, platform, arch, electronVersion) {
return {
platform,
arch,
version: electronVersion,
...opts.electronDownload,
};
}
async function beforeCopyExtraFiles(options) {
const { appOutDir, packager } = options;
const electronBranding = createBrandingOpts(packager.config);
if (packager.platform === index_1.Platform.LINUX) {
const linuxPackager = packager;
const executable = path.join(appOutDir, linuxPackager.executableName);
await (0, fs_extra_1.rename)(path.join(appOutDir, electronBranding.projectName), executable);
}
else if (packager.platform === index_1.Platform.WINDOWS) {
const executable = path.join(appOutDir, `${packager.appInfo.productFilename}.exe`);
await (0, fs_extra_1.rename)(path.join(appOutDir, `${electronBranding.projectName}.exe`), executable);
if (options.asarIntegrity) {
await (0, electronWin_1.addWinAsarIntegrity)(executable, options.asarIntegrity);
}
}
else {
await (0, electronMac_1.createMacApp)(packager, appOutDir, options.asarIntegrity, options.platformName === "mas");
}
await removeUnusedLanguagesIfNeeded(options);
}
async function removeUnusedLanguagesIfNeeded(options) {
const { packager: { config, platformSpecificBuildOptions }, } = options;
const wantedLanguages = (0, builder_util_1.asArray)(platformSpecificBuildOptions.electronLanguages || config.electronLanguages);
if (!wantedLanguages.length) {
return;
}
const { dirs, langFileExt } = getLocalesConfig(options);
// noinspection SpellCheckingInspection
const deletedFiles = async (dir) => {
await (0, tiny_async_pool_1.default)(builder_util_1.MAX_FILE_REQUESTS, await (0, fs_extra_1.readdir)(dir), async (file) => {
if (path.extname(file) !== langFileExt) {
return;
}
const language = path.basename(file, langFileExt);
if (!wantedLanguages.includes(language)) {
return (0, fs_extra_1.rm)(path.join(dir, file), { recursive: true, force: true });
}
return;
});
};
await Promise.all(dirs.map(deletedFiles));
function getLocalesConfig(options) {
const { appOutDir, packager } = options;
if (packager.platform === index_1.Platform.MAC) {
return { dirs: [packager.getResourcesDir(appOutDir), packager.getMacOsElectronFrameworkResourcesDir(appOutDir)], langFileExt: ".lproj" };
}
return { dirs: [path.join(packager.getResourcesDir(appOutDir), "..", "locales")], langFileExt: ".pak" };
}
}
class ElectronFramework {
constructor(name, version, distMacOsAppName) {
this.name = name;
this.version = version;
this.distMacOsAppName = distMacOsAppName;
// noinspection JSUnusedGlobalSymbols
this.macOsDefaultTargets = ["zip", "dmg"];
// noinspection JSUnusedGlobalSymbols
this.defaultAppIdPrefix = "com.electron.";
// noinspection JSUnusedGlobalSymbols
this.isCopyElevateHelper = true;
// noinspection JSUnusedGlobalSymbols
this.isNpmRebuildRequired = true;
}
getDefaultIcon(platform) {
if (platform === index_1.Platform.LINUX) {
return path.join((0, pathManager_1.getTemplatePath)("icons"), "electron-linux");
}
else {
// default icon is embedded into app skeleton
return null;
}
}
async prepareApplicationStageDirectory(options) {
const downloadOptions = createDownloadOpts(options.packager.config, options.platformName, options.arch, this.version);
const shouldCleanup = await unpack(options, downloadOptions, this.distMacOsAppName);
await cleanupAfterUnpack(options, this.distMacOsAppName, shouldCleanup);
if (options.packager.config.downloadAlternateFFmpeg) {
await (0, injectFFMPEG_1.default)(options, this.version);
}
}
beforeCopyExtraFiles(options) {
return beforeCopyExtraFiles(options);
}
}
async function createElectronFrameworkSupport(configuration, packager) {
let version = configuration.electronVersion;
if (version == null) {
// for prepacked app asar no dev deps in the app.asar
if (packager.isPrepackedAppAsar) {
version = await (0, electronVersion_1.getElectronVersionFromInstalled)(packager.projectDir);
if (version == null) {
throw new Error(`Cannot compute electron version for prepacked asar`);
}
}
else {
version = await (0, electronVersion_1.computeElectronVersion)(packager.projectDir);
}
configuration.electronVersion = version;
}
const branding = createBrandingOpts(configuration);
return new ElectronFramework(branding.projectName, version, `${branding.productName}.app`);
}
/**
* Unpacks a custom or default Electron distribution into the app output directory.
*/
async function unpack(prepareOptions, downloadOptions, distMacOsAppName) {
const downloadUsingAdjustedConfig = (options) => {
return (0, builder_util_1.executeAppBuilder)(["unpack-electron", "--configuration", JSON.stringify([options]), "--output", appOutDir, "--distMacOsAppName", distMacOsAppName]);
};
const copyUnpackedElectronDistribution = async (folderPath) => {
builder_util_1.log.info({ electronDist: builder_util_1.log.filePath(folderPath) }, "using custom unpacked Electron distribution");
const source = packager.getElectronSrcDir(folderPath);
const destination = packager.getElectronDestinationDir(appOutDir);
builder_util_1.log.info({ source, destination }, "copying unpacked Electron");
await (0, fs_extra_1.emptyDir)(appOutDir);
await (0, builder_util_1.copyDir)(source, destination, {
isUseHardLink: builder_util_1.DO_NOT_USE_HARD_LINKS,
});
return false;
};
const selectElectron = async (filepath) => {
const resolvedDist = path.isAbsolute(filepath) ? filepath : path.resolve(packager.projectDir, filepath);
const electronDistStats = await (0, builder_util_1.statOrNull)(resolvedDist);
if (!electronDistStats) {
throw new Error(`The specified electronDist does not exist: ${resolvedDist}. Please provide a valid path to the Electron zip file, cache directory, or electron build directory.`);
}
if (resolvedDist.endsWith(".zip")) {
builder_util_1.log.info({ zipFile: resolvedDist }, "using custom electronDist zip file");
await downloadUsingAdjustedConfig({
...downloadOptions,
cache: path.dirname(resolvedDist), // set custom directory to the zip file's directory
customFilename: path.basename(resolvedDist), // set custom filename to the zip file's name
});
return false; // do not clean up after unpacking, it's a custom bundle and we should respect its configuration/contents as required
}
if (electronDistStats.isDirectory()) {
// backward compatibility: if electronDist is a directory, check for the default zip file inside it
const files = await (0, fs_extra_1.readdir)(resolvedDist);
if (files.includes(defaultZipName)) {
builder_util_1.log.info({ electronDist: builder_util_1.log.filePath(resolvedDist) }, "using custom electronDist directory");
await downloadUsingAdjustedConfig({
...downloadOptions,
cache: resolvedDist,
customFilename: defaultZipName,
});
return false;
}
// if we reach here, it means the provided electronDist is neither a zip file nor a directory with the default zip file
// e.g. we treat it as a custom already-unpacked Electron distribution
return await copyUnpackedElectronDistribution(resolvedDist);
}
throw new Error(`The specified electronDist is neither a zip file nor a directory: ${resolvedDist}. Please provide a valid path to the Electron zip file or cache directory.`);
};
const { packager, appOutDir, platformName } = prepareOptions;
const { version, arch } = downloadOptions;
const defaultZipName = `electron-v${version}-${platformName}-${arch}.zip`;
const electronDist = packager.config.electronDist;
if (typeof electronDist === "string" && !(0, builder_util_1.isEmptyOrSpaces)(electronDist)) {
return selectElectron(electronDist);
}
let resolvedDist = null;
try {
const electronDistHook = await (0, resolve_1.resolveFunction)(packager.appInfo.type, electronDist, "electronDist");
resolvedDist = typeof electronDistHook === "function" ? await Promise.resolve(electronDistHook(prepareOptions)) : electronDistHook;
}
catch (error) {
builder_util_1.log.warn({ error }, "Failed to resolve electronDist, using default unpack logic");
}
if (resolvedDist == null) {
// if no custom electronDist is provided, use the default unpack logic
builder_util_1.log.debug(null, "no custom electronDist provided, unpacking default Electron distribution");
await downloadUsingAdjustedConfig(downloadOptions);
return true; // indicates that we should clean up after unpacking
}
return selectElectron(resolvedDist);
}
function cleanupAfterUnpack(prepareOptions, distMacOsAppName, isFullCleanup) {
const out = prepareOptions.appOutDir;
const isMac = prepareOptions.packager.platform === index_1.Platform.MAC;
const resourcesPath = isMac ? path.join(out, distMacOsAppName, "Contents", "Resources") : path.join(out, "resources");
return Promise.all([
isFullCleanup ? (0, builder_util_1.unlinkIfExists)(path.join(resourcesPath, "default_app.asar")) : Promise.resolve(),
isFullCleanup ? (0, builder_util_1.unlinkIfExists)(path.join(out, "version")) : Promise.resolve(),
isMac
? Promise.resolve()
: (0, fs_extra_1.rename)(path.join(out, "LICENSE"), path.join(out, "LICENSE.electron.txt")).catch(() => {
/* ignore */
}),
]);
}
//# sourceMappingURL=ElectronFramework.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export {};
+262
View File
@@ -0,0 +1,262 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMacApp = createMacApp;
const builder_util_1 = require("builder-util");
const promises_1 = require("fs/promises");
const path = require("path");
const fs = require("fs");
const appInfo_1 = require("../appInfo");
const platformPackager_1 = require("../platformPackager");
const plist_1 = require("../util/plist");
const ElectronFramework_1 = require("./ElectronFramework");
function doRename(basePath, oldName, newName) {
return (0, promises_1.rename)(path.join(basePath, oldName), path.join(basePath, newName));
}
function moveHelpers(helperSuffixes, frameworksPath, appName, prefix) {
return Promise.all(helperSuffixes.map(suffix => {
const executableBasePath = path.join(frameworksPath, `${prefix}${suffix}.app`, "Contents", "MacOS");
return doRename(executableBasePath, `${prefix}${suffix}`, appName + suffix).then(() => doRename(frameworksPath, `${prefix}${suffix}.app`, `${appName}${suffix}.app`));
}));
}
function getAvailableHelperSuffixes(helperEHPlist, helperNPPlist, helperRendererPlist, helperPluginPlist, helperGPUPlist) {
const result = [" Helper"];
if (helperEHPlist != null) {
result.push(" Helper EH");
}
if (helperNPPlist != null) {
result.push(" Helper NP");
}
if (helperRendererPlist != null) {
result.push(" Helper (Renderer)");
}
if (helperPluginPlist != null) {
result.push(" Helper (Plugin)");
}
if (helperGPUPlist != null) {
result.push(" Helper (GPU)");
}
return result;
}
/** @internal */
async function createMacApp(packager, appOutDir, asarIntegrity, isMas) {
var _a, _b;
const appInfo = packager.appInfo;
// Electon uses the application name (CFBundleName) to resolve helper apps
// https://github.com/electron/electron/blob/main/shell/app/electron_main_delegate_mac.mm
// https://github.com/electron-userland/electron-builder/issues/6962
const appFilename = appInfo.sanitizedProductName;
const electronBranding = (0, ElectronFramework_1.createBrandingOpts)(packager.config);
const contentsPath = path.join(appOutDir, packager.info.framework.distMacOsAppName, "Contents");
const frameworksPath = path.join(contentsPath, "Frameworks");
const loginItemPath = path.join(contentsPath, "Library", "LoginItems");
const appPlistFilename = path.join(contentsPath, "Info.plist");
const helperPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper.app`, "Contents", "Info.plist");
const helperEHPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper EH.app`, "Contents", "Info.plist");
const helperNPPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper NP.app`, "Contents", "Info.plist");
const helperRendererPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper (Renderer).app`, "Contents", "Info.plist");
const helperPluginPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper (Plugin).app`, "Contents", "Info.plist");
const helperGPUPlistFilename = path.join(frameworksPath, `${electronBranding.productName} Helper (GPU).app`, "Contents", "Info.plist");
const helperLoginPlistFilename = path.join(loginItemPath, `${electronBranding.productName} Login Helper.app`, "Contents", "Info.plist");
const safeParsePlistFile = async (filePath) => {
if (!fs.existsSync(filePath)) {
return null;
}
return await (0, plist_1.parsePlistFile)(filePath);
};
const appPlist = (await safeParsePlistFile(appPlistFilename));
if (appPlist == null) {
throw new Error("corrupted Electron dist");
}
// Replace the multiple parsePlistFile calls with:
const helperPlist = await safeParsePlistFile(helperPlistFilename);
const helperEHPlist = await safeParsePlistFile(helperEHPlistFilename);
const helperNPPlist = await safeParsePlistFile(helperNPPlistFilename);
const helperRendererPlist = await safeParsePlistFile(helperRendererPlistFilename);
const helperPluginPlist = await safeParsePlistFile(helperPluginPlistFilename);
const helperGPUPlist = await safeParsePlistFile(helperGPUPlistFilename);
const helperLoginPlist = await safeParsePlistFile(helperLoginPlistFilename);
const buildMetadata = packager.config;
/**
* Configure bundleIdentifier for the generic Electron Helper process
*
* This was the only Helper in Electron 5 and before. Allow users to configure
* the bundleIdentifier for continuity.
*/
const oldHelperBundleId = buildMetadata["helper-bundle-id"];
if (oldHelperBundleId != null) {
builder_util_1.log.warn("build.helper-bundle-id is deprecated, please set as build.mac.helperBundleId");
}
const defaultAppId = packager.platformSpecificBuildOptions.appId;
const cfBundleIdentifier = (0, appInfo_1.filterCFBundleIdentifier)((isMas ? (_a = packager.config.mas) === null || _a === void 0 ? void 0 : _a.appId : defaultAppId) || defaultAppId || appInfo.macBundleIdentifier);
const defaultHelperId = packager.platformSpecificBuildOptions.helperBundleId;
const helperBundleIdentifier = (0, appInfo_1.filterCFBundleIdentifier)((isMas ? (_b = packager.config.mas) === null || _b === void 0 ? void 0 : _b.helperBundleId : defaultHelperId) || defaultHelperId || oldHelperBundleId || `${cfBundleIdentifier}.helper`);
appPlist.CFBundleIdentifier = cfBundleIdentifier;
await packager.applyCommonInfo(appPlist, contentsPath);
// required for electron-updater proxy
if (!isMas) {
configureLocalhostAts(appPlist);
}
if (helperPlist != null) {
helperPlist.CFBundleExecutable = `${appFilename} Helper`;
helperPlist.CFBundleDisplayName = `${appInfo.productName} Helper`;
helperPlist.CFBundleIdentifier = helperBundleIdentifier;
helperPlist.CFBundleVersion = appPlist.CFBundleVersion;
}
/**
* Configure bundleIdentifier for Electron 5+ Helper processes
*
* In Electron 6, parts of the generic Electron Helper process were split into
* individual helper processes. Allow users to configure the bundleIdentifiers
* for continuity, specifically because macOS keychain access relies on
* bundleIdentifiers not changing (i.e. across versions of Electron).
*/
function configureHelper(helper, postfix, userProvidedBundleIdentifier) {
helper.CFBundleExecutable = `${appFilename} Helper ${postfix}`;
helper.CFBundleDisplayName = `${appInfo.productName} Helper ${postfix}`;
helper.CFBundleIdentifier = userProvidedBundleIdentifier
? (0, appInfo_1.filterCFBundleIdentifier)(userProvidedBundleIdentifier)
: (0, appInfo_1.filterCFBundleIdentifier)(`${helperBundleIdentifier}.${postfix}`);
helper.CFBundleVersion = appPlist.CFBundleVersion;
}
if (helperRendererPlist != null) {
configureHelper(helperRendererPlist, "(Renderer)", packager.platformSpecificBuildOptions.helperRendererBundleId);
}
if (helperPluginPlist != null) {
configureHelper(helperPluginPlist, "(Plugin)", packager.platformSpecificBuildOptions.helperPluginBundleId);
}
if (helperGPUPlist != null) {
configureHelper(helperGPUPlist, "(GPU)", packager.platformSpecificBuildOptions.helperGPUBundleId);
}
if (helperEHPlist != null) {
configureHelper(helperEHPlist, "EH", packager.platformSpecificBuildOptions.helperEHBundleId);
}
if (helperNPPlist != null) {
configureHelper(helperNPPlist, "NP", packager.platformSpecificBuildOptions.helperNPBundleId);
}
if (helperLoginPlist != null) {
helperLoginPlist.CFBundleExecutable = `${appFilename} Login Helper`;
helperLoginPlist.CFBundleDisplayName = `${appInfo.productName} Login Helper`;
// noinspection SpellCheckingInspection
helperLoginPlist.CFBundleIdentifier = `${cfBundleIdentifier}.loginhelper`;
helperLoginPlist.CFBundleVersion = appPlist.CFBundleVersion;
}
const protocols = (0, builder_util_1.asArray)(buildMetadata.protocols).concat((0, builder_util_1.asArray)(packager.platformSpecificBuildOptions.protocols));
if (protocols.length > 0) {
appPlist.CFBundleURLTypes = protocols.map(protocol => {
const schemes = (0, builder_util_1.asArray)(protocol.schemes);
if (schemes.length === 0) {
throw new builder_util_1.InvalidConfigurationError(`Protocol "${protocol.name}": must be at least one scheme specified`);
}
return {
CFBundleURLName: protocol.name,
CFBundleTypeRole: protocol.role || "Editor",
CFBundleURLSchemes: schemes.slice(),
};
});
}
const fileAssociations = packager.fileAssociations;
if (fileAssociations.length > 0) {
const documentTypes = await Promise.all(fileAssociations.map(async (fileAssociation) => {
const extensions = (0, builder_util_1.asArray)(fileAssociation.ext).map(platformPackager_1.normalizeExt);
const customIcon = await packager.getResource((0, builder_util_1.getPlatformIconFileName)(fileAssociation.icon, true), `${extensions[0]}.icns`);
let iconFile = appPlist.CFBundleIconFile;
if (customIcon != null) {
iconFile = path.basename(customIcon);
await (0, builder_util_1.copyOrLinkFile)(customIcon, path.join(path.join(contentsPath, "Resources"), iconFile));
}
const result = {
CFBundleTypeExtensions: extensions,
CFBundleTypeName: fileAssociation.name || extensions[0],
CFBundleTypeRole: fileAssociation.role || "Editor",
LSHandlerRank: fileAssociation.rank || "Default",
CFBundleTypeIconFile: iconFile,
};
if (fileAssociation.isPackage) {
result.LSTypeIsPackage = true;
}
return result;
}));
// `CFBundleDocumentTypes` may be defined in `mac.extendInfo`, so we need to merge it in that case
appPlist.CFBundleDocumentTypes = [...(appPlist.CFBundleDocumentTypes || []), ...documentTypes];
}
const toPlistObject = (asarIntegrity) => {
const result = {};
for (const [filePath, headerHash] of Object.entries(asarIntegrity)) {
result[filePath] = {
algorithm: headerHash.algorithm,
hash: headerHash.hash,
};
}
return result;
};
if (asarIntegrity != null) {
appPlist.ElectronAsarIntegrity = toPlistObject(asarIntegrity);
}
if (helperEHPlist != null) {
await (0, plist_1.savePlistFile)(helperEHPlistFilename, helperEHPlist);
}
if (helperNPPlist != null) {
await (0, plist_1.savePlistFile)(helperNPPlistFilename, helperNPPlist);
}
if (helperRendererPlist != null) {
await (0, plist_1.savePlistFile)(helperRendererPlistFilename, helperRendererPlist);
}
if (helperPluginPlist != null) {
await (0, plist_1.savePlistFile)(helperPluginPlistFilename, helperPluginPlist);
}
if (helperGPUPlist != null) {
await (0, plist_1.savePlistFile)(helperGPUPlistFilename, helperGPUPlist);
}
if (helperLoginPlist != null) {
await (0, plist_1.savePlistFile)(helperLoginPlistFilename, helperLoginPlist);
}
await (0, plist_1.savePlistFile)(appPlistFilename, appPlist);
if (helperPlist != null) {
await (0, plist_1.savePlistFile)(helperPlistFilename, helperPlist);
}
await Promise.all([
doRename(path.join(contentsPath, "MacOS"), electronBranding.productName, appPlist.CFBundleExecutable),
(0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSE")),
(0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSES.chromium.html")),
]);
await moveHelpers(getAvailableHelperSuffixes(helperEHPlist, helperNPPlist, helperRendererPlist, helperPluginPlist, helperGPUPlist), frameworksPath, appFilename, electronBranding.productName);
if (helperLoginPlist != null) {
const prefix = electronBranding.productName;
const suffix = " Login Helper";
const executableBasePath = path.join(loginItemPath, `${prefix}${suffix}.app`, "Contents", "MacOS");
await doRename(executableBasePath, `${prefix}${suffix}`, appFilename + suffix).then(() => doRename(loginItemPath, `${prefix}${suffix}.app`, `${appFilename}${suffix}.app`));
}
const appPath = path.join(appOutDir, `${appInfo.productFilename}.app`);
await (0, promises_1.rename)(path.dirname(contentsPath), appPath);
// https://github.com/electron-userland/electron-builder/issues/840
const now = Date.now() / 1000;
await (0, promises_1.utimes)(appPath, now, now);
}
function configureLocalhostAts(appPlist) {
// https://bencoding.com/2015/07/20/app-transport-security-and-localhost/
let ats = appPlist.NSAppTransportSecurity;
if (ats == null) {
ats = {};
appPlist.NSAppTransportSecurity = ats;
}
ats.NSAllowsLocalNetworking = true;
// https://github.com/electron-userland/electron-builder/issues/3377#issuecomment-446035814
ats.NSAllowsArbitraryLoads = true;
let exceptionDomains = ats.NSExceptionDomains;
if (exceptionDomains == null) {
exceptionDomains = {};
ats.NSExceptionDomains = exceptionDomains;
}
if (exceptionDomains.localhost == null) {
const allowHttp = {
NSTemporaryExceptionAllowsInsecureHTTPSLoads: false,
NSIncludesSubdomains: false,
NSTemporaryExceptionAllowsInsecureHTTPLoads: true,
NSTemporaryExceptionMinimumTLSVersion: "1.0",
NSTemporaryExceptionRequiresForwardSecrecy: false,
};
exceptionDomains.localhost = allowHttp;
exceptionDomains["127.0.0.1"] = allowHttp;
}
}
//# sourceMappingURL=electronMac.js.map
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
import { Lazy } from "lazy-val";
import { Configuration } from "../configuration";
export type MetadataValue = Lazy<Record<string, any> | null>;
export declare function getElectronVersion(projectDir: string, config?: Configuration): Promise<string>;
export declare function getElectronVersionFromInstalled(projectDir: string): Promise<string | null>;
export declare function getElectronPackage(projectDir: string): Promise<any>;
+120
View File
@@ -0,0 +1,120 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getElectronVersion = getElectronVersion;
exports.getElectronVersionFromInstalled = getElectronVersionFromInstalled;
exports.getElectronPackage = getElectronPackage;
exports.computeElectronVersion = computeElectronVersion;
const builder_util_1 = require("builder-util");
const builder_util_runtime_1 = require("builder-util-runtime");
const fs_extra_1 = require("fs-extra");
const path = require("path");
const semver = require("semver");
const config_1 = require("../util/config/config");
const load_1 = require("../util/config/load");
const search_module_1 = require("./search-module");
const electronPackages = ["electron", "electron-prebuilt", "electron-prebuilt-compile", "electron-nightly"];
async function getElectronVersion(projectDir, config) {
if (config == null) {
config = await (0, config_1.getConfig)(projectDir, null, null);
}
if (config.electronVersion != null) {
return config.electronVersion;
}
return computeElectronVersion(projectDir);
}
async function getElectronVersionFromInstalled(projectDir) {
for (const name of electronPackages) {
try {
return (await (0, fs_extra_1.readJson)(path.join(projectDir, "node_modules", name, "package.json"))).version;
}
catch (e) {
if (e.code !== "ENOENT") {
builder_util_1.log.warn({ name, error: e }, `cannot read electron version package.json`);
}
}
}
return null;
}
async function getElectronPackage(projectDir) {
for (const name of electronPackages) {
try {
return await (0, fs_extra_1.readJson)(path.join(projectDir, "node_modules", name, "package.json"));
}
catch (e) {
if (e.code !== "ENOENT") {
builder_util_1.log.warn({ name, error: e }, `cannot find electron in package.json`);
}
}
}
return null;
}
/** @internal */
async function computeElectronVersion(projectDir) {
const result = await getElectronVersionFromInstalled(projectDir);
if (result != null) {
return result;
}
const potentialRootDirs = [projectDir, await (0, search_module_1.getProjectRootPath)(projectDir)];
let dependency = null;
for (const dir of potentialRootDirs) {
const metadata = await (0, load_1.orNullIfFileNotExist)((0, fs_extra_1.readJson)(path.join(dir, "package.json")));
dependency = metadata ? findFromPackageMetadata(metadata) : null;
if (dependency) {
break;
}
}
if ((dependency === null || dependency === void 0 ? void 0 : dependency.name) === "electron-nightly") {
builder_util_1.log.info("You are using a nightly version of electron, be warned that those builds are highly unstable.");
const feedXml = await builder_util_1.httpExecutor.request({
hostname: "github.com",
path: `/electron/nightlies/releases.atom`,
headers: {
accept: "application/xml, application/atom+xml, text/xml, */*",
},
});
const feed = (0, builder_util_runtime_1.parseXml)(feedXml);
const latestRelease = feed.element("entry", false, `No published versions on GitHub`);
const v = /\/tag\/v?([^/]+)$/.exec(latestRelease.element("link").attribute("href"))[1];
return v.startsWith("v") ? v.substring(1) : v;
}
else if ((dependency === null || dependency === void 0 ? void 0 : dependency.version) === "latest") {
builder_util_1.log.warn('Electron version is set to "latest", but it is recommended to set it to some more restricted version range.');
try {
const releaseInfo = JSON.parse((await builder_util_1.httpExecutor.request({
hostname: "github.com",
path: `/electron/${dependency.name === "electron-nightly" ? "nightlies" : "electron"}/releases/latest`,
headers: {
accept: "application/json",
},
})));
const version = releaseInfo.tag_name.startsWith("v") ? releaseInfo.tag_name.substring(1) : releaseInfo.tag_name;
builder_util_1.log.info({ version }, `resolve ${dependency.name}@${dependency.version}`);
return version;
}
catch (e) {
builder_util_1.log.warn(e);
}
throw new builder_util_1.InvalidConfigurationError(`Cannot find electron dependency to get electron version in the '${path.join(projectDir, "package.json")}'`);
}
const version = dependency === null || dependency === void 0 ? void 0 : dependency.version;
if (version == null || !/^\d/.test(version)) {
const versionMessage = version == null ? "" : ` and version ("${version}") is not fixed in project`;
throw new builder_util_1.InvalidConfigurationError(`Cannot compute electron version from installed node modules - none of the possible electron modules are installed${versionMessage}.\nSee https://github.com/electron-userland/electron-builder/issues/3984#issuecomment-504968246`);
}
return semver.coerce(version).format();
}
function findFromPackageMetadata(packageData) {
for (const name of electronPackages) {
const devDependencies = packageData.devDependencies;
let dep = devDependencies == null ? null : devDependencies[name];
if (dep == null) {
const dependencies = packageData.dependencies;
dep = dependencies == null ? null : dependencies[name];
}
if (dep != null) {
return { name, version: dep };
}
}
return null;
}
//# sourceMappingURL=electronVersion.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export {};
+38
View File
@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addWinAsarIntegrity = addWinAsarIntegrity;
const builder_util_1 = require("builder-util");
const promises_1 = require("fs/promises");
const path = require("path");
const resedit_1 = require("resedit");
/** @internal */
async function addWinAsarIntegrity(executablePath, asarIntegrity) {
const buffer = await (0, promises_1.readFile)(executablePath);
const executable = resedit_1.NtExecutable.from(buffer);
const resource = resedit_1.NtExecutableResource.from(executable);
const versionInfo = resedit_1.Resource.VersionInfo.fromEntries(resource.entries);
if (versionInfo.length !== 1) {
throw new Error(`Failed to parse version info in ${executablePath}`);
}
const languages = versionInfo[0].getAllLanguagesForStringValues();
if (languages.length !== 1) {
throw new Error(`Failed to locate languages in ${executablePath}`);
}
// See: https://github.com/electron/packager/blob/00d20b99cf4aa4621103dbbd09ff7de7d2f7f539/src/resedit.ts#L124
const integrityList = Array.from(Object.entries(asarIntegrity)).map(([file, { algorithm: alg, hash: value }]) => ({
file: path.win32.normalize(file),
alg,
value,
}));
resource.entries.push({
type: "INTEGRITY",
id: "ELECTRONASAR",
bin: Buffer.from(JSON.stringify(integrityList)),
lang: languages[0].lang,
codepage: languages[0].codepage,
});
resource.outputResource(executable);
await (0, promises_1.writeFile)(executablePath, Buffer.from(executable.generate()));
builder_util_1.log.info({ executablePath: builder_util_1.log.filePath(executablePath) }, "updating asar integrity executable resource");
}
//# sourceMappingURL=electronWin.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"electronWin.js","sourceRoot":"","sources":["../../src/electron/electronWin.ts"],"names":[],"mappings":";;AAOA,kDAkCC;AAzCD,+CAAkC;AAClC,0CAAiD;AACjD,6BAA4B;AAC5B,qCAAsE;AAGtE,gBAAgB;AACT,KAAK,UAAU,mBAAmB,CAAC,cAAsB,EAAE,aAA4B;IAC5F,MAAM,MAAM,GAAG,MAAM,IAAA,mBAAQ,EAAC,cAAc,CAAC,CAAA;IAC7C,MAAM,UAAU,GAAG,sBAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAC5C,MAAM,QAAQ,GAAG,8BAAoB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;IAEtD,MAAM,WAAW,GAAG,kBAAQ,CAAC,WAAW,CAAC,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;IACtE,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,mCAAmC,cAAc,EAAE,CAAC,CAAA;IACtE,CAAC;IAED,MAAM,SAAS,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,8BAA8B,EAAE,CAAA;IACjE,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,iCAAiC,cAAc,EAAE,CAAC,CAAA;IACpE,CAAC;IAED,8GAA8G;IAC9G,MAAM,aAAa,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAChH,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC;QAChC,GAAG;QACH,KAAK;KACN,CAAC,CAAC,CAAA;IAEH,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;QACpB,IAAI,EAAE,WAAW;QACjB,EAAE,EAAE,cAAc;QAClB,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;QAC/C,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI;QACvB,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,QAAQ;KAChC,CAAC,CAAA;IAEF,QAAQ,CAAC,cAAc,CAAC,UAAU,CAAC,CAAA;IAEnC,MAAM,IAAA,oBAAS,EAAC,cAAc,EAAE,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;IACnE,kBAAG,CAAC,IAAI,CAAC,EAAE,cAAc,EAAE,kBAAG,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,EAAE,6CAA6C,CAAC,CAAA;AAC3G,CAAC","sourcesContent":["import { log } from \"builder-util\"\nimport { readFile, writeFile } from \"fs/promises\"\nimport * as path from \"path\"\nimport { NtExecutable, NtExecutableResource, Resource } from \"resedit\"\nimport { AsarIntegrity } from \"../asar/integrity\"\n\n/** @internal */\nexport async function addWinAsarIntegrity(executablePath: string, asarIntegrity: AsarIntegrity) {\n const buffer = await readFile(executablePath)\n const executable = NtExecutable.from(buffer)\n const resource = NtExecutableResource.from(executable)\n\n const versionInfo = Resource.VersionInfo.fromEntries(resource.entries)\n if (versionInfo.length !== 1) {\n throw new Error(`Failed to parse version info in ${executablePath}`)\n }\n\n const languages = versionInfo[0].getAllLanguagesForStringValues()\n if (languages.length !== 1) {\n throw new Error(`Failed to locate languages in ${executablePath}`)\n }\n\n // See: https://github.com/electron/packager/blob/00d20b99cf4aa4621103dbbd09ff7de7d2f7f539/src/resedit.ts#L124\n const integrityList = Array.from(Object.entries(asarIntegrity)).map(([file, { algorithm: alg, hash: value }]) => ({\n file: path.win32.normalize(file),\n alg,\n value,\n }))\n\n resource.entries.push({\n type: \"INTEGRITY\",\n id: \"ELECTRONASAR\",\n bin: Buffer.from(JSON.stringify(integrityList)),\n lang: languages[0].lang,\n codepage: languages[0].codepage,\n })\n\n resource.outputResource(executable)\n\n await writeFile(executablePath, Buffer.from(executable.generate()))\n log.info({ executablePath: log.filePath(executablePath) }, \"updating asar integrity executable resource\")\n}\n"]}
+2
View File
@@ -0,0 +1,2 @@
import { PrepareApplicationStageDirectoryOptions } from "../Framework";
export default function injectFFMPEG(options: PrepareApplicationStageDirectoryOptions, electrionVersion: string): Promise<string>;
+43
View File
@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = injectFFMPEG;
const fs = require("fs");
const path = require("path");
const builder_util_1 = require("builder-util");
const binDownload_1 = require("../binDownload");
// NOTE: Adapted from https://github.com/MarshallOfSound/electron-packager-plugin-non-proprietary-codecs-ffmpeg to resolve dependency vulnerabilities
const downloadFFMPEG = async (electronVersion, platform, arch) => {
const ffmpegFileName = `ffmpeg-v${electronVersion}-${platform}-${arch}.zip`;
const url = `https://github.com/electron/electron/releases/download/v${electronVersion}/${ffmpegFileName}`;
builder_util_1.log.info({ file: ffmpegFileName }, "downloading non-proprietary FFMPEG");
return (0, binDownload_1.getBin)(ffmpegFileName, url);
};
const copyFFMPEG = (targetPath, platform) => (sourcePath) => {
let fileName = "ffmpeg.dll";
if (["darwin", "mas"].includes(platform)) {
fileName = "libffmpeg.dylib";
}
else if (platform === "linux") {
fileName = "libffmpeg.so";
}
const libPath = path.resolve(sourcePath, fileName);
const libTargetPath = path.resolve(targetPath, fileName);
builder_util_1.log.info({ lib: builder_util_1.log.filePath(libPath), target: builder_util_1.log.filePath(libTargetPath) }, "copying non-proprietary FFMPEG");
// If the source doesn't exist we have a problem
if (!fs.existsSync(libPath)) {
throw new Error(`Failed to find FFMPEG library file at path: ${libPath}`);
}
// If we are copying to the source we can stop immediately
if (libPath !== libTargetPath) {
fs.copyFileSync(libPath, libTargetPath);
}
return libTargetPath;
};
function injectFFMPEG(options, electrionVersion) {
let libPath = options.appOutDir;
if (options.platformName === "darwin") {
libPath = path.resolve(options.appOutDir, "Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries");
}
return downloadFFMPEG(electrionVersion, options.platformName, options.arch).then(copyFFMPEG(libPath, options.platformName));
}
//# sourceMappingURL=injectFFMPEG.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"injectFFMPEG.js","sourceRoot":"","sources":["../../src/electron/injectFFMPEG.ts"],"names":[],"mappings":";;AAyCA,+BAOC;AAhDD,yBAAwB;AACxB,6BAA4B;AAG5B,+CAAkC;AAClC,gDAAuC;AAGvC,qJAAqJ;AACrJ,MAAM,cAAc,GAAG,KAAK,EAAE,eAAuB,EAAE,QAA8B,EAAE,IAAY,EAAE,EAAE;IACrG,MAAM,cAAc,GAAG,WAAW,eAAe,IAAI,QAAQ,IAAI,IAAI,MAAM,CAAA;IAC3E,MAAM,GAAG,GAAG,2DAA2D,eAAe,IAAI,cAAc,EAAE,CAAA;IAE1G,kBAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,oCAAoC,CAAC,CAAA;IACxE,OAAO,IAAA,oBAAM,EAAC,cAAc,EAAE,GAAG,CAAC,CAAA;AACpC,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,UAAkB,EAAE,QAA8B,EAAE,EAAE,CAAC,CAAC,UAAkB,EAAE,EAAE;IAChG,IAAI,QAAQ,GAAG,YAAY,CAAA;IAC3B,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QACzC,QAAQ,GAAG,iBAAiB,CAAA;IAC9B,CAAC;SAAM,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;QAChC,QAAQ,GAAG,cAAc,CAAA;IAC3B,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAA;IAClD,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAA;IACxD,kBAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,kBAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,kBAAG,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,EAAE,gCAAgC,CAAC,CAAA;IAE/G,gDAAgD;IAChD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,+CAA+C,OAAO,EAAE,CAAC,CAAA;IAC3E,CAAC;IAED,0DAA0D;IAC1D,IAAI,OAAO,KAAK,aAAa,EAAE,CAAC;QAC9B,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,aAAa,CAAC,CAAA;IACzC,CAAC;IACD,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA;AAED,SAAwB,YAAY,CAAC,OAAgD,EAAE,gBAAwB;IAC7G,IAAI,OAAO,GAAG,OAAO,CAAC,SAAS,CAAA;IAC/B,IAAI,OAAO,CAAC,YAAY,KAAK,QAAQ,EAAE,CAAC;QACtC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,oFAAoF,CAAC,CAAA;IACjI,CAAC;IAED,OAAO,cAAc,CAAC,gBAAgB,EAAE,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,CAAA;AAC7H,CAAC","sourcesContent":["import * as fs from \"fs\"\nimport * as path from \"path\"\nimport { ElectronPlatformName } from \"./ElectronFramework\"\n\nimport { log } from \"builder-util\"\nimport { getBin } from \"../binDownload\"\nimport { PrepareApplicationStageDirectoryOptions } from \"../Framework\"\n\n// NOTE: Adapted from https://github.com/MarshallOfSound/electron-packager-plugin-non-proprietary-codecs-ffmpeg to resolve dependency vulnerabilities\nconst downloadFFMPEG = async (electronVersion: string, platform: ElectronPlatformName, arch: string) => {\n const ffmpegFileName = `ffmpeg-v${electronVersion}-${platform}-${arch}.zip`\n const url = `https://github.com/electron/electron/releases/download/v${electronVersion}/${ffmpegFileName}`\n\n log.info({ file: ffmpegFileName }, \"downloading non-proprietary FFMPEG\")\n return getBin(ffmpegFileName, url)\n}\n\nconst copyFFMPEG = (targetPath: string, platform: ElectronPlatformName) => (sourcePath: string) => {\n let fileName = \"ffmpeg.dll\"\n if ([\"darwin\", \"mas\"].includes(platform)) {\n fileName = \"libffmpeg.dylib\"\n } else if (platform === \"linux\") {\n fileName = \"libffmpeg.so\"\n }\n\n const libPath = path.resolve(sourcePath, fileName)\n const libTargetPath = path.resolve(targetPath, fileName)\n log.info({ lib: log.filePath(libPath), target: log.filePath(libTargetPath) }, \"copying non-proprietary FFMPEG\")\n\n // If the source doesn't exist we have a problem\n if (!fs.existsSync(libPath)) {\n throw new Error(`Failed to find FFMPEG library file at path: ${libPath}`)\n }\n\n // If we are copying to the source we can stop immediately\n if (libPath !== libTargetPath) {\n fs.copyFileSync(libPath, libTargetPath)\n }\n return libTargetPath\n}\n\nexport default function injectFFMPEG(options: PrepareApplicationStageDirectoryOptions, electrionVersion: string) {\n let libPath = options.appOutDir\n if (options.platformName === \"darwin\") {\n libPath = path.resolve(options.appOutDir, \"Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries\")\n }\n\n return downloadFFMPEG(electrionVersion, options.platformName, options.arch).then(copyFFMPEG(libPath, options.platformName))\n}\n"]}
+23
View File
@@ -0,0 +1,23 @@
/**
* Find all instances of a given module in node_modules subdirectories while traversing up
* ancestor directories.
*
* @param cwd the initial directory to traverse
* @param moduleName the Node module name (should work for scoped modules as well)
* @param rootPath the project's root path. If provided, the traversal will stop at this path.
*/
export declare function searchForModule(cwd: string, moduleName: string, rootPath?: string): Promise<string[]>;
/**
* Find all instances of node_modules subdirectories while traversing up ancestor directories.
*
* @param cwd the initial directory to traverse
* @param rootPath the project's root path. If provided, the traversal will stop at this path.
*/
export declare function searchForNodeModules(cwd: string, rootPath?: string): Promise<string[]>;
/**
* Determine the root directory of a given project, by looking for a directory with an
* NPM or yarn lockfile or pnpm lockfile.
*
* @param cwd the initial directory to traverse
*/
export declare function getProjectRootPath(cwd: string): Promise<string>;
+73
View File
@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.searchForModule = searchForModule;
exports.searchForNodeModules = searchForNodeModules;
exports.getProjectRootPath = getProjectRootPath;
const fs = require("fs-extra");
const path = require("node:path");
async function shouldContinueSearch(traversedPath, rootPath, stopAtPackageJSON) {
if (rootPath) {
return Promise.resolve(traversedPath !== path.dirname(rootPath));
}
else if (stopAtPackageJSON) {
return fs.existsSync(path.join(traversedPath, "package.json"));
}
else {
return true;
}
}
async function traverseAncestorDirectories(cwd, pathGenerator, rootPath, maxItems, stopAtPackageJSON) {
const paths = [];
let traversedPath = path.resolve(cwd);
while (await shouldContinueSearch(traversedPath, rootPath, stopAtPackageJSON)) {
const generatedPath = pathGenerator(traversedPath);
if (fs.existsSync(generatedPath)) {
paths.push(generatedPath);
}
const parentPath = path.dirname(traversedPath);
if (parentPath === traversedPath || (maxItems && paths.length >= maxItems)) {
break;
}
traversedPath = parentPath;
}
return paths;
}
/**
* Find all instances of a given module in node_modules subdirectories while traversing up
* ancestor directories.
*
* @param cwd the initial directory to traverse
* @param moduleName the Node module name (should work for scoped modules as well)
* @param rootPath the project's root path. If provided, the traversal will stop at this path.
*/
async function searchForModule(cwd, moduleName, rootPath) {
const pathGenerator = traversedPath => path.join(traversedPath, "node_modules", moduleName);
return traverseAncestorDirectories(cwd, pathGenerator, rootPath, undefined, true);
}
/**
* Find all instances of node_modules subdirectories while traversing up ancestor directories.
*
* @param cwd the initial directory to traverse
* @param rootPath the project's root path. If provided, the traversal will stop at this path.
*/
async function searchForNodeModules(cwd, rootPath) {
const pathGenerator = traversedPath => path.join(traversedPath, "node_modules");
return traverseAncestorDirectories(cwd, pathGenerator, rootPath, undefined, true);
}
/**
* Determine the root directory of a given project, by looking for a directory with an
* NPM or yarn lockfile or pnpm lockfile.
*
* @param cwd the initial directory to traverse
*/
async function getProjectRootPath(cwd) {
for (const lockFilename of ["yarn.lock", "package-lock.json", "pnpm-lock.yaml", "bun.lock", "bun.lockb"]) {
const pathGenerator = traversedPath => path.join(traversedPath, lockFilename);
const lockPaths = await traverseAncestorDirectories(cwd, pathGenerator, undefined, 1);
if (lockPaths.length > 0) {
return path.dirname(lockPaths[0]);
}
}
return cwd;
}
//# sourceMappingURL=search-module.js.map
File diff suppressed because one or more lines are too long