Skip to content

Commit 55f371b

Browse files
committed
vercel og ast rules
1 parent 31b0f9b commit 55f371b

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { describe, expect, it } from "vitest";
2+
3+
import { patchCode } from "./util";
4+
import { vercelOgFallbackFontRule, vercelOgImportRule } from "./vercel-og";
5+
6+
describe("vercelOgImportRule", () => {
7+
it("should rewrite a node import to an edge import", () => {
8+
const code = `e.exports=import("next/dist/compiled/@vercel/og/index.node.js")`;
9+
expect(patchCode(code, vercelOgImportRule)).toMatchInlineSnapshot(
10+
`"e.exports=import("next/dist/compiled/@vercel/og/index.edge.js")"`
11+
);
12+
});
13+
});
14+
15+
describe("vercelOgFallbackFontRule", () => {
16+
it("should replace a fetch call for a font with an import", () => {
17+
const code = `var fallbackFont = fetch(new URL("./noto-sans-v27-latin-regular.ttf", import.meta.url)).then((res) => res.arrayBuffer());`;
18+
expect(patchCode(code, vercelOgFallbackFontRule)).toMatchInlineSnapshot(`
19+
"async function getFallbackFont() {
20+
return (await import("./noto-sans-v27-latin-regular.ttf.bin")).default
21+
}
22+
23+
var fallbackFont = getFallbackFont()"
24+
`);
25+
});
26+
});
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { SgNode } from "@ast-grep/napi";
2+
3+
import { applyRule } from "./util.js";
4+
5+
export const vercelOgImportRule = `
6+
rule:
7+
pattern: $NODE
8+
kind: string
9+
regex: "next/dist/compiled/@vercel/og/index.node.js"
10+
inside:
11+
kind: arguments
12+
inside:
13+
kind: call_expression
14+
stopBy: end
15+
has:
16+
field: function
17+
regex: "import"
18+
19+
fix: |-
20+
"next/dist/compiled/@vercel/og/index.edge.js"
21+
`;
22+
23+
export function patchVercelOgImport(root: SgNode) {
24+
return applyRule(vercelOgImportRule, root);
25+
}
26+
27+
export const vercelOgFallbackFontRule = `
28+
rule:
29+
kind: variable_declaration
30+
all:
31+
- has:
32+
kind: variable_declarator
33+
has:
34+
kind: identifier
35+
regex: ^fallbackFont$
36+
- has:
37+
kind: call_expression
38+
pattern: fetch(new URL("$PATH", $$$REST))
39+
stopBy: end
40+
41+
fix: |-
42+
async function getFallbackFont() {
43+
return (await import("$PATH.bin")).default
44+
}
45+
46+
var fallbackFont = getFallbackFont()
47+
`;
48+
49+
export function patchVercelOgFallbackFont(root: SgNode) {
50+
return applyRule(vercelOgFallbackFontRule, root);
51+
}

0 commit comments

Comments
 (0)