cbst 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ # 0.2.0
4
+
5
+ - Exit with code 1 on errors (including unresolved references)
6
+ - Support source map references
7
+ - Fix glob prefix
8
+
9
+ # 0.1.1
10
+
11
+ - Fix binary
12
+
13
+ # 0.1.0
14
+
15
+ - Initial version
package/README.md CHANGED
@@ -22,23 +22,23 @@ cbst <input dir> <output dir> [<config file>]
22
22
 
23
23
  ## Example
24
24
 
25
- This diff demonstrates how versioning is applied on a simple website:
25
+ This diff demonstrates how versioning is applied to a simple website:
26
26
 
27
27
  ```diff
28
- # index.html
28
+ # /index.html
29
29
 
30
30
  <!DOCTYPE html>
31
31
  <html>
32
32
  <head>
33
33
  <title>Hello, World!</title>
34
- - <link rel="stylesheet" href="styles/main.css">
35
- + <link rel="stylesheet" href="styles/main.ed1e118152.css">
34
+ - <link rel="stylesheet" href="/styles/main.css">
35
+ + <link rel="stylesheet" href="/styles/main.ed1e118152.css">
36
36
  </head>
37
37
  <body>
38
38
  <h1>Hello, World!</h1>
39
39
  <p>
40
- - <img id="welcome" src="assets/loading.png">
41
- + <img id="welcome" src="assets/loading.834ab3df39.png">
40
+ - <img id="welcome" src="/assets/loading.svg">
41
+ + <img id="welcome" src="/assets/loading.834ab3df39.svg">
42
42
  </p>
43
43
  <script type="module">
44
44
  - import { main } from './scripts/main.js';
@@ -49,19 +49,19 @@ This diff demonstrates how versioning is applied on a simple website:
49
49
  </body>
50
50
  </html>
51
51
 
52
- # scripts/main.js -> scripts/main.f39e95e656.js
52
+ # /scripts/main.js -> /scripts/main.f39e95e656.js
53
53
 
54
- - import { yell } from './yell.js';
55
- + import { yell } from './yell.93724d33b5.js';
54
+ - import { hello } from './hello.js';
55
+ + import { hello } from './hello.93724d33b5.js';
56
56
 
57
57
  export function main() {
58
- yell('hello');
59
- - document.getElementById('welcome').src = 'assets/welcome.svg';
60
- + document.getElementById('welcome').src = 'assets/welcome.afe45bb832.svg';
58
+ hello('world');
59
+ - document.getElementById('welcome').src = '/assets/welcome.svg';
60
+ + document.getElementById('welcome').src = '/assets/welcome.afe45bb832.svg';
61
61
  }
62
62
 
63
- # styles/main.css -> styles/main.ed1e118152.css
64
- # scripts/yell.js -> scripts/yell.93724d33b5.js
63
+ # /styles/main.css -> /styles/main.ed1e118152.css
64
+ # /scripts/hello.js -> /scripts/hello.93724d33b5.js
65
65
  # etc.
66
66
  ```
67
67
 
