Skip to content

Commit 220df63

Browse files
committed
build: add path mapping support to broccoli typescript
1 parent ba120c2 commit 220df63

File tree

4 files changed

+180
-33
lines changed

4 files changed

+180
-33
lines changed

lib/broccoli/angular-broccoli-sass.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,13 @@ class SASSPlugin extends Plugin {
3535

3636
compile(fileName, inputPath, outputPath) {
3737
const outSourceName = fileName.replace(inputPath, outputPath);
38-
const outFileName = outSourceName.replace(/\.s[ac]ss$/, '.css');
38+
let outFileName = outSourceName.replace(/\.s[ac]ss$/, '.css');
39+
if (this.options.getDestinationPath) {
40+
let tmpFileName = this.options.getDestinationPath(path.relative(outputPath, outFileName));
41+
if (tmpFileName) {
42+
outFileName = path.join(outputPath, tmpFileName);
43+
}
44+
}
3945

4046
// We overwrite file, outFile and include the file path for the includePath.
4147
// We also make sure the options don't include a data field.

lib/broccoli/angular2-app.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,8 +371,18 @@ class Angular2App extends BroccoliPlugin {
371371
* @return {Tree} The assets tree.
372372
*/
373373
_getAssetsTree() {
374+
const getDestinationPath = (name) => {
375+
if (this._options.assets && this._options.assets.getDestinationPath) {
376+
name = this._options.assets.getDestinationPath(name);
377+
}
378+
if (name.startsWith(this._sourceDir)) {
379+
return name.substr(this._sourceDir.length);
380+
} else {
381+
return name;
382+
}
383+
};
384+
374385
return new BroccoliFunnel(this._inputNode, {
375-
srcDir: this._sourceDir,
376386
exclude: [
377387
'**/*.ts',
378388
'**/*.scss',
@@ -381,6 +391,7 @@ class Angular2App extends BroccoliPlugin {
381391
'**/*.styl',
382392
'**/tsconfig.json'
383393
],
394+
getDestinationPath: getDestinationPath,
384395
allowEmpty: true
385396
});
386397
}

lib/broccoli/broccoli-typescript.js

Lines changed: 130 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,11 @@ class BroccoliTypeScriptCompiler extends Plugin {
7676
} else if (this._fileRegistry[tsFilePath].version >= entry.mtime) {
7777
// Nothing to do for this file. Just link the cached outputs.
7878
this._fileRegistry[tsFilePath].outputs.forEach(absoluteFilePath => {
79-
const outputFilePath = absoluteFilePath.replace(this.cachePath, this.outputPath);
79+
let outputFilePath = absoluteFilePath.replace(this.cachePath, this.outputPath);
80+
if (this._options.getDestinationPath) {
81+
const tmpOutputPath = this._options.getDestinationPath(path.relative(this.outputPath, outputFilePath));
82+
outputFilePath = tmpOutputPath ? path.join(this.outputPath, tmpOutputPath) : outputFilePath;
83+
}
8084
fse.mkdirsSync(path.dirname(outputFilePath));
8185
fs.symlinkSync(absoluteFilePath, outputFilePath);
8286
});
@@ -159,12 +163,14 @@ class BroccoliTypeScriptCompiler extends Plugin {
159163

160164
this._tsConfigFiles = tsconfig.files.splice(0);
161165

162-
this._tsOpts = ts.convertCompilerOptionsFromJson(tsconfig.compilerOptions, '', null).options;
166+
this._tsOpts = ts.convertCompilerOptionsFromJson(tsconfig['compilerOptions'],
167+
this.inputPaths[0], this._tsConfigPath).options;
163168
this._tsOpts.rootDir = '';
164169
this._tsOpts.outDir = '';
165170

166171
this._tsServiceHost = new CustomLanguageServiceHost(
167-
this._tsOpts, this._rootFilePaths, this._fileRegistry, this.inputPaths[0]);
172+
this._tsOpts, this._rootFilePaths, this._fileRegistry, this.inputPaths[0],
173+
tsconfig['compilerOptions'].paths, this._tsConfigPath);
168174
this._tsService = ts.createLanguageService(this._tsServiceHost, ts.createDocumentRegistry());
169175
}
170176

@@ -190,7 +196,11 @@ class BroccoliTypeScriptCompiler extends Plugin {
190196
absoluteFilePath = path.resolve(this.cachePath, absoluteFilePath);
191197
// Replace the input path by the output.
192198
absoluteFilePath = absoluteFilePath.replace(this.inputPaths[0], this.cachePath);
193-
const outputFilePath = absoluteFilePath.replace(this.cachePath, this.outputPath);
199+
let outputFilePath = absoluteFilePath.replace(this.cachePath, this.outputPath);
200+
if (this._options.getDestinationPath) {
201+
const tmpOutputPath = this._options.getDestinationPath(path.relative(this.outputPath, outputFilePath));
202+
outputFilePath = tmpOutputPath ? path.join(this.outputPath, tmpOutputPath) : outputFilePath;
203+
}
194204

195205
if (registry) {
196206
registry.outputs.add(absoluteFilePath);
@@ -249,13 +259,15 @@ class BroccoliTypeScriptCompiler extends Plugin {
249259
}
250260

251261
class CustomLanguageServiceHost {
252-
constructor(compilerOptions, fileNames, fileRegistry, treeInputPath) {
262+
constructor(compilerOptions, fileNames, fileRegistry, treeInputPath, paths, tsConfigPath) {
253263
this.compilerOptions = compilerOptions;
254264
this.fileNames = fileNames;
255265
this.fileRegistry = fileRegistry;
256266
this.treeInputPath = treeInputPath;
257267
this.currentDirectory = treeInputPath;
258268
this.defaultLibFilePath = ts.getDefaultLibFilePath(compilerOptions).replace(/\\/g, '/');
269+
this.paths = paths;
270+
this.tsConfigPath = tsConfigPath;
259271
this.projectVersion = 0;
260272
}
261273

@@ -272,23 +284,87 @@ class CustomLanguageServiceHost {
272284
return this.projectVersion.toString();
273285
}
274286

275-
/**
276-
* This method is called quite a bit to lookup 3 kinds of paths:
277-
* 1/ files in the fileRegistry
278-
* - these are the files in our project that we are watching for changes
279-
* - in the future we could add caching for these files and invalidate the cache when
280-
* the file is changed lazily during lookup
281-
* 2/ .d.ts and library files not in the fileRegistry
282-
* - these are not our files, they come from tsd or typescript itself
283-
* - these files change only rarely but since we need them very rarely, it's not worth the
284-
* cache invalidation hassle to cache them
285-
* 3/ bogus paths that typescript compiler tries to lookup during import resolution
286-
* - these paths are tricky to cache since files come and go and paths that was bogus in the
287-
* past might not be bogus later
288-
*
289-
* In the initial experiments the impact of this caching was insignificant (single digit %) and
290-
* not worth the potential issues with stale cache records.
291-
*/
287+
_resolveModulePathWithMapping(moduleName) {
288+
// check if module name should be used as-is or it should be mapped to different value
289+
let longestMatchedPrefixLength = 0;
290+
let matchedPattern;
291+
let matchedWildcard;
292+
const paths = this.paths || {};
293+
294+
for (let pattern of Object.keys(paths)) {
295+
if (pattern.indexOf('*') != pattern.lastIndexOf('*')) {
296+
throw `Invalid path mapping pattern: "${pattern}"`;
297+
}
298+
299+
let indexOfWildcard = pattern.indexOf('*');
300+
if (indexOfWildcard !== -1) {
301+
// check if module name starts with prefix, ends with suffix and these two don't overlap
302+
let prefix = pattern.substr(0, indexOfWildcard);
303+
let suffix = pattern.substr(indexOfWildcard + 1);
304+
if (moduleName.length >= prefix.length + suffix.length &&
305+
moduleName.startsWith(prefix) &&
306+
moduleName.endsWith(suffix)) {
307+
308+
// use length of matched prefix as betterness criteria
309+
if (longestMatchedPrefixLength < prefix.length) {
310+
longestMatchedPrefixLength = prefix.length;
311+
matchedPattern = pattern;
312+
matchedWildcard = moduleName.substr(prefix.length, moduleName.length - suffix.length);
313+
}
314+
}
315+
} else {
316+
// Pattern does not contain asterisk - module name should exactly match pattern to succeed.
317+
if (pattern === moduleName) {
318+
matchedPattern = pattern;
319+
matchedWildcard = undefined;
320+
break;
321+
}
322+
}
323+
}
324+
325+
if (!matchedPattern) {
326+
// We fallback to the old module resolution.
327+
return undefined;
328+
// // no pattern was matched so module name can be used as-is
329+
// let p = path.join(this.treeInputPath, moduleName);
330+
// return fs.existsSync(p) ? p : undefined;
331+
}
332+
333+
// some pattern was matched - module name needs to be substituted
334+
let substitutions = this.paths[matchedPattern];
335+
for (let subst of substitutions) {
336+
if (subst.indexOf('*') != subst.lastIndexOf('*')) {
337+
throw `Invalid substitution: "${subst}" for pattern "${matchedPattern}".`;
338+
}
339+
// replace * in substitution with matched wildcard
340+
let p = matchedWildcard ? subst.replace('*', matchedWildcard) : subst;
341+
// if substituion is a relative path - combine it with baseUrl
342+
p = path.isAbsolute(p) ? p : path.join(this.treeInputPath, path.dirname(this.tsConfigPath), p);
343+
if (fs.existsSync(p)) {
344+
return p;
345+
}
346+
}
347+
348+
return undefined;
349+
}
350+
351+
// /**
352+
// * This method is called quite a bit to lookup 3 kinds of paths:
353+
// * 1/ files in the fileRegistry
354+
// * - these are the files in our project that we are watching for changes
355+
// * - in the future we could add caching for these files and invalidate the cache when
356+
// * the file is changed lazily during lookup
357+
// * 2/ .d.ts and library files not in the fileRegistry
358+
// * - these are not our files, they come from tsd or typescript itself
359+
// * - these files change only rarely but since we need them very rarely, it's not worth the
360+
// * cache invalidation hassle to cache them
361+
// * 3/ bogus paths that typescript compiler tries to lookup during import resolution
362+
// * - these paths are tricky to cache since files come and go and paths that was bogus in the
363+
// * past might not be bogus later
364+
// *
365+
// * In the initial experiments the impact of this caching was insignificant (single digit %) and
366+
// * not worth the potential issues with stale cache records.
367+
// */
292368
getScriptSnapshot(tsFilePath) {
293369
var absoluteTsFilePath;
294370
if (tsFilePath == this.defaultLibFilePath || path.isAbsolute(tsFilePath)) {
@@ -306,10 +382,41 @@ class CustomLanguageServiceHost {
306382
// so we we just return undefined when the path is not correct.
307383
return undefined;
308384
}
309-
310385
return ts.ScriptSnapshot.fromString(fs.readFileSync(absoluteTsFilePath, FS_OPTS));
311386
}
312387

388+
resolveModuleNames(moduleNames, containingFile)/*: ResolvedModule[]*/ {
389+
return moduleNames.map((moduleName) => {
390+
for (const ext of ['ts', 'd.ts']) {
391+
const name = `${moduleName}.${ext}`;
392+
const maybeModule = this._resolveModulePathWithMapping(name, containingFile);
393+
if (maybeModule) {
394+
return {
395+
resolvedFileName: maybeModule,
396+
isExternalLibraryImport: false
397+
};
398+
}
399+
}
400+
401+
return ts.resolveModuleName(moduleName, containingFile, this.compilerOptions, {
402+
fileExists(fileName) {
403+
return fs.existsSync(fileName);
404+
},
405+
readFile(fileName) {
406+
return fs.readFileSync(fileName, 'utf-8');
407+
},
408+
directoryExists(directoryName) {
409+
try {
410+
const stats = fs.statSync(directoryName);
411+
return stats && stats.isDirectory();
412+
} catch (e) {
413+
return false;
414+
}
415+
}
416+
}).resolvedModule;
417+
});
418+
}
419+
313420
getCurrentDirectory() {
314421
return this.currentDirectory;
315422
}

tests/e2e/e2e_workflow.spec.js

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -315,23 +315,46 @@ describe('Basic end-to-end Workflow', function () {
315315
let config = require(configFilePath);
316316

317317
config.compilerOptions.noImplicitAny = true;
318-
fs.writeFileSync(configFilePath, JSON.stringify(config), 'utf8');
318+
fs.writeFileSync(configFilePath, JSON.stringify(config, null, 2), 'utf8');
319319

320320
sh.rm('-rf', path.join(process.cwd(), 'dist'));
321321

322322
return ng(['build'])
323-
.then(function () {
323+
.then(() => {
324324
expect(existsSync(path.join(process.cwd(), 'dist'))).to.be.equal(true);
325325
})
326326
.catch(() => {
327327
throw new Error('Build failed.');
328328
})
329-
.finally(function () {
330-
// Clean `tmp` folder
331-
process.chdir(path.resolve(root, '..'));
332-
// sh.rm('-rf', './tmp'); // tmp.teardown takes too long
333-
done();
334-
});
329+
.finally(done);
335330
});
336331

332+
it('Turn on path mapping in tsconfig.json and rebuild', function (done) {
333+
this.timeout(420000);
334+
335+
const configFilePath = path.join(process.cwd(), 'src', 'tsconfig.json');
336+
let config = require(configFilePath);
337+
338+
config.compilerOptions.baseUrl = '';
339+
340+
// This should fail.
341+
config.compilerOptions.paths = { '@angular/*': [] };
342+
fs.writeFileSync(configFilePath, JSON.stringify(config, null, 2), 'utf8');
343+
344+
return ng(['build'])
345+
.then(() => {
346+
expect('build succeeded where it should have failed').to.equal('');
347+
})
348+
.catch(() => {})
349+
.then(() => {
350+
// This should succeed.
351+
config.compilerOptions.paths = { '@angular/*': [ '../../node_modules/@angular/*' ] };
352+
fs.writeFileSync(configFilePath, JSON.stringify(config, null, 2), 'utf8');
353+
})
354+
.then(() => ng(['build']))
355+
.catch(() => {
356+
expect('build failed where it should have succeeded').to.equal('');
357+
})
358+
.finally(done);
359+
});
337360
});

0 commit comments

Comments
 (0)