Skip to content

Commit

Permalink
feat: transform script src to internal when using asset attr
Browse files Browse the repository at this point in the history
  • Loading branch information
aralroca committed Sep 26, 2023
1 parent cc221e9 commit e3cf84f
Show file tree
Hide file tree
Showing 10 changed files with 286 additions and 13 deletions.
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
The MIT License

MIT License

Copyright (c) 2023 Aral Roca Gomez

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@
"peerDependencies": {
"typescript": "5.2.2"
}
}
}
4 changes: 2 additions & 2 deletions src/brisa/render-to-readable-stream/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import getConstants from "../../constants";
import { ComponentType } from "../../types";

const testRequest = new RequestContext(new Request("http://test.com/"));
const mockConsoleError = mock(() => { });
const mockConsoleError = mock(() => {});
const consoleError = console.error;
console.error = mockConsoleError;

Expand Down Expand Up @@ -100,7 +100,7 @@ describe("brisa core", () => {
});

it("should be possible to provide and consume context", async () => {
const ComponentChild = ({ }, request: RequestContext) => (
const ComponentChild = ({}, request: RequestContext) => (
<div>Hello {request.context.get("testData").testName}</div>
);

Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const CONFIG = (await importFileIfExists("brisa.config", CONFIG_DIR)) ?? {};

const defaultConfig = {
trailingSlash: false,
assetPrefix: "",
};

const constants = {
Expand Down
2 changes: 2 additions & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export type Type = string | number | ComponentType | Promise<ComponentType>;

export type Configuration = {
trailingSlash?: boolean;
assetPrefix?: string;
basePath?: string;
};

export type JSXElement = {
Expand Down
5 changes: 3 additions & 2 deletions src/utils/generate-href-lang/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ export default function generateHrefLang(request: RequestContext) {

const url = getURLInAnotherLang(domain, lang, request);
const urlWithoutTrailingSlash = url.toString().replace(/\/$/, "");
const finalUrl = `${urlWithoutTrailingSlash}${CONFIG.trailingSlash ? "/" : ""
}`;
const finalUrl = `${urlWithoutTrailingSlash}${
CONFIG.trailingSlash ? "/" : ""
}`;

return `<link rel="alternate" hreflang="${lang}" href="${finalUrl}" />`;
})
Expand Down
6 changes: 3 additions & 3 deletions src/utils/get-files-from-dir/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ describe("utils", () => {
it("should return all files from a directory", async () => {
const output = await getFilesFromDir(assetsPath);
const expected = new Set([
path.join(assetsPath, 'favicon.ico'),
path.join(assetsPath, 'some-dir', 'some-img.png'),
path.join(assetsPath, 'some-dir', 'some-text.txt'),
path.join(assetsPath, "favicon.ico"),
path.join(assetsPath, "some-dir", "some-img.png"),
path.join(assetsPath, "some-dir", "some-text.txt"),
]);

expect(new Set(output)).toEqual(expected);
Expand Down
222 changes: 222 additions & 0 deletions src/utils/render-attributes/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,5 +179,227 @@ describe("utils", () => {
' href="/es/dinamico/1/atrapar/first/second/"',
);
});

it('should add the assetPrefix to the "src" attribute when the asset attribute is in production', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: true,
CONFIG: {
assetPrefix: "https://cdn.test.com",
},
};

const request = new RequestContext(new Request("https://example.com"));

const imgSrc = (src: string) =>
renderAttributes({
props: {
src,
},
request,
type: "img",
});
const scriptSrc = (src: string) =>
renderAttributes({
props: {
src,
},
request,
type: "script",
});

expect(imgSrc("https://example.com/some-image.png")).toBe(
' src="https://example.com/some-image.png"',
);

expect(imgSrc("/some-image.png")).toBe(
' src="https://cdn.test.com/some-image.png"',
);

expect(scriptSrc("https://example.com/some-script.js")).toBe(
' src="https://example.com/some-script.js"',
);

expect(scriptSrc("/some-script.js")).toBe(
' src="https://cdn.test.com/some-script.js"',
);
});

it('should NOT add the assetPrefix to the "src" attribute when the asset attribute is in development', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: false,
CONFIG: {
assetPrefix: "https://cdn.test.com",
},
};

const request = new RequestContext(new Request("https://example.com"));

const imgSrc = (src: string) =>
renderAttributes({
props: {
src,
},
request,
type: "img",
});
const scriptSrc = (src: string) =>
renderAttributes({
props: {
src,
},
request,
type: "script",
});

expect(imgSrc("https://example.com/some-image.png")).toBe(
' src="https://example.com/some-image.png"',
);

expect(imgSrc("/some-image.png")).toBe(' src="/some-image.png"');

expect(scriptSrc("https://example.com/some-script.js")).toBe(
' src="https://example.com/some-script.js"',
);

expect(scriptSrc("/some-script.js")).toBe(' src="/some-script.js"');
});

it('should move to assets the "script" src attribute when the asset attribute is in production', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: true,
};

const request = new RequestContext(new Request("https://example.com"));

const srcOfScriptTag = (src: string) =>
renderAttributes({
props: {
src,
asset: true,
},
request,
type: "script",
});

expect(srcOfScriptTag("https://example.com/some-script.js")).toBe(
' src="/_scripts/some-script.js"',
);
expect(srcOfScriptTag("https://example.com/some-script.js?foo=bar")).toBe(
' src="/_scripts/some-script.js?foo=bar"',
);
expect(srcOfScriptTag("https://example.com/some-script.js#foo")).toBe(
' src="/_scripts/some-script.js#foo"',
);
expect(
srcOfScriptTag("https://example.com/some-script.js?foo=bar#foo"),
).toBe(' src="/_scripts/some-script.js?foo=bar#foo"');
expect(srcOfScriptTag("/some-script.js")).toBe(' src="/some-script.js"');
});

it('should move to assets the "script" src attribute with the correct assetPrefix when the asset attribute is in production', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: true,
CONFIG: {
assetPrefix: "https://cdn.test.com",
},
};

const request = new RequestContext(new Request("https://example.com"));

const srcOfScriptTag = (src: string) =>
renderAttributes({
props: {
src,
asset: true,
},
request,
type: "script",
});

expect(srcOfScriptTag("https://example.com/some-script.js")).toBe(
' src="https://cdn.test.com/_scripts/some-script.js"',
);
expect(srcOfScriptTag("https://example.com/some-script.js?foo=bar")).toBe(
' src="https://cdn.test.com/_scripts/some-script.js?foo=bar"',
);
expect(srcOfScriptTag("https://example.com/some-script.js#foo")).toBe(
' src="https://cdn.test.com/_scripts/some-script.js#foo"',
);
expect(
srcOfScriptTag("https://example.com/some-script.js?foo=bar#foo"),
).toBe(' src="https://cdn.test.com/_scripts/some-script.js?foo=bar#foo"');
expect(srcOfScriptTag("/some-script.js")).toBe(
' src="https://cdn.test.com/some-script.js"',
);
});