@@ -95,7 +95,7 @@ File patterns support `*` (slash-free wildcards) and `/**/` (directory wildcards
95
95
  ## Versioning and references
96
96
 
97
97
  As `cbst` transforms files, it also rewrites any references to other versioned files.
98
- References are detected by scanning source files for quoted strings that
98
+ References are detected by scanning source files for **quoted strings** that
99
99
 
100
100
  - are double- or single-quoted,
101
101
  - contain no whitespace or quotes,
@@ -1,11 +1,13 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import EventEmitter from 'events';
3
5
  import { Cache } from './util/Cache';
4
6
  import { Glob } from './util/Glob';
5
7
  export interface CacheBusterConfig {
6
8
  /**
7
9
  * List of file patterns to exclude entirely.
8
- * Defaults to an `[]`.
10
+ * Defaults to `[]`.
9
11
  */
10
12
  exclude?: string[];
11
13
  /**
@@ -43,17 +45,11 @@ export interface CacheBusterOptions extends CacheBusterConfig {
43
45
  * Output directory
44
46
  */
45
47
  outputDir: string;
46
- /**
47
- * Error handler
48
- */
49
- onError?: ErrorHandler;
50
48
  }
51
- export type ErrorHandler = (err: Error) => unknown;
52
- export declare class CacheBuster {
49
+ export declare class CacheBuster extends EventEmitter {
53
50
  static defaultConfig: Required<CacheBusterConfig>;
54
51
  protected inputDir: string;
55
52
  protected outputDir: string;
56
- protected onError?: ErrorHandler;
57
53
  protected excludeGlob: Glob;
58
54
  protected sourceGlob: Glob;
59
55
  protected htmlGlob: Glob;
@@ -64,7 +60,8 @@ export declare class CacheBuster {
64
60
  protected getReferencesCache: Cache<string[]>;
65
61
  protected hashRawFileCache: Cache<string>;
66
62
  protected readFileCache: Cache<Buffer>;
67
- protected map: Record<string, string>;
63
+ protected map: Map<string, string>;
64
+ protected unresolved: Map<string, Set<string>>;
68
65
  protected referenceRx: RegExp;
69
66
  protected baseRx: RegExp;
70
67
  protected extensionRx: RegExp;
@@ -77,7 +74,7 @@ export declare class CacheBuster {
77
74
  hashFile(file: string): Promise<string | undefined>;
78
75
  hashFileReferences(file: string, exclude: string[]): Promise<string[]>;
79
76
  hashRawFile(file: string): Promise<string>;
80
- handleReferenceError(err: Error, source: string, reference: string): void;
77
+ handleReferenceError(error: Error, source: string, reference: string): void;
81
78
  getReferences(file: string): Promise<string[]>;
82
79
  isReference(reference: string): boolean;
83
80
  resolveReference(base: string, reference: string): string;
@@ -1,27 +1,31 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.CacheBuster = void 0;
4
7
  const crypto_1 = require("crypto");
8
+ const events_1 = __importDefault(require("events"));
5
9
  const fs_1 = require("fs");
6
10
  const path_1 = require("path");
7
11
  const ReferenceError_1 = require("./ReferenceError");
8
- const assert_1 = require("./util/assert");
9
12
  const Cache_1 = require("./util/Cache");
10
13
  const Glob_1 = require("./util/Glob");
11
- class CacheBuster {
14
+ class CacheBuster extends events_1.default {
12
15
  constructor(options) {
16
+ super();
13
17
  this.hashFileCache = new Cache_1.Cache((file) => this.hashFile(file));
14
18
  this.getReferencesCache = new Cache_1.Cache((file) => this.getReferences(file));
15
19
  this.hashRawFileCache = new Cache_1.Cache((file) => this.hashRawFile(file));
16
20
  this.readFileCache = new Cache_1.Cache((file) => this.readFile(file));
17
- this.map = {};
18
- this.referenceRx = /((")(([^"\s]+)\.([a-zA-Z0-9]+))")|((')(([^'\s]+)\.([a-zA-Z0-9]+))')/g;
21
+ this.map = new Map();
22
+ this.unresolved = new Map();
23
+ this.referenceRx = /((")(([^"\s]+)\.([a-zA-Z0-9]+))")|((')(([^'\s]+)\.([a-zA-Z0-9]+))')|# sourceMappingURL=(([^\s]+)\.([a-zA-Z0-9]+))/g;
19
24
  this.baseRx = /<base[^<>]+href\s*=\s*"([^"]+)"[^<>]*>/i;
20
25
  this.extensionRx = /(?<=\.)[^.]+$/;
21
26
  const o = { ...CacheBuster.defaultConfig, ...options };
22
27
  this.inputDir = o.inputDir;
23
28
  this.outputDir = o.outputDir;
24
- this.onError = o.onError;
25
29
  this.excludeGlob = new Glob_1.Glob(o.exclude);
26
30
  this.sourceGlob = new Glob_1.Glob(o.source);
27
31
  this.htmlGlob = new Glob_1.Glob(o.html);
@@ -34,7 +38,7 @@ class CacheBuster {
34
38
  await this.writeManifest();
35
39
  }
36
40
  async writeManifest() {
37
- await this.writeFile(this.manifest, JSON.stringify({ map: this.map }));
41
+ await this.writeFile(this.manifest, JSON.stringify({ map: Object.fromEntries(this.map.entries()) }));
38
42
  }
39
43
  async handleDir(dir) {
40
44
  if (this.excludeGlob.match(dir))
@@ -58,7 +62,7 @@ class CacheBuster {
58
62
  const outputFile = hash
59
63
  ? file.replace(this.extensionRx, (extension) => `${this.formatVersion(hash)}.${extension}`)
60
64
  : file;
61
- this.map[file] = outputFile;
65
+ this.map.set(file, outputFile);
62
66
  await this.writeFile(outputFile, output);
63
67
  if (!this.sourceGlob.match(file)) {
64
68
  this.readFileCache.delete(file);
@@ -78,14 +82,17 @@ class CacheBuster {
78
82
  let i = 0;
79
83
  return source.replace(this.referenceRx, (match, ...groups) => {
80
84
  const quote = groups[1] || groups[6];
81
- const reference = groups[2] || groups[7];
82
- const filename = groups[3] || groups[8];
83
- const extension = groups[4] || groups[9];
85
+ const reference = groups[2] || groups[7] || groups[10];
86
+ const filename = groups[3] || groups[8] || groups[11];
87
+ const extension = groups[4] || groups[9] || groups[12];
84
88
  if (!this.isReference(reference))
85
89
  return match;
86
90
  const hash = hashes[i++];
87
91
  if (!hash)
88
92
  return match;
93
+ if (groups[10]) {
94
+ return `# sourceMappingURL=${filename}.${this.formatVersion(hash)}.${extension}`;
95
+ }
89
96
  return `${quote}${filename}.${this.formatVersion(hash)}.${extension}${quote}`;
90
97
  });
91
98
  }
@@ -105,17 +112,26 @@ class CacheBuster {
105
112
  this.handleReferenceError(err, file, it);
106
113
  return '';
107
114
  })));
108
- const deep = await Promise.all(references.map((it) => this.hashFileReferences(it, [...exclude, file])));
115
+ const deep = await Promise.all(references.map((it) => this.hashFileReferences(it, [...exclude, file]).catch((err) => {
116
+ this.handleReferenceError(err, file, it);
117
+ return [];
118
+ })));
109
119
  return [...direct, ...deep.flat()];
110
120
  }
111
121
  async hashRawFile(file) {
112
122
  const buffer = await this.readFileCache.get(file);
113
123
  return this.hash([buffer]);
114
124
  }
115
- handleReferenceError(err, source, reference) {
116
- if (this.onError) {
117
- this.onError?.(new ReferenceError_1.ReferenceError(err, source, reference));
125
+ handleReferenceError(error, source, reference) {
126
+ let unresolved = this.unresolved.get(source);
127
+ if (!unresolved) {
128
+ unresolved = new Set();
129
+ this.unresolved.set(source, unresolved);
118
130
  }
131
+ if (unresolved.has(reference))
132
+ return;
133
+ unresolved.add(reference);
134
+ this.emit('error', new ReferenceError_1.ReferenceError(error, source, reference));
119
135
  }
120
136
  // references
121
137
  async getReferences(file) {
@@ -126,7 +142,7 @@ class CacheBuster {
126
142
  const base = await this.getBase(file);
127
143
  const references = [];
128
144
  for (const match of source.matchAll(this.referenceRx)) {
129
- const reference = match[3] || match[8];
145
+ const reference = match[3] || match[8] || match[11];
130
146
  if (this.isReference(reference)) {
131
147
  references.push(this.resolveReference(base, reference));
132
148
  }
@@ -177,7 +193,9 @@ class CacheBuster {
177
193
  }
178
194
  safePath(rootDir, candidate) {
179
195
  const s = path_1.posix.normalize(path_1.posix.join(rootDir, candidate));
180
- (0, assert_1.assert)(s.indexOf(rootDir) === 0, `Trying to access file outside of ${rootDir}: ${candidate}`);
196
+ if (s.indexOf(rootDir) !== 0) {
197
+ throw new Error(`Trying to access file outside of ${rootDir}: ${candidate}`);
198
+ }
181
199
  return s;
182
200
  }
183
201
  }
@@ -3,7 +3,7 @@ import { ConsoleLike } from './util/ConsoleLike';
3
3
  export declare class CacheBusterCli {
4
4
  protected console: ConsoleLike;
5
5
  constructor(console?: ConsoleLike);
6
- run(argv: string[], noExit?: boolean): Promise<void>;
6
+ run(argv: string[]): Promise<number>;
7
7
  help(): string;
8
8
  loadConfig(file: string): Promise<CacheBusterConfig>;
9
9
  }
@@ -3,16 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CacheBusterCli = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const CacheBuster_1 = require("./CacheBuster");
6
- const assert_1 = require("./util/assert");
6
+ const isRecord_1 = require("./util/isRecord");
7
+ const isStringArray_1 = require("./util/isStringArray");
7
8
  class CacheBusterCli {
8
9
  constructor(console = global.console) {
9
10
  this.console = console;
10
11
  }
11
- async run(argv, noExit = false) {
12
+ async run(argv) {
12
13
  try {
13
14
  if (argv.includes('--help')) {
14
15
  this.console.log(this.help());
15
- return;
16
+ return 0;
16
17
  }
17
18
  const [inputDir, outputDir, configFile] = argv;
18
19
  if (!inputDir)
@@ -24,16 +25,19 @@ class CacheBusterCli {
24
25
  ...config,
25
26
  inputDir,
26
27
  outputDir,
27
- onError: (err) => this.console.error(`Warning: ${err.message}`),
28
+ });
29
+ let exitCode = 0;
30
+ cacheBuster.on('error', (err) => {
31
+ this.console.error(err.message);
32
+ exitCode = 1;
28
33
  });
29
34
  await cacheBuster.run();
35
+ return exitCode;
30
36
  }
31
37
  catch (err) {
32
38
  this.console.error(err instanceof Error ? err.message : `${err}`);
33
39
  this.console.error(this.help());
34
- if (noExit)
35
- throw err;
36
- process.exit(1);
40
+ return 1;
37
41
  }
38
42
  }
39
43
  help() {
@@ -42,13 +46,27 @@ class CacheBusterCli {
42
46
  }
43
47
  async loadConfig(file) {
44
48
  const config = JSON.parse(await fs_1.promises.readFile(file, 'utf-8'));
45
- (0, assert_1.assertRecord)(config, 'Config must be an object');
46
- (0, assert_1.assertStringArray)(config.exclude ?? [], '"exclude" must be an array of strings');
47
- (0, assert_1.assertStringArray)(config.sources ?? [], '"sources" must be an array of strings');
48
- (0, assert_1.assertStringArray)(config.html ?? [], '"html" must be an array of strings');
49
- (0, assert_1.assertStringArray)(config.dynamic ?? [], '"dynamic" must be an array of strings');
50
- (0, assert_1.assertString)(config.manifest ?? '', '"manifest" must be a string');
51
- (0, assert_1.assertNumber)(config.hashLength ?? 10, '"hashLength" must be number');
49
+ if (!(0, isRecord_1.isRecord)(config)) {
50
+ throw new Error('Config must be an object');
51
+ }
52
+ if (!(0, isStringArray_1.isStringArray)(config.exclude ?? [])) {
53
+ throw new Error('"exclude" must be an array of strings');
54
+ }
55
+ if (!(0, isStringArray_1.isStringArray)(config.sources ?? [])) {
56
+ throw new Error('"sources" must be an array of strings');
57
+ }
58
+ if (!(0, isStringArray_1.isStringArray)(config.html ?? [])) {
59
+ throw new Error('"html" must be an array of strings');
60
+ }
61
+ if (!(0, isStringArray_1.isStringArray)(config.dynamic ?? [])) {
62
+ throw new Error('"dynamic" must be an array of strings');
63
+ }
64
+ if (typeof (config.manifest ?? '') !== 'string') {
65
+ throw new Error('"manifest" must be a string');
66
+ }
67
+ if (typeof (config.hashLength ?? 10) !== 'number') {
68
+ throw new Error('"hashLength" must be number');
69
+ }
52
70
  return config;
53
71
  }
54
72
  }
@@ -1,6 +1,10 @@
1
1
  export declare class ReferenceError extends Error {
2
- originalError: Error;
2
+ originalError: Error & {
3
+ code?: string;
4
+ };
3
5
  source: string;
4
6
  reference: string;
5
- constructor(originalError: Error, source: string, reference: string);
7
+ constructor(originalError: Error & {
8
+ code?: string;
9
+ }, source: string, reference: string);
6
10
  }
@@ -3,7 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ReferenceError = void 0;
4
4
  class ReferenceError extends Error {
5
5
  constructor(originalError, source, reference) {
6
- super(`Could not resolve reference ${reference} from ${source} (${originalError.message})`);
6
+ super(originalError.code === 'ENOENT'
7
+ ? `Could not resolve ${reference} from ${source}`
8
+ : `Could not resolve ${reference} from ${source} (${originalError.message})`);
7
9
  this.originalError = originalError;
8
10
  this.source = source;
9
11
  this.reference = reference;
package/dist/bin.d.ts CHANGED
@@ -1 +1,2 @@
1
+ #!/usr/bin/env node
1
2
  export {};
package/dist/bin.js CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  "use strict";
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  const CacheBusterCli_1 = require("./CacheBusterCli");
package/dist/util/Glob.js CHANGED
@@ -21,7 +21,7 @@ class Glob {
21
21
  }
22
22
  compile(pattern) {
23
23
  const inverted = !!pattern.match(/^!/);
24
- const absolutePrefix = pattern.match(/^!?\//) ? '^' : '';
24
+ const prefix = pattern.match(/^!?\//) ? '^' : '(^|/)';
25
25
  const rxBase = pattern
26
26
  .slice(inverted ? 1 : 0)
27
27
  .replace(/(\/\*\*\/)|(\*\*)|(\*)|([.+])/g, (_, ...groups) => {
@@ -41,7 +41,7 @@ class Glob {
41
41
  return `\\${groups[3]}`;
42
42
  }
43
43
  });
44
- const rx = new RegExp(absolutePrefix + rxBase + '$');
44
+ const rx = new RegExp(prefix + rxBase + '$');
45
45
  return {
46
46
  inverted,
47
47
  rx,
@@ -0,0 +1 @@
1
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRecord = void 0;
4
+ function isRecord(value) {
5
+ return typeof value === 'object' && !!value && !Array.isArray(value);
6
+ }
7
+ exports.isRecord = isRecord;
@@ -0,0 +1 @@
1
+ export declare function isStringArray(value: unknown): value is string[];
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isStringArray = void 0;
4
+ function isStringArray(value) {
5
+ return Array.isArray(value) && value.every((it) => typeof it === 'string');
6
+ }
7
+ exports.isStringArray = isStringArray;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cbst",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A cache buster that versions a website's files for immutable cache control",
5
5
  "author": "Morris Brodersen <mb@morrisbrodersen.de>",
6
6
  "license": "ISC",
@@ -20,7 +20,7 @@
20
20
  "build": "tsc --project tsconfig.build.json",
21
21
  "clean": "rm -rf coverage dist test/fixtures/out",
22
22
  "lint": "eslint .",
23
- "format": "pretter --write .",
23
+ "format": "prettier --write .",
24
24
  "format-check": "prettier --check .",
25
25
  "test": "jest --runInBand --coverage",
26
26
  "maybe-publish": "bash scripts/maybe-publish.sh"
@@ -1,5 +0,0 @@
1
- export declare function assertRecord(value: unknown, message: string): asserts value is Record<string, unknown>;
2
- export declare function assertString(value: unknown, message: string): asserts value is string;
3
- export declare function assertStringArray(value: unknown, message: string): asserts value is string[];
4
- export declare function assertNumber(value: unknown, message: string): void;
5
- export declare function assert(condition: boolean, message: string): asserts condition;
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assert = exports.assertNumber = exports.assertStringArray = exports.assertString = exports.assertRecord = void 0;
4
- const assert_1 = require("assert");
5
- function assertRecord(value, message) {
6
- assert(typeof value === 'object' && !!value && !Array.isArray(value), message);
7
- }
8
- exports.assertRecord = assertRecord;
9
- function assertString(value, message) {
10
- assert(typeof value === 'string', message);
11
- }
12
- exports.assertString = assertString;
13
- function assertStringArray(value, message) {
14
- assert(Array.isArray(value) && value.every((it) => typeof it === 'string'), message);
15
- }
16
- exports.assertStringArray = assertStringArray;
17
- function assertNumber(value, message) {
18
- assert(typeof value === 'number' && isFinite(value), message);
19
- }
20
- exports.assertNumber = assertNumber;
21
- function assert(condition, message) {
22
- if (!condition)
23
- throw new assert_1.AssertionError({ message });
24
- }
25
- exports.assert = assert;