1 import type { Transformer } from "unified"
2 import type { CloudinaryConfig, UnistNode, UnistTree } from "types"
3
4 const cloudinaryImageRegex =
5 /^https:\/\/res.cloudinary.com\/(?<cloudName>[^/]+)\/.*\/upload\/v[0-9]+\/(?<imageId>.*)$/
6
7 export function cloudinaryImgRehypePlugin({
8 cloudinaryConfig,
9 }: {
10 cloudinaryConfig: CloudinaryConfig
11 }): Transformer {
12 return async (tree) => {
13 if (!cloudinaryConfig) {
14 return
15 }
16 const { visit } = await import("unist-util-visit")
17 const { Cloudinary } = await import("@cloudinary/url-gen")
18 const { byRadius } = await import(
19 "@cloudinary/url-gen/actions/roundCorners"
20 )
21
22 const {
23 pad,
24 imaggaScale,
25 imaggaCrop,
26 crop,
27 fit,
28 minimumPad,
29 fill,
30 scale,
31 limitFit,
32 thumbnail,
33 limitFill,
34 minimumFit,
35 limitPad,
36 fillPad,
37 } = await import("@cloudinary/url-gen/actions/resize")
38
39 const resizeActions = {
40 pad,
41 imaggaScale,
42 imaggaCrop,
43 crop,
44 fit,
45 minimumPad,
46 fill,
47 scale,
48 limitFit,
49 thumbnail,
50 limitFill,
51 minimumFit,
52 limitPad,
53 fillPad,
54 }
55
56 visit(tree as UnistTree, (node: UnistNode) => {
57 const matchingRegex = node.properties?.src?.match(cloudinaryImageRegex)
58
59 if (node.tagName !== "img" || !matchingRegex?.groups?.imageId) {
60 return
61 }
62
63 const cloudName =
64 cloudinaryConfig.cloudName || matchingRegex.groups.cloudName
65
66 if (!cloudName) {
67 return
68 }
69
70 const cloudinary = new Cloudinary({
71 cloud: {
72 cloudName,
73 },
74 })
75 const image = cloudinary.image(
76 matchingRegex.groups.imageId.replaceAll("%20", " ")
77 )
78
79 cloudinaryConfig.flags?.forEach((flag) => image.addTransformation(flag))
80
81 if (cloudinaryConfig.roundCorners) {
82 image.roundCorners(byRadius(cloudinaryConfig.roundCorners))
83 }
84
85 if (cloudinaryConfig.resize) {
86 const action =
87 resizeActions[
88 cloudinaryConfig.resize.action as keyof typeof resizeActions
89 ]
90 let resizeAction = action()
91 if (node.properties?.width || node.properties?.height) {
92 if (node.properties?.width) {
93 resizeAction = resizeAction.width(node.properties.width)
94 }
95
96 if (node.properties?.height) {
97 resizeAction = resizeAction.height(node.properties.height)
98 }
99 } else if (cloudinaryConfig.resize.aspectRatio) {
100 resizeAction = resizeAction.aspectRatio(
101 cloudinaryConfig.resize.aspectRatio
102 )
103 } else {
104 if (cloudinaryConfig.resize.width) {
105 resizeAction = resizeAction.width(cloudinaryConfig.resize.width)
106 }
107
108 if (cloudinaryConfig.resize.height) {
109 resizeAction = resizeAction.height(cloudinaryConfig.resize.height)
110 }
111 }
112
113 image.resize(resizeAction)
114 }
115
116 node.properties!.src = image.toURL()
117 })
118 }
119 }