Skip to content

Commit

Permalink
feat: prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
gurgunday committed Jul 28, 2024
1 parent 226addb commit aa59d2c
Show file tree
Hide file tree
Showing 10 changed files with 35 additions and 29 deletions.
6 changes: 5 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"root": true,
"extends": ["plugin:grules/all"]
"extends": ["plugin:grules/all"],
"rules": {
"no-await-in-loop": "off",
"require-unicode-regexp": "off"
}
}
14 changes: 3 additions & 11 deletions bench/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-unused-expressions */
import { html } from "../src/index.js";
import { Bench } from "tinybench";
import { writeFileSync } from "node:fs";
Expand All @@ -8,7 +7,6 @@ import { Buffer } from "node:buffer";
let result = "";
const bench = new Bench({ time: 500 });

// Simple cases
bench.add("simple HTML formatting", () => {
result = html`<div>Hello, world!</div>`;
});
Expand All @@ -17,7 +15,6 @@ bench.add("null and undefined expressions", () => {
result = html`<p>${null} and ${undefined}</p>`;
});

// String expressions
const username = "User";
bench.add("single string expression", () => {
result = html`<p>${username}</p>`;
Expand All @@ -27,7 +24,6 @@ bench.add("multiple string expressions", () => {
result = html`<p>${username} and ${username}</p>`;
});

// Array expressions
const items1 = ["Item 1", undefined, "Item 2", null, 2000, 1500.5];
bench.add("array expressions", () => {
result = html`<ul>
Expand All @@ -46,7 +42,6 @@ bench.add("array expressions with escapable chars", () => {
</ul>`;
});

// Object expressions
const user = { id: 1, name: "John Doe" };
bench.add("object expressions", () => {
result = html`
Expand All @@ -55,7 +50,6 @@ bench.add("object expressions", () => {
`;
});

// Mixed expressions
bench.add("multiple types of expressions", () => {
result = html`
${undefined}
Expand All @@ -70,17 +64,15 @@ bench.add("multiple types of expressions", () => {
`;
});

// Large strings
const largeString = Array.from({ length: 1000 }).join("Lorem ipsum ");
bench.add("large strings", () => {
result = html`<p>${largeString}${largeString}</p>`;
});

// Escaped and unescaped expressions
const rawHTML = "<em>Italic</em> and <strong>bold</strong>";
const markup = "<mark>Highlighted</mark>";
bench.add("unescaped expressions", () => {
html`
result = html`
<div>!${rawHTML}</div>
<div>!${rawHTML}</div>
<div>!${markup}</div>
Expand All @@ -91,7 +83,7 @@ bench.add("unescaped expressions", () => {
});

bench.add("escaped expressions", () => {
html`
result = html`
<div>${rawHTML}</div>
<div>${rawHTML}</div>
<div>${markup}</div>
Expand All @@ -102,7 +94,7 @@ bench.add("escaped expressions", () => {
});

bench.add("mixed escaped and unescaped expressions", () => {
html`
result = html`
<div>!${rawHTML}</div>
<div>!${rawHTML}</div>
<div>${markup}</div>
Expand Down
6 changes: 3 additions & 3 deletions bin/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Lets you append unique hashes to assets referenced in your views to aggressively cache them while guaranteeing that clients receive the most recent versions.
Append unique hashes to assets referenced in your views to aggressively cache them while guaranteeing that clients receive the most recent versions.

## Usage

Expand All @@ -14,8 +14,8 @@ Register `@fastify/static`:

```js
await fastify.register(import("@fastify/static"), {
root: new URL("assets/", import.meta.url).pathname,
prefix: "/p/assets/",
root: new URL("assets/", import.meta.url).pathname,
wildcard: false,
index: false,
immutable: true,
Expand All @@ -27,7 +27,7 @@ Add the `ghtml` command to the build script:
```json
"scripts": {
"build": "npx ghtml --roots=assets/ --refs=views/,routes/",
"build": "npx ghtml --prefix=/p/assets/ --roots=assets/ --refs=views/,routes/",
},
```
Expand Down
6 changes: 6 additions & 0 deletions bin/example/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"rules": {
"require-await": "off",
"n/no-missing-import": "off"
}
}
2 changes: 1 addition & 1 deletion bin/example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"main": "./server.js",
"scripts": {
"start": "node server.js",
"build": "ghtml --roots=assets/ --refs=routes/"
"build": "ghtml --prefix=/p/assets/ --roots=assets/ --refs=routes/"
},
"dependencies": {
"@fastify/static": "^7.0.1",
Expand Down
2 changes: 0 additions & 2 deletions bin/example/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable n/no-missing-import */

import { html } from "ghtml";

export default async (fastify) => {
Expand Down
2 changes: 0 additions & 2 deletions bin/example/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable n/no-missing-import */

import Fastify from "fastify";

const fastify = Fastify();
Expand Down
12 changes: 8 additions & 4 deletions bin/src/index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,45 @@
#!/usr/bin/env node

import { generateHashesAndReplace } from "./utils.js";
import process from "node:process";

const parseArguments = (args) => {
let roots = null;
let refs = null;
let prefix = "/";

for (const arg of args) {
if (arg.startsWith("--roots=")) {
roots = arg.split("=", 2)[1].split(",");
} else if (arg.startsWith("--refs=")) {
refs = arg.split("=", 2)[1].split(",");
} else if (arg.startsWith("--prefix=")) {
prefix = arg.split("=", 2)[1];
}
}

if (!roots || !refs) {
console.error(
'Usage: npx ghtml --roots="path/to/scan/assets1/,path/to/scan/assets2/" --refs="views/path/to/append/hashes1/,views/path/to/append/hashes2/"',
'Usage: npx ghtml --roots="path/to/scan/assets1/,path/to/scan/assets2/" --refs="views/path/to/append/hashes1/,views/path/to/append/hashes2/" [--prefix="optional/prefix/"]',
);
process.exit(1);
}

return { roots, refs };
return { roots, refs, prefix };
};

const main = async () => {
const { roots, refs } = parseArguments(process.argv.slice(2));
const { roots, refs, prefix } = parseArguments(process.argv.slice(2));

try {
console.warn(`Generating hashes and updating file paths...`);
console.warn(`Scanning files in: ${roots}`);
console.warn(`Updating files in: ${refs}`);
console.warn(`Using prefix: ${prefix}`);

await generateHashesAndReplace({
roots,
refs,
prefix,
});

console.warn("Hash generation and file updates completed successfully.");
Expand Down
12 changes: 8 additions & 4 deletions bin/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const generateFileHash = async (filePath) => {
const updateFilePathsWithHashes = async (
fileHashes,
refs,
prefix,
includeDotFiles,
skipPatterns,
) => {
Expand All @@ -40,14 +41,15 @@ const updateFilePathsWithHashes = async (
let content = await readFile(filePath, "utf8");
let found = false;

for (const [originalPath, hash] of fileHashes) {
const escapedPath = originalPath.replace(
for (const [path, hash] of fileHashes) {
const fullPath = prefix + path;
const escapedPath = fullPath.replace(
/[$()*+.?[\\\]^{|}]/gu,
"\\$&",
String.raw`\$&`,
);
const regex = new RegExp(
`(?<path>${escapedPath})(\\?(?<queryString>[^#"'\`]*))?`,
"gu",
"g",
);

content = content.replace(
Expand Down Expand Up @@ -75,6 +77,7 @@ const updateFilePathsWithHashes = async (
const generateHashesAndReplace = async ({
roots,
refs,
prefix,
includeDotFiles = false,
skipPatterns = ["**/node_modules/**"],
}) => {
Expand Down Expand Up @@ -116,6 +119,7 @@ const generateHashesAndReplace = async ({
await updateFilePathsWithHashes(
fileHashes,
refs,
prefix,
includeDotFiles,
skipPatterns,
);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"devDependencies": {
"@fastify/pre-commit": "^2.1.0",
"c8": "^10.1.2",
"grules": "^0.17.3",
"grules": "^0.21.0",
"tinybench": "^2.8.0"
},
"repository": {
Expand Down

0 comments on commit aa59d2c

Please sign in to comment.