it('should NOT move to assets the "script" src attribute WITHOUT the asset attribute, in production', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: true,
};

const request = new RequestContext(new Request("https://example.com"));

const srcOfScriptTag = (src: string) =>
renderAttributes({
props: {
src,
},
request,
type: "script",
});

expect(srcOfScriptTag("https://example.com/some-script.js")).toBe(
' src="https://example.com/some-script.js"',
);
expect(srcOfScriptTag("https://example.com/some-script.js?foo=bar")).toBe(
' src="https://example.com/some-script.js?foo=bar"',
);
expect(srcOfScriptTag("https://example.com/some-script.js#foo")).toBe(
' src="https://example.com/some-script.js#foo"',
);
expect(
srcOfScriptTag("https://example.com/some-script.js?foo=bar#foo"),
).toBe(' src="https://example.com/some-script.js?foo=bar#foo"');
expect(srcOfScriptTag("/some-script.js")).toBe(' src="/some-script.js"');
});

it('should NOT move to assets the "script" src attribute when the asset attribute is in development', () => {
globalThis.mockConstants = {
...(getConstants() ?? {}),
IS_PRODUCTION: false,
};

const request = new RequestContext(new Request("https://example.com"));

const srcOfScriptTag = (src: string) =>
renderAttributes({
props: {
src,
asset: true,
},
request,
type: "script",
});

expect(srcOfScriptTag("https://example.com/some-script.js")).toBe(
' src="https://example.com/some-script.js"',
);
expect(srcOfScriptTag("https://example.com/some-script.js?foo=bar")).toBe(
' src="https://example.com/some-script.js?foo=bar"',
);
expect(srcOfScriptTag("https://example.com/some-script.js#foo")).toBe(
' src="https://example.com/some-script.js#foo"',
);
expect(
srcOfScriptTag("https://example.com/some-script.js?foo=bar#foo"),
).toBe(' src="https://example.com/some-script.js?foo=bar#foo"');
expect(srcOfScriptTag("/some-script.js")).toBe(' src="/some-script.js"');
});
});
});
28 changes: 27 additions & 1 deletion src/utils/render-attributes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,38 @@ export default function renderAttributes({
request: RequestContext;
type: string;
}): string {
const { IS_PRODUCTION, CONFIG } = getConstants();
let attributes = "";

for (const prop in props) {
const value = props[prop];
let value = props[prop];

if (prop === "children" || (type === "html" && prop === "lang")) continue;
if (prop === "asset" && type === "script") continue;

// Use assetPrefix in production in scripts with "asset" attribute
if (
IS_PRODUCTION &&
prop === "src" &&
type === "script" &&
"asset" in props &&
URL.canParse(value as string)
) {
const url = new URL(value as string);
value = `${CONFIG.assetPrefix}/_scripts${
url.pathname + url.search + url.hash
}`;
}

// Add the assetPrefix to internal assets (img, picture, video, audio, script)
if (
IS_PRODUCTION &&
prop === "src" &&
CONFIG.assetPrefix &&
!URL.canParse(value as string)
) {
value = `${CONFIG.assetPrefix}${value}`;
}

// i18n navigation
if (
Expand Down
6 changes: 2 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"compilerOptions": {
"lib": [
"ESNext"
],
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
"moduleResolution": "bundler",
Expand All @@ -22,4 +20,4 @@
"bun-types" // add Bun global
]
}
}
}

0 comments on commit e3cf84f

Please sign in to comment.