cbst 0.1.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/LICENSE.md ADDED
@@ -0,0 +1,5 @@
1
+ Copyright 2022 Morris Brodersen <mb@morrisbrodersen.de>
2
+
3
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4
+
5
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # cbst
2
+
3
+ A cache buster that versions a website's files for immutable cache control.
4
+
5
+ - Takes a directory containing a website (i.e. HTML, CSS, JS and other files),
6
+ - appends version tags to static files,
7
+ - rewrites references to versioned files,
8
+ - and writes the result into an output directory.
9
+
10
+ ## Installation
11
+
12
+ ```
13
+ npm install cbst --save-dev # project installation (recommended)
14
+ npm install cbst --global # global installation
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```
20
+ cbst <input dir> <output dir> [<config file>]
21
+ ```
22
+
23
+ ## Example
24
+
25
+ This diff demonstrates how versioning is applied on a simple website:
26
+
27
+ ```diff
28
+ # index.html
29
+
30
+ <!DOCTYPE html>
31
+ <html>
32
+ <head>
33
+ <title>Hello, World!</title>
34
+ - <link rel="stylesheet" href="styles/main.css">
35
+ + <link rel="stylesheet" href="styles/main.ed1e118152.css">
36
+ </head>
37
+ <body>
38
+ <h1>Hello, World!</h1>
39
+ <p>
40
+ - <img id="welcome" src="assets/loading.png">
41
+ + <img id="welcome" src="assets/loading.834ab3df39.png">
42
+ </p>
43
+ <script type="module">
44
+ - import { main } from './scripts/main.js';
45
+ + import { main } from './scripts/main.f39e95e656.js';
46
+
47
+ setTimeout(main, 1000);
48
+ </script>
49
+ </body>
50
+ </html>
51
+
52
+ # scripts/main.js -> scripts/main.f39e95e656.js
53
+
54
+ - import { yell } from './yell.js';
55
+ + import { yell } from './yell.93724d33b5.js';
56
+
57
+ export function main() {
58
+ yell('hello');
59
+ - document.getElementById('welcome').src = 'assets/welcome.svg';
60
+ + document.getElementById('welcome').src = 'assets/welcome.afe45bb832.svg';
61
+ }
62
+
63
+ # styles/main.css -> styles/main.ed1e118152.css
64
+ # scripts/yell.js -> scripts/yell.93724d33b5.js
65
+ # etc.
66
+ ```
67
+
68
+ ## Configuration
69
+
70
+ The configuration file (JSON) supports the following properties:
71
+
72
+ - `exclude`
73
+ - List of file patterns to exclude.
74
+ - Defaults to `[]`.
75
+ - `source`
76
+ - List of file patterns to treat as sources with references to other files.
77
+ - Defaults to `['*.html', '*.css', '*.js', '*.svg']`.
78
+ - `html`
79
+ - List of file patterns to treat as HTML.
80
+ - Defaults to `['*.html']`.
81
+ - `dynamic`
82
+ - List of file patterns to treat as dynamic.
83
+ - Matching files will not be versioned.
84
+ - References from matching source files will be still be rewritten.
85
+ - Defaults to `['*.html']`.
86
+ - `manifest`
87
+ - Manifest filename.
88
+ - Defaults to `'.manifest.json'`.
89
+ - `hashLength`
90
+ - Length of hashes in versioned filenames.
91
+ - Defaults to `10`.
92
+
93
+ File patterns support `*` (slash-free wildcards) and `/**/` (directory wildcards).
94
+
95
+ ## Versioning and references
96
+
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
99
+
100
+ - are double- or single-quoted,
101
+ - contain no whitespace or quotes,
102
+ - and have a file extension.
103
+
104
+ If a reference can be resolved to a file, and that file is not `dynamic`,
105
+ the reference is rewritten with the versioned filename.
106
+
107
+ If a reference cannot be resolved to a file, the reference is not modified.
108
+
109
+ ## Static vs. dynamic files
110
+
111
+ **Static files** (not listed in `dynamic`) will be versioned based on a hash
112
+ of their contents, as well as the contents of any referenced files.
113
+ Circular references are resolved deterministically.
114
+
115
+ Static files should be delivered with a `Cache-Control` header that allows
116
+ browsers and proxies to cache them indefinitely. For example:
117
+
118
+ ```
119
+ Cache-Control: public, max-age=31536000, immutable
120
+ ```
121
+
122
+ **Dynamic files** (those listed in `dynamic`) will not be versioned, but any
123
+ references detected will be rewritten if necessary. For example,
124
+ `*.html` files are usually be marked dynamic because they are directly
125
+ visited, not indirectly requested like other files.
126
+
127
+ Dynamic files should be delivered with a `Cache-Control` header that
128
+ requires browsers and proxies to revalidate the file in a timely fashion.
129
+ Additional `E-Tag` or `Last-Modified` headers should be provided to
130
+ allow conditional requests. For example:
131
+
132
+ ```
133
+ Cache-Control: public, max-age=604800, stale-while-revalidate=86400
134
+ ETag: 0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33
135
+ ```
136
+
137
+ See also
138
+
139
+ - [Cache-Control (MDN)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
140
+ - [Conditional requests (MDN)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests)
141
+
142
+ ## Discussion
143
+
144
+ > I can't use my favorite libraries from NPM with this because they require Node.js resolution and/or bundling.
145
+
146
+ Chicken & egg problem here.
147
+ The industry got used to bundlers and started building libraries for the web
148
+ assuming that everyone uses a bundler.
149
+
150
+ Ask library authors to ship standard ESM modules.
151
+ That will make all our lives easier.
152
+
153
+ > Isn't bundling still more performant larger websites?
154
+
155
+ You should be fine if your website is delivered via HTTP/2 with compression and
156
+ solid cache control.
157
+
158
+ For recurring users, bundled websites that are modified regularly require
159
+ downloading/parsing the entire bundle after every modification.
160
+
161
+ With fine-grained file versioning and long-term caching,
162
+ the first page visit may suffer,
163
+ but recurring users will have a better experience.
164
+
165
+ Finally, avoiding frameworks and large dependencies is a much more effective
166
+ optimization in the first place.
167
+
168
+ > What about minification?
169
+
170
+ It's out of scope.
171
+ There are too many options to consider,
172
+ and any integration with minifiers will probably result in config/plug-in hell.
173
+
174
+ > Why is this implemented with regular expressions? Everyone knows you can't parse HTML, CSS, and JS like that!!1
175
+
176
+ It's a trade-off.
177
+ The RegExp-based implementation is simple, fast,
178
+ and will only fail in obscure cases (hopefully).
@@ -0,0 +1,91 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import { Cache } from './util/Cache';
4
+ import { Glob } from './util/Glob';
5
+ export interface CacheBusterConfig {
6
+ /**
7
+ * List of file patterns to exclude entirely.
8
+ * Defaults to an `[]`.
9
+ */
10
+ exclude?: string[];
11
+ /**
12
+ * List of file patterns to treat as source files with references.
13
+ * Defaults to `['*.html', '*.css', '*.js', '*.svg']`.
14
+ */
15
+ source?: string[];
16
+ /**
17
+ * List of file patterns to treat as HTML.
18
+ * Defaults to `['*.html']`.
19
+ */
20
+ html?: string[];
21
+ /**
22
+ * List of file patterns to treat as dynamic (filenames will not be versioned).
23
+ * Defaults to `['*.html']`.
24
+ */
25
+ dynamic?: string[];
26
+ /**
27
+ * Manifest filename.
28
+ * Defaults to `'.manifest.json'`
29
+ */
30
+ manifest?: string;
31
+ /**
32
+ * Length of hashes in versioned filenames.
33
+ * Defaults to 10.
34
+ */
35
+ hashLength?: number;
36
+ }
37
+ export interface CacheBusterOptions extends CacheBusterConfig {
38
+ /**
39
+ * Input directory
40
+ */
41
+ inputDir: string;
42
+ /**
43
+ * Output directory
44
+ */
45
+ outputDir: string;
46
+ /**
47
+ * Error handler
48
+ */
49
+ onError?: ErrorHandler;
50
+ }
51
+ export type ErrorHandler = (err: Error) => unknown;
52
+ export declare class CacheBuster {
53
+ static defaultConfig: Required<CacheBusterConfig>;
54
+ protected inputDir: string;
55
+ protected outputDir: string;
56
+ protected onError?: ErrorHandler;
57
+ protected excludeGlob: Glob;
58
+ protected sourceGlob: Glob;
59
+ protected htmlGlob: Glob;
60
+ protected dynamicGlob: Glob;
61
+ protected manifest: string;
62
+ protected hashLength: number;
63
+ protected hashFileCache: Cache<string | undefined>;
64
+ protected getReferencesCache: Cache<string[]>;
65
+ protected hashRawFileCache: Cache<string>;
66
+ protected readFileCache: Cache<Buffer>;
67
+ protected map: Record<string, string>;
68
+ protected referenceRx: RegExp;
69
+ protected baseRx: RegExp;
70
+ protected extensionRx: RegExp;
71
+ constructor(options: CacheBusterOptions);
72
+ run(): Promise<void>;
73
+ writeManifest(): Promise<void>;
74
+ handleDir(dir: string): Promise<undefined>;
75
+ handleFile(file: string): Promise<undefined>;
76
+ transformFile(file: string): Promise<string | Buffer>;
77
+ hashFile(file: string): Promise<string | undefined>;
78
+ hashFileReferences(file: string, exclude: string[]): Promise<string[]>;
79
+ hashRawFile(file: string): Promise<string>;
80
+ handleReferenceError(err: Error, source: string, reference: string): void;
81
+ getReferences(file: string): Promise<string[]>;
82
+ isReference(reference: string): boolean;
83
+ resolveReference(base: string, reference: string): string;
84
+ getBase(file: string): Promise<string>;
85
+ formatVersion(hash: string): string;
86
+ hash(inputs: (string | Buffer)[]): string;
87
+ readFile(file: string): Promise<Buffer>;
88
+ readDir(dir: string): Promise<import("fs").Dirent[]>;
89
+ writeFile(file: string, data: string | Buffer): Promise<void>;
90
+ safePath(rootDir: string, candidate: string): string;
91
+ }
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CacheBuster = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const ReferenceError_1 = require("./ReferenceError");
8
+ const assert_1 = require("./util/assert");
9
+ const Cache_1 = require("./util/Cache");
10
+ const Glob_1 = require("./util/Glob");
11
+ class CacheBuster {
12
+ constructor(options) {
13
+ this.hashFileCache = new Cache_1.Cache((file) => this.hashFile(file));
14
+ this.getReferencesCache = new Cache_1.Cache((file) => this.getReferences(file));
15
+ this.hashRawFileCache = new Cache_1.Cache((file) => this.hashRawFile(file));
16
+ 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;
19
+ this.baseRx = /<base[^<>]+href\s*=\s*"([^"]+)"[^<>]*>/i;
20
+ this.extensionRx = /(?<=\.)[^.]+$/;
21
+ const o = { ...CacheBuster.defaultConfig, ...options };
22
+ this.inputDir = o.inputDir;
23
+ this.outputDir = o.outputDir;
24
+ this.onError = o.onError;
25
+ this.excludeGlob = new Glob_1.Glob(o.exclude);
26
+ this.sourceGlob = new Glob_1.Glob(o.source);
27
+ this.htmlGlob = new Glob_1.Glob(o.html);
28
+ this.dynamicGlob = new Glob_1.Glob(o.dynamic);
29
+ this.manifest = o.manifest;
30
+ this.hashLength = o.hashLength;
31
+ }
32
+ async run() {
33
+ await this.handleDir('.');
34
+ await this.writeManifest();
35
+ }
36
+ async writeManifest() {
37
+ await this.writeFile(this.manifest, JSON.stringify({ map: this.map }));
38
+ }
39
+ async handleDir(dir) {
40
+ if (this.excludeGlob.match(dir))
41
+ return undefined;
42
+ const entries = await this.readDir(dir);
43
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
44
+ for (const entry of entries) {
45
+ if (entry.isFile()) {
46
+ await this.handleFile(path_1.posix.join(dir, entry.name));
47
+ }
48
+ else if (entry.isDirectory()) {
49
+ await this.handleDir(path_1.posix.join(dir, entry.name));
50
+ }
51
+ }
52
+ }
53
+ async handleFile(file) {
54
+ if (this.excludeGlob.match(file))
55
+ return undefined;
56
+ const output = await this.transformFile(file);
57
+ const hash = await this.hashFileCache.get(file);
58
+ const outputFile = hash
59
+ ? file.replace(this.extensionRx, (extension) => `${this.formatVersion(hash)}.${extension}`)
60
+ : file;
61
+ this.map[file] = outputFile;
62
+ await this.writeFile(outputFile, output);
63
+ if (!this.sourceGlob.match(file)) {
64
+ this.readFileCache.delete(file);
65
+ }
66
+ }
67
+ async transformFile(file) {
68
+ const references = await this.getReferencesCache.get(file);
69
+ const buffer = await this.readFileCache.get(file);
70
+ if (references.length === 0) {
71
+ return buffer;
72
+ }
73
+ const hashes = await Promise.all(references.map((reference) => this.hashFileCache.get(reference).catch((err) => {
74
+ this.handleReferenceError(err, file, reference);
75
+ return undefined;
76
+ })));
77
+ const source = buffer.toString();
78
+ let i = 0;
79
+ return source.replace(this.referenceRx, (match, ...groups) => {
80
+ 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];
84
+ if (!this.isReference(reference))
85
+ return match;
86
+ const hash = hashes[i++];
87
+ if (!hash)
88
+ return match;
89
+ return `${quote}${filename}.${this.formatVersion(hash)}.${extension}${quote}`;
90
+ });
91
+ }
92
+ async hashFile(file) {
93
+ if (this.dynamicGlob.match(file))
94
+ return undefined;
95
+ return this.hash([
96
+ await this.hashRawFileCache.get(file),
97
+ ...(await this.hashFileReferences(file, [])),
98
+ ]);
99
+ }
100
+ async hashFileReferences(file, exclude) {
101
+ if (exclude.includes(file))
102
+ return [];
103
+ const references = await this.getReferencesCache.get(file);
104
+ const direct = await Promise.all(references.map((it) => this.hashRawFileCache.get(it).catch((err) => {
105
+ this.handleReferenceError(err, file, it);
106
+ return '';
107
+ })));
108
+ const deep = await Promise.all(references.map((it) => this.hashFileReferences(it, [...exclude, file])));
109
+ return [...direct, ...deep.flat()];
110
+ }
111
+ async hashRawFile(file) {
112
+ const buffer = await this.readFileCache.get(file);
113
+ return this.hash([buffer]);
114
+ }
115
+ handleReferenceError(err, source, reference) {
116
+ if (this.onError) {
117
+ this.onError?.(new ReferenceError_1.ReferenceError(err, source, reference));
118
+ }
119
+ }
120
+ // references
121
+ async getReferences(file) {
122
+ if (!this.sourceGlob.match(file))
123
+ return [];
124
+ const buffer = await this.readFileCache.get(file);
125
+ const source = buffer.toString();
126
+ const base = await this.getBase(file);
127
+ const references = [];
128
+ for (const match of source.matchAll(this.referenceRx)) {
129
+ const reference = match[3] || match[8];
130
+ if (this.isReference(reference)) {
131
+ references.push(this.resolveReference(base, reference));
132
+ }
133
+ }
134
+ return references;
135
+ }
136
+ isReference(reference) {
137
+ return !reference.includes('//');
138
+ }
139
+ resolveReference(base, reference) {
140
+ if (reference[0] === '/')
141
+ return reference.slice(1);
142
+ return path_1.posix.join(base[0] === '/' ? base.slice(1) : base, reference);
143
+ }
144
+ async getBase(file) {
145
+ if (this.htmlGlob.match(file)) {
146
+ const buffer = await this.readFileCache.get(file);
147
+ const source = buffer.toString();
148
+ const match = source.match(this.baseRx);
149
+ if (match)
150
+ return match[1];
151
+ }
152
+ return path_1.posix.dirname(file);
153
+ }
154
+ // hashing
155
+ formatVersion(hash) {
156
+ return hash.slice(0, this.hashLength);
157
+ }
158
+ hash(inputs) {
159
+ const h = (0, crypto_1.createHash)('sha1');
160
+ for (const input of inputs)
161
+ h.update(input);
162
+ return h.digest('hex');
163
+ }
164
+ // i/o
165
+ async readFile(file) {
166
+ return fs_1.promises.readFile(this.safePath(this.inputDir, file));
167
+ }
168
+ async readDir(dir) {
169
+ return fs_1.promises.readdir(this.safePath(this.inputDir, dir), {
170
+ withFileTypes: true,
171
+ });
172
+ }
173
+ async writeFile(file, data) {
174
+ const outputFile = this.safePath(this.outputDir, file);
175
+ await fs_1.promises.mkdir(path_1.posix.dirname(outputFile), { recursive: true });
176
+ return fs_1.promises.writeFile(outputFile, data);
177
+ }
178
+ safePath(rootDir, candidate) {
179
+ 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}`);
181
+ return s;
182
+ }
183
+ }
184
+ exports.CacheBuster = CacheBuster;
185
+ CacheBuster.defaultConfig = {
186
+ exclude: [],
187
+ source: ['*.html', '*.css', '*.js', '*.svg'],
188
+ html: ['*.html'],
189
+ dynamic: ['*.html'],
190
+ manifest: '.manifest.json',
191
+ hashLength: 10,
192
+ };
@@ -0,0 +1,9 @@
1
+ import { CacheBusterConfig } from './CacheBuster';
2
+ import { ConsoleLike } from './util/ConsoleLike';
3
+ export declare class CacheBusterCli {
4
+ protected console: ConsoleLike;
5
+ constructor(console?: ConsoleLike);
6
+ run(argv: string[], noExit?: boolean): Promise<void>;
7
+ help(): string;
8
+ loadConfig(file: string): Promise<CacheBusterConfig>;
9
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CacheBusterCli = void 0;
4
+ const fs_1 = require("fs");
5
+ const CacheBuster_1 = require("./CacheBuster");
6
+ const assert_1 = require("./util/assert");
7
+ class CacheBusterCli {
8
+ constructor(console = global.console) {
9
+ this.console = console;
10
+ }
11
+ async run(argv, noExit = false) {
12
+ try {
13
+ if (argv.includes('--help')) {
14
+ this.console.log(this.help());
15
+ return;
16
+ }
17
+ const [inputDir, outputDir, configFile] = argv;
18
+ if (!inputDir)
19
+ throw new Error('No input directory given');
20
+ if (!outputDir)
21
+ throw new Error('No output directory given');
22
+ const config = configFile ? await this.loadConfig(configFile) : undefined;
23
+ const cacheBuster = new CacheBuster_1.CacheBuster({
24
+ ...config,
25
+ inputDir,
26
+ outputDir,
27
+ onError: (err) => this.console.error(`Warning: ${err.message}`),
28
+ });
29
+ await cacheBuster.run();
30
+ }
31
+ catch (err) {
32
+ this.console.error(err instanceof Error ? err.message : `${err}`);
33
+ this.console.error(this.help());
34
+ if (noExit)
35
+ throw err;
36
+ process.exit(1);
37
+ }
38
+ }
39
+ help() {
40
+ return `Usage:
41
+ cbst <input dir> <output dir> [<config file>]`;
42
+ }
43
+ async loadConfig(file) {
44
+ 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');
52
+ return config;
53
+ }
54
+ }
55
+ exports.CacheBusterCli = CacheBusterCli;
@@ -0,0 +1,6 @@
1
+ export declare class ReferenceError extends Error {
2
+ originalError: Error;
3
+ source: string;
4
+ reference: string;
5
+ constructor(originalError: Error, source: string, reference: string);
6
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReferenceError = void 0;
4
+ class ReferenceError extends Error {
5
+ constructor(originalError, source, reference) {
6
+ super(`Could not resolve reference ${reference} from ${source} (${originalError.message})`);
7
+ this.originalError = originalError;
8
+ this.source = source;
9
+ this.reference = reference;
10
+ }
11
+ }
12
+ exports.ReferenceError = ReferenceError;
package/dist/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const CacheBusterCli_1 = require("./CacheBusterCli");
4
+ const cli = new CacheBusterCli_1.CacheBusterCli();
5
+ cli.run(process.argv.slice(2));
@@ -0,0 +1,3 @@
1
+ export * from './CacheBuster';
2
+ export * from './CacheBusterCli';
3
+ export * from './ReferenceError';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./CacheBuster"), exports);
18
+ __exportStar(require("./CacheBusterCli"), exports);
19
+ __exportStar(require("./ReferenceError"), exports);
@@ -0,0 +1,8 @@
1
+ export type CacheFn<T> = (key: string) => Promise<T>;
2
+ export declare class Cache<T> {
3
+ protected fn: CacheFn<T>;
4
+ protected map: Map<string, Promise<T>>;
5
+ constructor(fn: CacheFn<T>);
6
+ get(key: string): Promise<T>;
7
+ delete(key: string): void;
8
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Cache = void 0;
4
+ class Cache {
5
+ constructor(fn) {
6
+ this.fn = fn;
7
+ this.map = new Map();
8
+ }
9
+ get(key) {
10
+ const cached = this.map.get(key);
11
+ if (cached)
12
+ return cached;
13
+ const result = this.fn(key);
14
+ this.map.set(key, result);
15
+ return result;
16
+ }
17
+ delete(key) {
18
+ this.map.delete(key);
19
+ }
20
+ }
21
+ exports.Cache = Cache;
@@ -0,0 +1,4 @@
1
+ export interface ConsoleLike {
2
+ log(message: string): unknown;
3
+ error(message: string | Error): unknown;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,11 @@
1
+ interface CompiledPattern {
2
+ inverted: boolean;
3
+ rx: RegExp;
4
+ }
5
+ export declare class Glob {
6
+ protected patterns: CompiledPattern[];
7
+ constructor(patterns: string[]);
8
+ match(file: string): boolean;
9
+ protected compile(pattern: string): CompiledPattern;
10
+ }
11
+ export {};
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Glob = void 0;
4
+ class Glob {
5
+ constructor(patterns) {
6
+ this.patterns = patterns.map((pattern) => this.compile(pattern));
7
+ }
8
+ match(file) {
9
+ let matched = false;
10
+ for (const compiled of this.patterns) {
11
+ if (compiled.inverted) {
12
+ if (file.match(compiled.rx))
13
+ return false;
14
+ }
15
+ else if (!matched) {
16
+ if (file.match(compiled.rx))
17
+ matched = true;
18
+ }
19
+ }
20
+ return matched;
21
+ }
22
+ compile(pattern) {
23
+ const inverted = !!pattern.match(/^!/);
24
+ const absolutePrefix = pattern.match(/^!?\//) ? '^' : '';
25
+ const rxBase = pattern
26
+ .slice(inverted ? 1 : 0)
27
+ .replace(/(\/\*\*\/)|(\*\*)|(\*)|([.+])/g, (_, ...groups) => {
28
+ if (groups[0]) {
29
+ // directory wildcard
30
+ return '(/.+?/|/)';
31
+ }
32
+ else if (groups[1]) {
33
+ throw new Error(`Invalid glob pattern ${pattern}; double star must be enclosed by slashes`);
34
+ }
35
+ else if (groups[2]) {
36
+ // slash-free wildcard
37
+ return '[^/]*';
38
+ }
39
+ else {
40
+ // . or +
41
+ return `\\${groups[3]}`;
42
+ }
43
+ });
44
+ const rx = new RegExp(absolutePrefix + rxBase + '$');
45
+ return {
46
+ inverted,
47
+ rx,
48
+ };
49
+ }
50
+ }
51
+ exports.Glob = Glob;
@@ -0,0 +1,5 @@
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;
@@ -0,0 +1,25 @@
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;
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "cbst",
3
+ "version": "0.1.0",
4
+ "description": "A cache buster that versions a website's files for immutable cache control",
5
+ "author": "Morris Brodersen <mb@morrisbrodersen.de>",
6
+ "license": "ISC",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/morris/cbst.git"
10
+ },
11
+ "engines": {
12
+ "node": ">=14"
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "main": "dist/index.js",
18
+ "bin": "dist/bin.js",
19
+ "scripts": {
20
+ "build": "tsc --project tsconfig.build.json",
21
+ "clean": "rm -rf coverage dist test/fixtures/out",
22
+ "lint": "eslint .",
23
+ "format": "pretter --write .",
24
+ "format-check": "prettier --check .",
25
+ "test": "jest --runInBand --coverage",
26
+ "maybe-publish": "bash scripts/maybe-publish.sh"
27
+ },
28
+ "devDependencies": {
29
+ "@types/jest": "^29.1.2",
30
+ "@types/node": "^14.18.31",
31
+ "@typescript-eslint/eslint-plugin": "^5.23.0",
32
+ "@typescript-eslint/parser": "^5.23.0",
33
+ "eslint": "^8.15.0",
34
+ "jest": "^29.1.2",
35
+ "prettier": "^2.6.2",
36
+ "ts-jest": "^29.0.3",
37
+ "ts-node": "^10.9.1",
38
+ "typescript": "^4.6.4"
39
+ }
40
+ }