1 | import * as Promise from 'bluebird';
|
2 | import * as cheerio from 'cheerio';
|
3 | import * as fs from 'fs';
|
4 | import * as path from 'path';
|
5 | import { getAppConfig, saveAppConfig } from './config-serializer';
|
6 | import {Config, BundleConfig, Inject} from './models';
|
7 | import {
|
8 | ensureDefaults,
|
9 | validateConfig,
|
10 | getHtmlImportBundleConfig,
|
11 | } from './utils';
|
12 |
|
13 | export function unbundle(cfg: Config) {
|
14 | let config = ensureDefaults(cfg);
|
15 | validateConfig(config);
|
16 |
|
17 | let tasks = [
|
18 | removeBundles(config),
|
19 | removeHtmlImportBundles(config)
|
20 | ];
|
21 |
|
22 | return Promise.all<any>(tasks);
|
23 | }
|
24 |
|
25 | function removeBundles(cfg: Config) {
|
26 | let configPath = cfg.injectionConfigPath;
|
27 | let appCfg = getAppConfig(configPath as string);
|
28 | delete appCfg.bundles;
|
29 | delete appCfg.depCache;
|
30 | saveAppConfig(configPath as string, appCfg);
|
31 |
|
32 | return Promise.resolve();
|
33 | }
|
34 |
|
35 | function removeHtmlImportBundles(config: Config) {
|
36 | let tasks: Promise<any>[] = [];
|
37 | Object
|
38 | .keys(config.bundles)
|
39 | .forEach((key) => {
|
40 | let cfg = config.bundles[key];
|
41 | if (cfg.htmlimport) {
|
42 | tasks.push(_removeHtmlImportBundle(getHtmlImportBundleConfig(cfg, key, config)));
|
43 | }
|
44 | });
|
45 |
|
46 | return Promise.all<any>(tasks);
|
47 | }
|
48 |
|
49 | function _removeHtmlImportBundle(cfg: BundleConfig) {
|
50 | let inject = cfg.options.inject as Inject;
|
51 | let file = path.resolve(cfg.baseURL, inject.destFile);
|
52 |
|
53 | if (!fs.existsSync(file)) {
|
54 | return Promise.resolve();
|
55 | }
|
56 |
|
57 | return Promise
|
58 | .promisify<string, string, any>(fs.readFile)(file, {
|
59 | encoding: 'utf8'
|
60 | })
|
61 | .then((content) => {
|
62 | let $ = cheerio.load(content);
|
63 | return Promise.resolve($);
|
64 | })
|
65 | .then(($) => {
|
66 | return removeLinkInjections($);
|
67 | })
|
68 | .then(($) => {
|
69 | return Promise.promisify<void, string, string>(fs.writeFile)(file, $.html());
|
70 | });
|
71 | }
|
72 |
|
73 | function removeLinkInjections($: CheerioStatic) {
|
74 | $('link[aurelia-view-bundle]').remove();
|
75 | return Promise.resolve($);
|
76 | }
|