2018-06-26 15:01:09 -07:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
|
*
|
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import * as fs from 'fs';
|
|
|
|
|
|
|
|
|
|
import {ResourceLoader} from './annotations';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* `ResourceLoader` which delegates to a `CompilerHost` resource loading method.
|
|
|
|
|
*/
|
|
|
|
|
export class HostResourceLoader implements ResourceLoader {
|
|
|
|
|
private cache = new Map<string, string>();
|
2018-11-18 22:04:43 +01:00
|
|
|
private fetching = new Map<string, Promise<void>>();
|
2018-06-26 15:01:09 -07:00
|
|
|
|
|
|
|
|
constructor(private host: (url: string) => string | Promise<string>) {}
|
|
|
|
|
|
|
|
|
|
preload(url: string): Promise<void>|undefined {
|
2018-11-18 22:04:43 +01:00
|
|
|
if (this.cache.has(url)) {
|
2018-06-26 15:01:09 -07:00
|
|
|
return undefined;
|
2018-11-18 22:04:43 +01:00
|
|
|
} else if (this.fetching.has(url)) {
|
|
|
|
|
return this.fetching.get(url);
|
2018-06-26 15:01:09 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const result = this.host(url);
|
|
|
|
|
if (typeof result === 'string') {
|
|
|
|
|
this.cache.set(url, result);
|
|
|
|
|
return undefined;
|
|
|
|
|
} else {
|
2018-11-18 22:04:43 +01:00
|
|
|
const fetchCompletion = result.then(str => {
|
2018-06-26 15:01:09 -07:00
|
|
|
this.fetching.delete(url);
|
|
|
|
|
this.cache.set(url, str);
|
|
|
|
|
});
|
2018-11-18 22:04:43 +01:00
|
|
|
this.fetching.set(url, fetchCompletion);
|
|
|
|
|
return fetchCompletion;
|
2018-06-26 15:01:09 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
load(url: string): string {
|
|
|
|
|
if (this.cache.has(url)) {
|
|
|
|
|
return this.cache.get(url) !;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const result = this.host(url);
|
|
|
|
|
if (typeof result !== 'string') {
|
|
|
|
|
throw new Error(`HostResourceLoader: host(${url}) returned a Promise`);
|
|
|
|
|
}
|
|
|
|
|
this.cache.set(url, result);
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* `ResourceLoader` which directly uses the filesystem to resolve resources synchronously.
|
|
|
|
|
*/
|
|
|
|
|
export class FileResourceLoader implements ResourceLoader {
|
|
|
|
|
load(url: string): string { return fs.readFileSync(url, 'utf8'); }
|
|
|
|
|
}
|