UNPKG

2.44 kBPlain TextView Raw
1#!/usr/bin/env node
2
3const yargs = require('yargs')
4 .usage('$0 --root <inputRootDirectory> -o <dir> [options] <htmlFile(s)>')
5 .wrap(72)
6 .options('h', {
7 alias: 'help',
8 describe: 'Show this help',
9 type: 'boolean',
10 default: false,
11 })
12 .options('algorithm', {
13 describe: 'The hash algorithm to use',
14 type: 'string',
15 default: 'sha256',
16 demand: false,
17 })
18 .options('root', {
19 describe:
20 'Path to your web root (will be deduced from your input files if not specified)',
21 type: 'string',
22 demand: false,
23 })
24 .options('output', {
25 alias: ['o', 'outroot'],
26 describe:
27 'Path to the output folder (will be generated if non-existing). Defaults to overwrite the source files in-place',
28 type: 'string',
29 demand: false,
30 });
31
32const commandLineOptions = yargs.argv;
33
34if (commandLineOptions.h) {
35 yargs.showHelp();
36 process.exit(0);
37}
38
39const AssetGraph = require('../lib/AssetGraph');
40const urlTools = require('urltools');
41const output =
42 commandLineOptions.output &&
43 urlTools.fsDirToFileUrl(commandLineOptions.output);
44let rootUrl =
45 commandLineOptions.root &&
46 urlTools.urlOrFsPathToUrl(commandLineOptions.root, true);
47let inputUrls;
48
49if (commandLineOptions._.length > 0) {
50 inputUrls = commandLineOptions._.map(function (urlOrFsPath) {
51 return urlTools.urlOrFsPathToUrl(String(urlOrFsPath), false);
52 });
53 if (!rootUrl) {
54 rootUrl = urlTools.findCommonUrlPrefix(
55 inputUrls.filter((inputUrl) => /^file:/.test(inputUrl))
56 );
57 if (rootUrl) {
58 console.warn('Guessing --root from input files: ' + rootUrl);
59 }
60 }
61} else if (rootUrl && /^file:/.test(rootUrl)) {
62 inputUrls = [rootUrl + '*.html'];
63 console.warn('No input files specified, defaulting to ' + inputUrls[0]);
64} else {
65 throw new Error(
66 "No input files and no --root specified (or it isn't file:), cannot proceed"
67 );
68}
69
70new AssetGraph({ root: rootUrl })
71 .loadAssets(inputUrls)
72 .populate({
73 from: { type: 'Html' },
74 followRelations: {
75 type: ['HtmlScript', 'HtmlStyle'],
76 to: { protocol: { $not: 'file:' } },
77 },
78 })
79 .reviewSubResourceIntegrity(
80 { type: 'Html', isInline: false, isFragment: false, isLoaded: true },
81 { update: true, single: true, algorithm: commandLineOptions.algorithm }
82 )
83 .writeAssetsToDisc(
84 { url: /^file:/, type: 'Html', isLoaded: true, isDirty: true },
85 output || rootUrl
86 )
87 .writeStatsToStderr()
88 .run();