-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
vite-plugin-astro-image.ts
162 lines (133 loc) · 4.38 KB
/
vite-plugin-astro-image.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import type { AstroConfig } from 'astro';
import MagicString from 'magic-string';
import fs from 'node:fs/promises';
import path, { basename, extname, join } from 'node:path';
import { Readable } from 'node:stream';
import { fileURLToPath, pathToFileURL } from 'node:url';
import slash from 'slash';
import type { Plugin, ResolvedConfig } from 'vite';
import type { IntegrationOptions } from './index.js';
import type { InputFormat } from './loaders/index.js';
import { metadata } from './utils/metadata.js';
export interface ImageMetadata {
src: string;
width: number;
height: number;
format: InputFormat;
}
export function createPlugin(config: AstroConfig, options: Required<IntegrationOptions>): Plugin {
const filter = (id: string) =>
/^(?!\/_image?).*.(heic|heif|avif|jpeg|jpg|png|tiff|webp|gif)$/.test(id);
const virtualModuleId = 'virtual:image-loader';
let resolvedConfig: ResolvedConfig;
return {
name: '@astrojs/image',
enforce: 'pre',
configResolved(viteConfig) {
resolvedConfig = viteConfig;
},
async resolveId(id) {
// The virtual model redirects imports to the ImageService being used
// This ensures the module is available in `astro dev` and is included
// in the SSR server bundle.
if (id === virtualModuleId) {
return await this.resolve(options.serviceEntryPoint);
}
},
async load(id) {
// only claim image ESM imports
if (!filter(id)) {
return null;
}
const url = pathToFileURL(id);
const meta = await metadata(url);
if (!meta) {
return;
}
if (!this.meta.watchMode) {
const pathname = decodeURI(url.pathname);
const filename = basename(pathname, extname(pathname) + `.${meta.format}`);
const handle = this.emitFile({
name: filename,
source: await fs.readFile(url),
type: 'asset',
});
meta.src = `__ASTRO_IMAGE_ASSET__${handle}__`;
} else {
const relId = path.relative(fileURLToPath(config.srcDir), id);
meta.src = join('/@astroimage', relId);
// Windows compat
meta.src = slash(meta.src);
}
return `export default ${JSON.stringify(meta)}`;
},
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (req.url?.startsWith('/@astroimage/')) {
const [, id] = req.url.split('/@astroimage/');
const url = new URL(id, config.srcDir);
const file = await fs.readFile(url);
const meta = await metadata(url);
if (!meta) {
return next();
}
const transform = await globalThis.astroImage.defaultLoader.parseTransform(
url.searchParams
);
// if no transforms were added, the original file will be returned as-is
let data = file;
let format = meta.format;
if (transform) {
const result = await globalThis.astroImage.defaultLoader.transform(file, transform);
data = result.data;
format = result.format;
}
res.setHeader('Content-Type', `image/${format}`);
res.setHeader('Cache-Control', 'max-age=360000');
const stream = Readable.from(data);
return stream.pipe(res);
}
return next();
});
},
outputOptions(outputOptions) {
if(resolvedConfig.build.ssr) {
// Build the image-pool chunk to the top-level and not inside of a chunks/
// folder. This is because the wasm is built at the top-level and this makes
// it accessible from the pool worker.
const chunkFileNames = outputOptions.chunkFileNames;
outputOptions.chunkFileNames = (chunk) => {
for(const name of Object.keys(chunk.modules)) {
if(name.endsWith('vendor/squoosh/image-pool.js')) {
return '[name].[hash].mjs';
}
}
if(typeof chunkFileNames === 'function') {
return chunkFileNames.call(this, chunk);
}
return chunkFileNames!;
};
}
},
async renderChunk(code) {
const assetUrlRE = /__ASTRO_IMAGE_ASSET__([a-z\d]{8})__(?:_(.*?)__)?/g;
let match;
let s;
while ((match = assetUrlRE.exec(code))) {
s = s || (s = new MagicString(code));
const [full, hash, postfix = ''] = match;
const file = this.getFileName(hash);
const outputFilepath = resolvedConfig.base + file + postfix;
s.overwrite(match.index, match.index + full.length, outputFilepath);
}
if (s) {
return {
code: s.toString(),
map: resolvedConfig.build.sourcemap ? s.generateMap({ hires: true }) : null,
};
} else {
return null;
}
},
};
}