@vanhanit/pre-compress 1.0.1
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 +91 -0
- package/README.md +103 -0
- package/dist/args.js +59 -0
- package/dist/cli.js +64 -0
- package/dist/compress.js +56 -0
- package/dist/concurrency.js +28 -0
- package/dist/files.js +51 -0
- package/dist/format.js +32 -0
- package/dist/main.js +3 -0
- package/dist/package-info.js +8 -0
- package/package.json +63 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Required Notice: Copyright (c) 2021-2026 Thomas Vanhaniemi (https://github.com/vanhanit)
|
|
2
|
+
|
|
3
|
+
# PolyForm Shield License 1.0.0
|
|
4
|
+
|
|
5
|
+
<https://polyformproject.org/licenses/shield/1.0.0>
|
|
6
|
+
|
|
7
|
+
## Acceptance
|
|
8
|
+
|
|
9
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
10
|
+
|
|
11
|
+
## Copyright License
|
|
12
|
+
|
|
13
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
14
|
+
|
|
15
|
+
## Distribution License
|
|
16
|
+
|
|
17
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
18
|
+
|
|
19
|
+
## Notices
|
|
20
|
+
|
|
21
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
22
|
+
|
|
23
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
24
|
+
|
|
25
|
+
## Changes and New Works License
|
|
26
|
+
|
|
27
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
28
|
+
|
|
29
|
+
## Patent License
|
|
30
|
+
|
|
31
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
32
|
+
|
|
33
|
+
## Noncompete
|
|
34
|
+
|
|
35
|
+
Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
|
|
36
|
+
|
|
37
|
+
## Competition
|
|
38
|
+
|
|
39
|
+
Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
|
|
40
|
+
|
|
41
|
+
## New Products
|
|
42
|
+
|
|
43
|
+
If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
|
|
44
|
+
|
|
45
|
+
## Discontinued Products
|
|
46
|
+
|
|
47
|
+
You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
|
|
48
|
+
|
|
49
|
+
> Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
|
|
50
|
+
|
|
51
|
+
## Sales of Business
|
|
52
|
+
|
|
53
|
+
If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
|
|
54
|
+
|
|
55
|
+
## Fair Use
|
|
56
|
+
|
|
57
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
58
|
+
|
|
59
|
+
## No Other Rights
|
|
60
|
+
|
|
61
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
62
|
+
|
|
63
|
+
## Patent Defense
|
|
64
|
+
|
|
65
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
66
|
+
|
|
67
|
+
## Violations
|
|
68
|
+
|
|
69
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
70
|
+
|
|
71
|
+
## No Liability
|
|
72
|
+
|
|
73
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
74
|
+
|
|
75
|
+
## Definitions
|
|
76
|
+
|
|
77
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
78
|
+
|
|
79
|
+
A **product** can be a good or service, or a combination of them.
|
|
80
|
+
|
|
81
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
82
|
+
|
|
83
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
|
|
84
|
+
|
|
85
|
+
**Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
|
|
86
|
+
|
|
87
|
+
**Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
88
|
+
|
|
89
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
90
|
+
|
|
91
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
package/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# pre-compress
|
|
2
|
+
|
|
3
|
+
[](https://github.com/vanhanit/pre-compress/actions/workflows/main.yml)
|
|
4
|
+
[](https://sonarcloud.io/summary/new_code?id=vanhanit_pre-compress)
|
|
5
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
6
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
7
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
8
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
9
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
10
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
11
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
12
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
13
|
+
[](https://sonarcloud.io/dashboard?id=vanhanit_pre-compress)
|
|
14
|
+
|
|
15
|
+
> Compress static files to be served by a web server.
|
|
16
|
+
|
|
17
|
+
pre-compress writes a gzip (`.gz`) and a brotli (`.br`) version next to each file matched by the glob patterns, using
|
|
18
|
+
the highest compression levels. A web server can then send the compressed file from disk instead of compressing it on
|
|
19
|
+
every request, for example with `gzip_static` and `brotli_static` in nginx.
|
|
20
|
+
|
|
21
|
+
- Files that are already compressed (`.gz` and `.br`) are never compressed again.
|
|
22
|
+
- Compressed files are written atomically, so a server never sends a partially written file.
|
|
23
|
+
- No dependencies, only Node.js built-ins.
|
|
24
|
+
- Free to use, also in companies, under the [PolyForm Shield License](#license).
|
|
25
|
+
|
|
26
|
+
Requires Node.js 22.18 or newer.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
The package is published as `@vanhanit/pre-compress` and installs the `pre-compress` command.
|
|
31
|
+
|
|
32
|
+
Run it without installing:
|
|
33
|
+
|
|
34
|
+
```shell
|
|
35
|
+
npx @vanhanit/pre-compress --files "dist/**/*.{html,css,js,svg}"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Install it globally:
|
|
39
|
+
|
|
40
|
+
```shell
|
|
41
|
+
npm install --global @vanhanit/pre-compress
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Or add it to a project and compress the build output after each build:
|
|
45
|
+
|
|
46
|
+
```shell
|
|
47
|
+
npm install --save-dev @vanhanit/pre-compress
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "vite build",
|
|
54
|
+
"postbuild": "pre-compress --delete-larger --skip-existing --files \"dist/**/*.{html,css,js,svg}\""
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Usage
|
|
60
|
+
|
|
61
|
+
```shell
|
|
62
|
+
Usage: pre-compress [options]
|
|
63
|
+
|
|
64
|
+
Compress static files to be served by a web server.
|
|
65
|
+
|
|
66
|
+
Options:
|
|
67
|
+
-f, --files <files...> the files to compress, supports glob patterns to match multiple files
|
|
68
|
+
-d, --delete-larger delete compressed files that are not smaller than the source
|
|
69
|
+
-s, --skip-existing don't compress if the compressed version is newer than the source
|
|
70
|
+
-V, --version output the version number
|
|
71
|
+
-h, --help display help for command
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Quote the patterns so the shell passes them on unexpanded:
|
|
75
|
+
|
|
76
|
+
```shell
|
|
77
|
+
pre-compress --delete-larger --skip-existing --files "dist/**/*.{html,css,js,svg}"
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
- `--delete-larger` removes compressed versions that would not save any bytes, so the server sends the source instead.
|
|
81
|
+
- `--skip-existing` only compresses files that changed since they were last compressed, which speeds up repeated runs.
|
|
82
|
+
|
|
83
|
+
The command exits with code 1 when the arguments are invalid or a file cannot be compressed.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```shell
|
|
88
|
+
npm ci
|
|
89
|
+
npm run check # lint, formatting, type check and tests
|
|
90
|
+
npm run build # compile to dist/
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
pre-compress is licensed under the [PolyForm Shield License 1.0.0](LICENSE). You may use it for any purpose, also in
|
|
96
|
+
commercial projects and companies of any size, and you may fork, change and redistribute it. You may not use it to
|
|
97
|
+
provide a product that competes with it, such as selling pre-compress or a service built on it.
|
|
98
|
+
|
|
99
|
+
For a commercial license without these limits, contact [@vanhanit](https://github.com/vanhanit).
|
|
100
|
+
|
|
101
|
+
Contributions are welcome, see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
102
|
+
|
|
103
|
+
Version 1.0.0 was published under the MIT License.
|
package/dist/args.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
/**
|
|
3
|
+
* Invalid command line arguments.
|
|
4
|
+
*/
|
|
5
|
+
export class ArgumentError extends Error {
|
|
6
|
+
name = "ArgumentError";
|
|
7
|
+
}
|
|
8
|
+
const OPTIONS = {
|
|
9
|
+
files: { type: "string", short: "f", multiple: true },
|
|
10
|
+
"delete-larger": { type: "boolean", short: "d" },
|
|
11
|
+
"skip-existing": { type: "boolean", short: "s" },
|
|
12
|
+
version: { type: "boolean", short: "V" },
|
|
13
|
+
help: { type: "boolean", short: "h" }
|
|
14
|
+
};
|
|
15
|
+
const HELP = [
|
|
16
|
+
["-f, --files <files...>", "the files to compress, supports glob patterns to match multiple files"],
|
|
17
|
+
["-d, --delete-larger", "delete compressed files that are not smaller than the source"],
|
|
18
|
+
["-s, --skip-existing", "don't compress if the compressed version is newer than the source"],
|
|
19
|
+
["-V, --version", "output the version number"],
|
|
20
|
+
["-h, --help", "display help for command"]
|
|
21
|
+
];
|
|
22
|
+
function parse(args) {
|
|
23
|
+
try {
|
|
24
|
+
return parseArgs({ args: [...args], options: OPTIONS, allowPositionals: true });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
throw new ArgumentError(error.message);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Parses the command line arguments, without the node and script paths. Patterns may follow `-f` or be repeated.
|
|
32
|
+
*/
|
|
33
|
+
export function parseArguments(args) {
|
|
34
|
+
const { values, positionals } = parse(args);
|
|
35
|
+
if (values.help) {
|
|
36
|
+
return { name: "help" };
|
|
37
|
+
}
|
|
38
|
+
if (values.version) {
|
|
39
|
+
return { name: "version" };
|
|
40
|
+
}
|
|
41
|
+
const patterns = [...(values.files ?? []), ...positionals];
|
|
42
|
+
if (patterns.length === 0) {
|
|
43
|
+
throw new ArgumentError("required option '-f, --files <files...>' not specified");
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
name: "compress",
|
|
47
|
+
patterns,
|
|
48
|
+
deleteLarger: values["delete-larger"] ?? false,
|
|
49
|
+
skipExisting: values["skip-existing"] ?? false
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Returns the help text.
|
|
54
|
+
*/
|
|
55
|
+
export function usage(name, description) {
|
|
56
|
+
const width = Math.max(...HELP.map(([flags]) => flags.length));
|
|
57
|
+
const options = HELP.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`);
|
|
58
|
+
return [`Usage: ${name} [options]`, "", description, "", "Options:", ...options].join("\n");
|
|
59
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { availableParallelism } from "node:os";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
import { styleText } from "node:util";
|
|
4
|
+
import { ArgumentError, parseArguments, usage } from "./args.js";
|
|
5
|
+
import { compressFile, isCompressed } from "./compress.js";
|
|
6
|
+
import { mapConcurrently } from "./concurrency.js";
|
|
7
|
+
import { findFiles } from "./files.js";
|
|
8
|
+
import { formatDuration, pluralize } from "./format.js";
|
|
9
|
+
import { readPackageInfo } from "./package-info.js";
|
|
10
|
+
function report({ file, size, outputs }, io) {
|
|
11
|
+
for (const output of outputs) {
|
|
12
|
+
if (output.status === "written") {
|
|
13
|
+
io.log(`Compressed file ${styleText("yellow", file)} to ${styleText("green", output.file)}`);
|
|
14
|
+
}
|
|
15
|
+
else if (output.status === "skipped") {
|
|
16
|
+
io.log(`Skipped file ${styleText("yellow", output.file)} because it is up to date`);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
io.log(`Deleted file ${styleText("red", output.file)} because ${output.size} byte(s) is not smaller than ${size} byte(s)`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function compress(command, io) {
|
|
24
|
+
const startTime = performance.now();
|
|
25
|
+
const files = (await findFiles(command.patterns)).filter((file) => !isCompressed(file));
|
|
26
|
+
const results = await mapConcurrently(files, availableParallelism(), async (file) => {
|
|
27
|
+
const result = await compressFile(file, command);
|
|
28
|
+
report(result, io);
|
|
29
|
+
return result;
|
|
30
|
+
});
|
|
31
|
+
const timeTakenMs = performance.now() - startTime;
|
|
32
|
+
const outputs = results.flatMap((result) => result.outputs);
|
|
33
|
+
const count = (status) => outputs.filter((output) => output.status === status).length;
|
|
34
|
+
io.log(`Processed ${pluralize(files.length, "file")} in ${styleText("green", formatDuration(timeTakenMs))}: ` +
|
|
35
|
+
`${styleText("green", String(count("written")))} written, ` +
|
|
36
|
+
`${styleText("yellowBright", String(count("skipped")))} skipped, ` +
|
|
37
|
+
`${styleText("red", String(count("deleted")))} deleted`);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Runs the command line interface with the arguments, without the node and script paths, and returns the exit code.
|
|
41
|
+
*/
|
|
42
|
+
export async function run(args, io = console) {
|
|
43
|
+
const { command: name, version, description } = readPackageInfo();
|
|
44
|
+
try {
|
|
45
|
+
const command = parseArguments(args);
|
|
46
|
+
if (command.name === "help") {
|
|
47
|
+
io.log(usage(name, description));
|
|
48
|
+
}
|
|
49
|
+
else if (command.name === "version") {
|
|
50
|
+
io.log(version);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
await compress(command, io);
|
|
54
|
+
}
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
io.error(`error: ${error instanceof Error ? error.message : String(error)}`);
|
|
59
|
+
if (error instanceof ArgumentError) {
|
|
60
|
+
io.error(`Run '${name} --help' for usage.`);
|
|
61
|
+
}
|
|
62
|
+
return 1;
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/compress.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readFile, rm, stat } from "node:fs/promises";
|
|
2
|
+
import { extname } from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { brotliCompress, constants, gzip } from "node:zlib";
|
|
5
|
+
import { replaceFile, statFile } from "./files.js";
|
|
6
|
+
const gzipAsync = promisify(gzip);
|
|
7
|
+
const brotliCompressAsync = promisify(brotliCompress);
|
|
8
|
+
const ENCODINGS = [
|
|
9
|
+
{
|
|
10
|
+
extension: "gz",
|
|
11
|
+
compress: (data) => gzipAsync(data, { level: constants.Z_BEST_COMPRESSION })
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
extension: "br",
|
|
15
|
+
compress: (data) => brotliCompressAsync(data, {
|
|
16
|
+
params: {
|
|
17
|
+
[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT,
|
|
18
|
+
[constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,
|
|
19
|
+
[constants.BROTLI_PARAM_SIZE_HINT]: data.length
|
|
20
|
+
}
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
];
|
|
24
|
+
/**
|
|
25
|
+
* Whether the file has the extension of a compressed file this tool writes.
|
|
26
|
+
*/
|
|
27
|
+
export function isCompressed(file) {
|
|
28
|
+
const extension = extname(file).slice(1).toLowerCase();
|
|
29
|
+
return ENCODINGS.some((encoding) => encoding.extension === extension);
|
|
30
|
+
}
|
|
31
|
+
async function isUpToDate(target, source) {
|
|
32
|
+
const stats = await statFile(target);
|
|
33
|
+
return stats !== undefined && stats.mtimeMs >= source.mtimeMs;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Writes a compressed file next to the source for every encoding.
|
|
37
|
+
*/
|
|
38
|
+
export async function compressFile(file, options) {
|
|
39
|
+
const source = await stat(file);
|
|
40
|
+
let data;
|
|
41
|
+
const outputs = await Promise.all(ENCODINGS.map(async (encoding) => {
|
|
42
|
+
const target = `${file}.${encoding.extension}`;
|
|
43
|
+
if (options.skipExisting && (await isUpToDate(target, source))) {
|
|
44
|
+
return { file: target, status: "skipped" };
|
|
45
|
+
}
|
|
46
|
+
data ??= readFile(file);
|
|
47
|
+
const compressed = await encoding.compress(await data);
|
|
48
|
+
if (options.deleteLarger && compressed.length >= source.size) {
|
|
49
|
+
await rm(target, { force: true });
|
|
50
|
+
return { file: target, status: "deleted", size: compressed.length };
|
|
51
|
+
}
|
|
52
|
+
await replaceFile(target, compressed);
|
|
53
|
+
return { file: target, status: "written", size: compressed.length };
|
|
54
|
+
}));
|
|
55
|
+
return { file, size: source.size, outputs };
|
|
56
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps items with an async mapper, running at most `concurrency` mappers at once. The results keep the input order.
|
|
3
|
+
* Rejects with the first error, after which no more items are started.
|
|
4
|
+
*/
|
|
5
|
+
export async function mapConcurrently(items, concurrency, mapper) {
|
|
6
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
7
|
+
throw new RangeError(`Concurrency must be a positive integer, got ${concurrency}`);
|
|
8
|
+
}
|
|
9
|
+
const results = [];
|
|
10
|
+
let next = 0;
|
|
11
|
+
let failed = false;
|
|
12
|
+
const worker = async () => {
|
|
13
|
+
if (failed || next >= items.length) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const index = next++;
|
|
17
|
+
try {
|
|
18
|
+
results[index] = await mapper(items[index]);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
failed = true;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
return worker();
|
|
25
|
+
};
|
|
26
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
27
|
+
return results;
|
|
28
|
+
}
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { glob, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* Returns the stats of the file at the path, following symbolic links. Undefined when it is missing or not a file.
|
|
6
|
+
*/
|
|
7
|
+
export async function statFile(path) {
|
|
8
|
+
try {
|
|
9
|
+
const stats = await stat(path);
|
|
10
|
+
return stats.isFile() ? stats : undefined;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error.code === "ENOENT") {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Finds the files matching any of the glob patterns. Paths are relative to `cwd`, unless the pattern is absolute.
|
|
21
|
+
* Directories, dotfiles and broken symbolic links are skipped.
|
|
22
|
+
*/
|
|
23
|
+
export async function findFiles(patterns, cwd = process.cwd()) {
|
|
24
|
+
const matches = new Map();
|
|
25
|
+
for await (const match of glob([...patterns], { cwd })) {
|
|
26
|
+
const path = resolve(cwd, match);
|
|
27
|
+
if (!matches.has(path)) {
|
|
28
|
+
matches.set(path, match);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const entries = [...matches];
|
|
32
|
+
const stats = await Promise.all(entries.map(([path]) => statFile(path)));
|
|
33
|
+
return entries
|
|
34
|
+
.filter((_, index) => stats[index] !== undefined)
|
|
35
|
+
.map(([, match]) => match)
|
|
36
|
+
.sort((a, b) => a.localeCompare(b));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Writes the data to a hidden temporary file and renames it to the path, so readers never see a partial file.
|
|
40
|
+
*/
|
|
41
|
+
export async function replaceFile(path, data) {
|
|
42
|
+
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
43
|
+
try {
|
|
44
|
+
await writeFile(temporary, data);
|
|
45
|
+
await rename(temporary, path);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
await rm(temporary, { force: true });
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const TENTHS_PER_UNIT = [
|
|
2
|
+
["hour", 36_000],
|
|
3
|
+
["minute", 600]
|
|
4
|
+
];
|
|
5
|
+
/**
|
|
6
|
+
* Returns the count with the unit, adding an s unless the count is one.
|
|
7
|
+
*/
|
|
8
|
+
export function pluralize(count, unit) {
|
|
9
|
+
return `${count} ${unit}${count === 1 ? "" : "s"}`;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Formats a duration for humans, e.g. `1 minute 1.5 seconds`.
|
|
13
|
+
*/
|
|
14
|
+
export function formatDuration(milliseconds) {
|
|
15
|
+
const rounded = Math.round(milliseconds);
|
|
16
|
+
if (rounded < 1000) {
|
|
17
|
+
return pluralize(rounded, "millisecond");
|
|
18
|
+
}
|
|
19
|
+
let tenths = Math.round(milliseconds / 100);
|
|
20
|
+
const parts = [];
|
|
21
|
+
for (const [unit, size] of TENTHS_PER_UNIT) {
|
|
22
|
+
const count = Math.floor(tenths / size);
|
|
23
|
+
if (count > 0) {
|
|
24
|
+
parts.push(pluralize(count, unit));
|
|
25
|
+
tenths -= count * size;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (tenths > 0) {
|
|
29
|
+
parts.push(pluralize(tenths / 10, "second"));
|
|
30
|
+
}
|
|
31
|
+
return parts.join(" ");
|
|
32
|
+
}
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Reads the command name, version and description from package.json.
|
|
4
|
+
*/
|
|
5
|
+
export function readPackageInfo() {
|
|
6
|
+
const { bin, version, description } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
7
|
+
return { command: Object.keys(bin)[0], version, description };
|
|
8
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vanhanit/pre-compress",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Compress static files to be served by a web server.",
|
|
5
|
+
"author": "Thomas Vanhaniemi",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"pre-compress": "dist/main.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public",
|
|
15
|
+
"provenance": true
|
|
16
|
+
},
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22.18.0"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "https://github.com/vanhanit/pre-compress.git"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/vanhanit/pre-compress#readme",
|
|
25
|
+
"bugs": {
|
|
26
|
+
"url": "https://github.com/vanhanit/pre-compress/issues"
|
|
27
|
+
},
|
|
28
|
+
"license": "PolyForm-Shield-1.0.0",
|
|
29
|
+
"keywords": [
|
|
30
|
+
"compress",
|
|
31
|
+
"compression",
|
|
32
|
+
"precompress",
|
|
33
|
+
"pre-compress",
|
|
34
|
+
"glob",
|
|
35
|
+
"br",
|
|
36
|
+
"brotli",
|
|
37
|
+
"gz",
|
|
38
|
+
"gzip",
|
|
39
|
+
"static",
|
|
40
|
+
"assets"
|
|
41
|
+
],
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@eslint/js": "^10.0.1",
|
|
44
|
+
"@types/node": "^22.20.5",
|
|
45
|
+
"eslint": "^10.12.0",
|
|
46
|
+
"prettier": "^3.9.10",
|
|
47
|
+
"typescript": "^6.0.3",
|
|
48
|
+
"typescript-eslint": "^8.71.2"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"test": "node --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
|
52
|
+
"pretest:coverage": "node -e \"fs.mkdirSync('coverage', { recursive: true })\"",
|
|
53
|
+
"test:coverage": "node --test --experimental-test-coverage --test-coverage-include=\"src/**\" --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info \"tests/**/*.test.ts\"",
|
|
54
|
+
"clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
|
|
55
|
+
"build": "npm run clean && tsc -p tsconfig.build.json",
|
|
56
|
+
"prepack": "npm run build",
|
|
57
|
+
"typecheck": "tsc",
|
|
58
|
+
"lint": "eslint .",
|
|
59
|
+
"format": "prettier --write .",
|
|
60
|
+
"format:check": "prettier --check .",
|
|
61
|
+
"check": "npm run lint && npm run format:check && npm run typecheck && npm test"
|
|
62
|
+
}
|
|
63
|
+
}
|