Skip to content

Commit dd8f866

Browse files
Fix getting production dependencies code (#2789)
* Fix getting production dependencies code CLI has logic to find which are the "production" dependencies, i.e. which should be copied from `node_modules` to `platforms` dir. However, when the project has a lot of dependencies (more than 15), on some machines the code leads to error: "Maximum callstack size exceeded". On other machines the code tooks significant time to execute. After investigation, it turned out the recursion inside `node-modules-dependencies-builder` is incorrect and it adds each package many times to the result array. Fix the recursion and change the class NodeModulesDependenciesBuilder to be stateless - instead of using properties in `this` object when calculating the production dependencies, the methods will persist the results through the passed args. This way the whole class can be safely added to `$injector` and used whenever we need the production dependencies. Each time the calculation is started from the beginning, which is the requirement for long living process, where the project may change. Fix the type of the result, which leads to fix in several other services, where the result has been expected as `IDictionary<smth>`. However it's never been dictionary, it's always been an array. The code, that expected dictionary has been working because the `_.values` method of lodash (used all over the places where the incorrect type of data has been expected), returns the same array when the passed argument is array. Fix the tests that incorrectly expected dictionary with keys "0", "1", "2", etc. Remove the usage of Node.js's `fs` module from `NodeModulesDependenciesBuilder` - replace it with `$fs` which allows easir writing of tests. Require the `nodeModulesDependenciesBuilder` in bootstrap, so it can be correctly resolved by `$injector`. Add unit tests for `nodeModulesDependenciesBuilder`. * Use breadth-first search for getting production dependencies Replace the recursion with breadth-first search algorithm in order to make the code easier for understanding and debugging. Fix some incorrect code in the tests. * Add checks before adding new elements to queue of production dependencies Add check before adding new elements to queue of production dependencies - do not add elements, which are already added and do not read package.json of elements that are already added to "resolvedModules".
1 parent 2124b88 commit dd8f866

15 files changed

+477
-125
lines changed

lib/bootstrap.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,5 @@ $injector.requireCommand("extension|*list", "./commands/extensibility/list-exten
135135
$injector.requireCommand("extension|install", "./commands/extensibility/install-extension");
136136
$injector.requireCommand("extension|uninstall", "./commands/extensibility/uninstall-extension");
137137
$injector.requirePublic("extensibilityService", "./services/extensibility-service");
138+
139+
$injector.require("nodeModulesDependenciesBuilder", "./tools/node-modules/node-modules-dependencies-builder");

lib/common

lib/declarations.d.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,12 +202,36 @@ interface INpmInstallOptions {
202202
dependencyType?: string;
203203
}
204204

205+
/**
206+
* Describes npm package installed in node_modules.
207+
*/
205208
interface IDependencyData {
209+
/**
210+
* The name of the package.
211+
*/
206212
name: string;
207-
version: string;
208-
nativescript: any;
209-
dependencies?: IStringDictionary;
210-
devDependencies?: IStringDictionary;
213+
214+
/**
215+
* The full path where the package is installed.
216+
*/
217+
directory: string;
218+
219+
/**
220+
* The depth inside node_modules dir, where the package is located.
221+
* The <project_dir>/node_modules/ is level 0.
222+
* Level 1 is <project dir>/node_modules/<package name>/node_modules, etc.
223+
*/
224+
depth: number;
225+
226+
/**
227+
* Describes the `nativescript` key in package.json of a dependency.
228+
*/
229+
nativescript?: any;
230+
231+
/**
232+
* Dependencies of the current module.
233+
*/
234+
dependencies?: string[];
211235
}
212236

213237
interface IStaticConfig extends Config.IStaticConfig { }

lib/definitions/platform.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ interface INodeModulesBuilder {
275275
}
276276

277277
interface INodeModulesDependenciesBuilder {
278-
getProductionDependencies(projectPath: string): void;
278+
getProductionDependencies(projectPath: string): IDependencyData[];
279279
}
280280

281281
interface IBuildInfo {

lib/definitions/project.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ interface IPlatformProjectService extends NodeJS.EventEmitter {
225225
removePluginNativeCode(pluginData: IPluginData, projectData: IProjectData): Promise<void>;
226226

227227
afterPrepareAllPlugins(projectData: IProjectData): Promise<void>;
228-
beforePrepareAllPlugins(projectData: IProjectData, dependencies?: IDictionary<IDependencyData>): Promise<void>;
228+
beforePrepareAllPlugins(projectData: IProjectData, dependencies?: IDependencyData[]): Promise<void>;
229229

230230
/**
231231
* Gets the path wheren App_Resources should be copied.

lib/services/android-project-service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ export class AndroidProjectService extends projectServiceBaseLib.PlatformProject
400400
return;
401401
}
402402

403-
public async beforePrepareAllPlugins(projectData: IProjectData, dependencies?: IDictionary<IDependencyData>): Promise<void> {
403+
public async beforePrepareAllPlugins(projectData: IProjectData, dependencies?: IDependencyData[]): Promise<void> {
404404
if (!this.$config.debugLivesync) {
405405
if (dependencies) {
406406
let platformDir = path.join(projectData.platformsDir, "android");

lib/services/livesync/livesync-service.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import * as constants from "../../constants";
22
import * as helpers from "../../common/helpers";
33
import * as path from "path";
4-
import { NodeModulesDependenciesBuilder } from "../../tools/node-modules/node-modules-dependencies-builder";
54

65
let choki = require("chokidar");
76

@@ -17,7 +16,8 @@ class LiveSyncService implements ILiveSyncService {
1716
private $logger: ILogger,
1817
private $dispatcher: IFutureDispatcher,
1918
private $hooksService: IHooksService,
20-
private $processService: IProcessService) { }
19+
private $processService: IProcessService,
20+
private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder) { }
2121

2222
public get isInitialized(): boolean { // This function is used from https://github.com/NativeScript/nativescript-dev-typescript/blob/master/lib/before-prepare.js#L4
2323
return this._isInitialized;
@@ -94,8 +94,7 @@ class LiveSyncService implements ILiveSyncService {
9494

9595
private partialSync(syncWorkingDirectory: string, onChangedActions: ((event: string, filePath: string, dispatcher: IFutureDispatcher) => Promise<void>)[], projectData: IProjectData): void {
9696
let that = this;
97-
let dependenciesBuilder = this.$injector.resolve(NodeModulesDependenciesBuilder, {});
98-
let productionDependencies = dependenciesBuilder.getProductionDependencies(projectData.projectDir);
97+
let productionDependencies = this.$nodeModulesDependenciesBuilder.getProductionDependencies(projectData.projectDir);
9998
let pattern = ["app"];
10099

101100
if (this.$options.syncAllFiles) {

lib/tools/node-modules/node-modules-builder.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import * as shelljs from "shelljs";
22
import { TnsModulesCopy, NpmPluginPrepare } from "./node-modules-dest-copy";
3-
import { NodeModulesDependenciesBuilder } from "./node-modules-dependencies-builder";
43

54
export class NodeModulesBuilder implements INodeModulesBuilder {
65
constructor(private $fs: IFileSystem,
76
private $injector: IInjector,
8-
private $options: IOptions
7+
private $options: IOptions,
8+
private $nodeModulesDependenciesBuilder: INodeModulesDependenciesBuilder
99
) { }
1010

1111
public async prepareNodeModules(absoluteOutputPath: string, platform: string, lastModifiedTime: Date, projectData: IProjectData): Promise<void> {
@@ -14,8 +14,7 @@ export class NodeModulesBuilder implements INodeModulesBuilder {
1414
lastModifiedTime = null;
1515
}
1616

17-
let dependenciesBuilder = this.$injector.resolve(NodeModulesDependenciesBuilder, {});
18-
let productionDependencies = dependenciesBuilder.getProductionDependencies(projectData.projectDir);
17+
let productionDependencies = this.$nodeModulesDependenciesBuilder.getProductionDependencies(projectData.projectDir);
1918

2019
if (!this.$options.bundle) {
2120
const tnsModulesCopy = this.$injector.resolve(TnsModulesCopy, {

lib/tools/node-modules/node-modules-dependencies-builder.ts

Lines changed: 77 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,111 +1,110 @@
11
import * as path from "path";
2-
import * as fs from "fs";
2+
import { NODE_MODULES_FOLDER_NAME, PACKAGE_JSON_FILE_NAME } from "../../constants";
33

4-
export class NodeModulesDependenciesBuilder implements INodeModulesDependenciesBuilder {
5-
private projectPath: string;
6-
private rootNodeModulesPath: string;
7-
private resolvedDependencies: any[];
8-
private seen: any;
9-
10-
public constructor(private $fs: IFileSystem) {
11-
this.seen = {};
12-
this.resolvedDependencies = [];
13-
}
14-
15-
public getProductionDependencies(projectPath: string): any[] {
16-
this.projectPath = projectPath;
17-
this.rootNodeModulesPath = path.join(this.projectPath, "node_modules");
18-
19-
let projectPackageJsonpath = path.join(this.projectPath, "package.json");
20-
let packageJsonContent = this.$fs.readJson(projectPackageJsonpath);
21-
22-
_.keys(packageJsonContent.dependencies).forEach(dependencyName => {
23-
let depth = 0;
24-
let directory = path.join(this.rootNodeModulesPath, dependencyName);
25-
26-
// find and traverse child with name `key`, parent's directory -> dep.directory
27-
this.traverseDependency(dependencyName, directory, depth);
28-
});
29-
30-
return this.resolvedDependencies;
31-
}
4+
interface IDependencyDescription {
5+
parentDir: string;
6+
name: string;
7+
depth: number;
8+
}
329

33-
private traverseDependency(name: string, currentModulePath: string, depth: number): void {
34-
// Check if child has been extracted in the parent's node modules, AND THEN in `node_modules`
35-
// Slower, but prevents copying wrong versions if multiple of the same module are installed
36-
// Will also prevent copying project's devDependency's version if current module depends on another version
37-
let modulePath = path.join(currentModulePath, "node_modules", name); // node_modules/parent/node_modules/<package>
38-
let alternativeModulePath = path.join(this.rootNodeModulesPath, name);
10+
export class NodeModulesDependenciesBuilder implements INodeModulesDependenciesBuilder {
11+
public constructor(private $fs: IFileSystem) { }
12+
13+
public getProductionDependencies(projectPath: string): IDependencyData[] {
14+
const rootNodeModulesPath = path.join(projectPath, NODE_MODULES_FOLDER_NAME);
15+
const projectPackageJsonPath = path.join(projectPath, PACKAGE_JSON_FILE_NAME);
16+
const packageJsonContent = this.$fs.readJson(projectPackageJsonPath);
17+
const dependencies = packageJsonContent && packageJsonContent.dependencies;
18+
19+
let resolvedDependencies: IDependencyData[] = [];
20+
21+
let queue: IDependencyDescription[] = _.keys(dependencies)
22+
.map(dependencyName => ({
23+
parentDir: projectPath,
24+
name: dependencyName,
25+
depth: 0
26+
}));
27+
28+
while (queue.length) {
29+
const currentModule = queue.shift();
30+
const resolvedDependency = this.findModule(rootNodeModulesPath, currentModule.parentDir, currentModule.name, currentModule.depth, resolvedDependencies);
31+
32+
if (resolvedDependency && !_.some(resolvedDependencies, r => r.directory === resolvedDependency.directory)) {
33+
_.each(resolvedDependency.dependencies, d => {
34+
const dependency: IDependencyDescription = { name: d, parentDir: resolvedDependency.directory, depth: resolvedDependency.depth + 1 };
35+
36+
const shouldAdd = !_.some(queue, element =>
37+
element.name === dependency.name &&
38+
element.parentDir === dependency.parentDir &&
39+
element.depth === dependency.depth);
40+
41+
if (shouldAdd) {
42+
queue.push(dependency);
43+
}
44+
});
45+
46+
resolvedDependencies.push(resolvedDependency);
47+
}
48+
}
3949

40-
this.findModule(modulePath, alternativeModulePath, name, depth);
50+
return resolvedDependencies;
4151
}
4252

43-
private findModule(modulePath: string, alternativeModulePath: string, name: string, depth: number) {
44-
let exists = this.moduleExists(modulePath);
53+
private findModule(rootNodeModulesPath: string, parentModulePath: string, name: string, depth: number, resolvedDependencies: IDependencyData[]): IDependencyData {
54+
let modulePath = path.join(parentModulePath, NODE_MODULES_FOLDER_NAME, name); // node_modules/parent/node_modules/<package>
55+
const rootModulesPath = path.join(rootNodeModulesPath, name);
56+
let depthInNodeModules = depth;
4557

46-
if (exists) {
47-
if (this.seen[modulePath]) {
48-
return;
58+
if (!this.moduleExists(modulePath)) {
59+
modulePath = rootModulesPath; // /node_modules/<package>
60+
if (!this.moduleExists(modulePath)) {
61+
return null;
4962
}
5063

51-
let dependency = this.addDependency(name, modulePath, depth + 1);
52-
this.readModuleDependencies(modulePath, depth + 1, dependency);
53-
} else {
54-
modulePath = alternativeModulePath; // /node_modules/<package>
55-
exists = this.moduleExists(modulePath);
64+
depthInNodeModules = 0;
65+
}
5666

57-
if (!exists) {
58-
return;
59-
}
67+
if (_.some(resolvedDependencies, r => r.name === name && r.directory === modulePath)) {
68+
return null;
6069

61-
if (this.seen[modulePath]) {
62-
return;
63-
}
64-
65-
let dependency = this.addDependency(name, modulePath, 0);
66-
this.readModuleDependencies(modulePath, 0, dependency);
6770
}
6871

69-
this.seen[modulePath] = true;
72+
return this.getDependencyData(name, modulePath, depthInNodeModules);
7073
}
7174

72-
private readModuleDependencies(modulePath: string, depth: number, currentModule: any): void {
73-
let packageJsonPath = path.join(modulePath, 'package.json');
74-
let packageJsonExists = fs.lstatSync(packageJsonPath).isFile();
75+
private getDependencyData(name: string, directory: string, depth: number): IDependencyData {
76+
const dependency: IDependencyData = {
77+
name,
78+
directory,
79+
depth
80+
};
81+
82+
const packageJsonPath = path.join(directory, PACKAGE_JSON_FILE_NAME);
83+
const packageJsonExists = this.$fs.getLsStats(packageJsonPath).isFile();
7584

7685
if (packageJsonExists) {
7786
let packageJsonContents = this.$fs.readJson(packageJsonPath);
7887

7988
if (!!packageJsonContents.nativescript) {
8089
// add `nativescript` property, necessary for resolving plugins
81-
currentModule.nativescript = packageJsonContents.nativescript;
90+
dependency.nativescript = packageJsonContents.nativescript;
8291
}
8392

84-
_.keys(packageJsonContents.dependencies).forEach((dependencyName) => {
85-
this.traverseDependency(dependencyName, modulePath, depth);
86-
});
93+
dependency.dependencies = _.keys(packageJsonContents.dependencies);
94+
return dependency;
8795
}
88-
}
8996

90-
private addDependency(name: string, directory: string, depth: number): any {
91-
let dependency: any = {
92-
name,
93-
directory,
94-
depth
95-
};
96-
97-
this.resolvedDependencies.push(dependency);
98-
99-
return dependency;
97+
return null;
10098
}
10199

102100
private moduleExists(modulePath: string): boolean {
103101
try {
104-
let exists = fs.lstatSync(modulePath);
105-
if (exists.isSymbolicLink()) {
106-
exists = fs.lstatSync(fs.realpathSync(modulePath));
102+
let modulePathLsStat = this.$fs.getLsStats(modulePath);
103+
if (modulePathLsStat.isSymbolicLink()) {
104+
modulePathLsStat = this.$fs.getLsStats(this.$fs.realpath(modulePath));
107105
}
108-
return exists.isDirectory();
106+
107+
return modulePathLsStat.isDirectory();
109108
} catch (e) {
110109
return false;
111110
}

lib/tools/node-modules/node-modules-dest-copy.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export class TnsModulesCopy {
1515
) {
1616
}
1717

18-
public copyModules(dependencies: any[], platform: string): void {
18+
public copyModules(dependencies: IDependencyData[], platform: string): void {
1919
for (let entry in dependencies) {
2020
let dependency = dependencies[entry];
2121

@@ -34,7 +34,7 @@ export class TnsModulesCopy {
3434
}
3535
}
3636

37-
private copyDependencyDir(dependency: any): void {
37+
private copyDependencyDir(dependency: IDependencyData): void {
3838
if (dependency.depth === 0) {
3939
let isScoped = dependency.name.indexOf("@") === 0;
4040
let targetDir = this.outputRoot;
@@ -61,18 +61,18 @@ export class NpmPluginPrepare {
6161
) {
6262
}
6363

64-
protected async beforePrepare(dependencies: IDictionary<IDependencyData>, platform: string, projectData: IProjectData): Promise<void> {
64+
protected async beforePrepare(dependencies: IDependencyData[], platform: string, projectData: IProjectData): Promise<void> {
6565
await this.$platformsData.getPlatformData(platform, projectData).platformProjectService.beforePrepareAllPlugins(projectData, dependencies);
6666
}
6767

68-
protected async afterPrepare(dependencies: IDictionary<IDependencyData>, platform: string, projectData: IProjectData): Promise<void> {
68+
protected async afterPrepare(dependencies: IDependencyData[], platform: string, projectData: IProjectData): Promise<void> {
6969
await this.$platformsData.getPlatformData(platform, projectData).platformProjectService.afterPrepareAllPlugins(projectData);
7070
this.writePreparedDependencyInfo(dependencies, platform, projectData);
7171
}
7272

73-
private writePreparedDependencyInfo(dependencies: IDictionary<IDependencyData>, platform: string, projectData: IProjectData): void {
73+
private writePreparedDependencyInfo(dependencies: IDependencyData[], platform: string, projectData: IProjectData): void {
7474
let prepareData: IDictionary<boolean> = {};
75-
_.values(dependencies).forEach(d => {
75+
_.each(dependencies, d => {
7676
prepareData[d.name] = true;
7777
});
7878
this.$fs.createDirectory(this.preparedPlatformsDir(platform, projectData));
@@ -101,18 +101,18 @@ export class NpmPluginPrepare {
101101
return this.$fs.readJson(this.preparedPlatformsFile(platform, projectData), "utf8");
102102
}
103103

104-
private allPrepared(dependencies: IDictionary<IDependencyData>, platform: string, projectData: IProjectData): boolean {
104+
private allPrepared(dependencies: IDependencyData[], platform: string, projectData: IProjectData): boolean {
105105
let result = true;
106106
const previouslyPrepared = this.getPreviouslyPreparedDependencies(platform, projectData);
107-
_.values(dependencies).forEach(d => {
107+
_.each(dependencies, d => {
108108
if (!previouslyPrepared[d.name]) {
109109
result = false;
110110
}
111111
});
112112
return result;
113113
}
114114

115-
public async preparePlugins(dependencies: IDictionary<IDependencyData>, platform: string, projectData: IProjectData): Promise<void> {
115+
public async preparePlugins(dependencies: IDependencyData[], platform: string, projectData: IProjectData): Promise<void> {
116116
if (_.isEmpty(dependencies) || this.allPrepared(dependencies, platform, projectData)) {
117117
return;
118118
}

0 commit comments

Comments
 (0)