refactor(ivy): expose resolving URLs in the ResourceLoader (#28199)

Resources can be loaded in the context of another file, which
means that the path to the resource file must be resolved
before it can be loaded.

Previously the API of this interface did not allow the client
code to get access to the resolved URL which is used to load
the resource.

Now this API has been refactored so that you must do the
resource URL resolving first and the loading expects a
resolved URL.

PR Close #28199
This commit is contained in:
Pete Bacon Darwin
2019-01-16 17:22:53 +00:00
committed by Alex Rickabaugh
parent 7bdf3fe41c
commit 73dcd72afb
6 changed files with 192 additions and 101 deletions

View File

@ -8,8 +8,8 @@
import * as fs from 'fs';
import * as ts from 'typescript';
import {ResourceLoader} from './annotations';
import {CompilerHost} from '../transformers/api';
import {ResourceLoader} from './annotations/src/api';
/**
* `ResourceLoader` which delegates to a `CompilerHost` resource loading method.
@ -18,107 +18,141 @@ export class HostResourceLoader implements ResourceLoader {
private cache = new Map<string, string>();
private fetching = new Map<string, Promise<void>>();
constructor(
private resolver: (file: string, basePath: string) => string | null,
private loader: (url: string) => string | Promise<string>) {}
canPreload = !!this.host.readResource;
preload(file: string, containingFile: string): Promise<void>|undefined {
const resolved = this.resolver(file, containingFile);
if (resolved === null) {
constructor(private host: CompilerHost, private options: ts.CompilerOptions) {}
/**
* Resolve the url of a resource relative to the file that contains the reference to it.
* The return value of this method can be used in the `load()` and `preload()` methods.
*
* Uses the provided CompilerHost if it supports mapping resources to filenames.
* Otherwise, uses a fallback mechanism that searches the module resolution candidates.
*
* @param url The, possibly relative, url of the resource.
* @param fromFile The path to the file that contains the URL of the resource.
* @returns A resolved url of resource.
* @throws An error if the resource cannot be resolved.
*/
resolve(url: string, fromFile: string): string {
let resolvedUrl: string|null = null;
if (this.host.resourceNameToFileName) {
resolvedUrl = this.host.resourceNameToFileName(url, fromFile);
} else {
resolvedUrl = this.fallbackResolve(url, fromFile);
}
if (resolvedUrl === null) {
throw new Error(`HostResourceResolver: could not resolve ${url} in context of ${fromFile})`);
}
return resolvedUrl;
}
/**
* Preload the specified resource, asynchronously.
*
* Once the resource is loaded, its value is cached so it can be accessed synchronously via the
* `load()` method.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to preload.
* @returns A Promise that is resolved once the resource has been loaded or `undefined` if the
* file has already been loaded.
* @throws An Error if pre-loading is not available.
*/
preload(resolvedUrl: string): Promise<void>|undefined {
if (!this.host.readResource) {
throw new Error(
'HostResourceLoader: the CompilerHost provided does not support pre-loading resources.');
}
if (this.cache.has(resolvedUrl)) {
return undefined;
} else if (this.fetching.has(resolvedUrl)) {
return this.fetching.get(resolvedUrl);
}
if (this.cache.has(resolved)) {
return undefined;
} else if (this.fetching.has(resolved)) {
return this.fetching.get(resolved);
}
const result = this.loader(resolved);
const result = this.host.readResource(resolvedUrl);
if (typeof result === 'string') {
this.cache.set(resolved, result);
this.cache.set(resolvedUrl, result);
return undefined;
} else {
const fetchCompletion = result.then(str => {
this.fetching.delete(resolved);
this.cache.set(resolved, str);
this.fetching.delete(resolvedUrl);
this.cache.set(resolvedUrl, str);
});
this.fetching.set(resolved, fetchCompletion);
this.fetching.set(resolvedUrl, fetchCompletion);
return fetchCompletion;
}
}
load(file: string, containingFile: string): string {
const resolved = this.resolver(file, containingFile);
if (resolved === null) {
throw new Error(
`HostResourceLoader: could not resolve ${file} in context of ${containingFile})`);
/**
* Load the resource at the given url, synchronously.
*
* The contents of the resource may have been cached by a previous call to `preload()`.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to load.
* @returns The contents of the resource.
*/
load(resolvedUrl: string): string {
if (this.cache.has(resolvedUrl)) {
return this.cache.get(resolvedUrl) !;
}
if (this.cache.has(resolved)) {
return this.cache.get(resolved) !;
}
const result = this.loader(resolved);
const result = this.host.readResource ? this.host.readResource(resolvedUrl) :
fs.readFileSync(resolvedUrl, 'utf8');
if (typeof result !== 'string') {
throw new Error(`HostResourceLoader: loader(${resolved}) returned a Promise`);
throw new Error(`HostResourceLoader: loader(${resolvedUrl}) returned a Promise`);
}
this.cache.set(resolved, result);
this.cache.set(resolvedUrl, result);
return result;
}
}
// `failedLookupLocations` is in the name of the type ts.ResolvedModuleWithFailedLookupLocations
// but is marked @internal in TypeScript. See https://github.com/Microsoft/TypeScript/issues/28770.
type ResolvedModuleWithFailedLookupLocations =
ts.ResolvedModuleWithFailedLookupLocations & {failedLookupLocations: ReadonlyArray<string>};
/**
* `ResourceLoader` which directly uses the filesystem to resolve resources synchronously.
*/
export class FileResourceLoader implements ResourceLoader {
constructor(private host: ts.CompilerHost, private options: ts.CompilerOptions) {}
load(file: string, containingFile: string): string {
// Attempt to resolve `file` in the context of `containingFile`, while respecting the rootDirs
// option from the tsconfig. First, normalize the file name.
/**
* Attempt to resolve `url` in the context of `fromFile`, while respecting the rootDirs
* option from the tsconfig. First, normalize the file name.
*/
private fallbackResolve(url: string, fromFile: string): string|null {
// Strip a leading '/' if one is present.
if (file.startsWith('/')) {
file = file.substr(1);
if (url.startsWith('/')) {
url = url.substr(1);
}
// Turn absolute paths into relative paths.
if (!file.startsWith('.')) {
file = `./${file}`;
if (!url.startsWith('.')) {
url = `./${url}`;
}
// TypeScript provides utilities to resolve module names, but not resource files (which aren't
// a part of the ts.Program). However, TypeScript's module resolution can be used creatively
// to locate where resource files should be expected to exist. Since module resolution returns
// a list of file names that were considered, the loader can enumerate the possible locations
// for the file by setting up a module resolution for it that will fail.
file += '.$ngresource$';
const candidateLocations = this.getCandidateLocations(url, fromFile);
for (const candidate of candidateLocations) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
/**
* TypeScript provides utilities to resolve module names, but not resource files (which aren't
* a part of the ts.Program). However, TypeScript's module resolution can be used creatively
* to locate where resource files should be expected to exist. Since module resolution returns
* a list of file names that were considered, the loader can enumerate the possible locations
* for the file by setting up a module resolution for it that will fail.
*/
private getCandidateLocations(url: string, fromFile: string): string[] {
// `failedLookupLocations` is in the name of the type ts.ResolvedModuleWithFailedLookupLocations
// but is marked @internal in TypeScript. See
// https://github.com/Microsoft/TypeScript/issues/28770.
type ResolvedModuleWithFailedLookupLocations =
ts.ResolvedModuleWithFailedLookupLocations & {failedLookupLocations: ReadonlyArray<string>};
// clang-format off
const failedLookup = ts.resolveModuleName(file, containingFile, this.options, this.host) as ResolvedModuleWithFailedLookupLocations;
const failedLookup = ts.resolveModuleName(url + '.$ngresource$', fromFile, this.options, this.host) as ResolvedModuleWithFailedLookupLocations;
// clang-format on
if (failedLookup.failedLookupLocations === undefined) {
throw new Error(
`Internal error: expected to find failedLookupLocations during resolution of resource '${file}' in context of ${containingFile}`);
`Internal error: expected to find failedLookupLocations during resolution of resource '${url}' in context of ${fromFile}`);
}
const candidateLocations =
failedLookup.failedLookupLocations
.filter(candidate => candidate.endsWith('.$ngresource$.ts'))
.map(candidate => candidate.replace(/\.\$ngresource\$\.ts$/, ''));
for (const candidate of candidateLocations) {
if (fs.existsSync(candidate)) {
return fs.readFileSync(candidate, 'utf8');
}
}
throw new Error(`Could not find resource ${file} in context of ${containingFile}`);
return failedLookup.failedLookupLocations
.filter(candidate => candidate.endsWith('.$ngresource$.ts'))
.map(candidate => candidate.replace(/\.\$ngresource\$\.ts$/, ''));
}
}