@uniflowed/vite 0.0.0-alpha.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,744 @@
1
+ // @noflow
2
+ //
3
+ // Plain JavaScript: Vite imports this module directly, before any transform.
4
+ //
5
+ // `uf:asset` — what an imported image or font becomes.
6
+ //
7
+ // The name and the hook set are not new. `crates/uf_plugin/src/builtin.rs` has
8
+ // declared `uf:asset` — "resolves, fingerprints, and emits non-JavaScript
9
+ // imports", `resolveId` + `load` + `generateBundle` + `writeBundle` +
10
+ // `transformIndexHtml` — since before there was anything behind it, and
11
+ // `uf inspect` has been listing it in the resolved pipeline. This is the
12
+ // implementation of a plugin uf was already claiming to run — and `resolveId`
13
+ // and `generateBundle`, declared there from the start and unimplemented until
14
+ // icons arrived, are now real: the first resolves `uf:icon/…`, the second
15
+ // assembles the sprite once the graph is complete.
16
+ //
17
+ // # What an import becomes
18
+ //
19
+ // ```js
20
+ // import hero from "./hero.jpg";
21
+ // <Image src={hero} alt="…" sizes="(max-width: 640px) 100vw, 640px" />
22
+ // ```
23
+ //
24
+ // `hero` is not a URL string. It is the manifest `crates/uf_assets` produced —
25
+ // the intrinsic width and height, every emitted variant with its own width, the
26
+ // blur placeholder — because a `srcSet` can only be written by something that
27
+ // knows which other sizes exist, and a URL string does not.
28
+ //
29
+ // A font import is the same shape: the self-hosted file, the `@font-face` rules
30
+ // that declare it, and the metric-matched fallback.
31
+ //
32
+ // # Where the work happens, and when
33
+ //
34
+ // In `uf`, over the `uf assets` protocol — one native process for the whole
35
+ // build rather than an image codec in the dependency tree. Both schedules go
36
+ // through the same process with the same parameters, and both write to the
37
+ // same cache directory:
38
+ //
39
+ // * **`uf build`** reads each emitted variant out of the cache and hands it to
40
+ // Rollup with `emitFile`, so the bundler owns what lands in `dist/` and the
41
+ // size report counts it.
42
+ // * **`uf dev`** serves the same files out of the same cache directory over a
43
+ // middleware, transformed on the first import and reused after.
44
+ //
45
+ // The files are named by a content hash of the source and the parameters, so
46
+ // the second build of an unchanged image does no work in either mode and a dev
47
+ // session warms the cache a build then reuses. That is also the whole of "the
48
+ // two must agree": there is one pipeline and one set of bytes, and the only
49
+ // thing that differs between them is the URL prefix they are served under.
50
+ //
51
+ // # Icons, and why they are not `.svg`
52
+ //
53
+ // `import Star from "uf:icon/star"` resolves against the directory
54
+ // `app.builtins.icons.dir` names, and `import sprite from "uf:icon-sprite"` is
55
+ // the sprite built from every icon the build reached. Neither claims an
56
+ // extension, which is the point: `.svg` stays Vite's, so `vite-plugin-svgr`
57
+ // and everything like it keep working, and uf adds a capability in its own
58
+ // namespace instead of taking one away.
59
+ //
60
+ // The sprite is emitted in `generateBundle`, which is the first hook that runs
61
+ // after every module has been loaded — and therefore the first moment the set
62
+ // of icons a build reached is the whole set.
63
+ //
64
+ // # What this plugin deliberately does not claim
65
+ //
66
+ // An import with a query — `./hero.png?url`, `?raw`, `?inline` — is left to
67
+ // Vite. Those are Vite's own asset conventions and a project reaching for one
68
+ // is reaching past uf on purpose; claiming them here would make a documented
69
+ // Vite feature unreachable from a uf project, which is red line 8 in
70
+ // `docs/red-lines.md`. `import hero from "./hero.png"` is uf's; everything
71
+ // with a `?` after it is Vite's.
72
+
73
+ import { existsSync, readFileSync } from "node:fs";
74
+ import path from "node:path";
75
+
76
+ import {
77
+ AssetService,
78
+ ICON_PREFIX,
79
+ ICON_SPRITE,
80
+ OG_EXTENSION,
81
+ assetKind,
82
+ } from "@uniflowed/host/assets";
83
+
84
+ import { endpointSettings, localImageEndpoint, servesRemoteImages } from "./image-endpoint.js";
85
+
86
+ /**
87
+ * Whether `id` is `@uniflowed/web`'s `internal/image-endpoint.js`.
88
+ *
89
+ * By path *and* by the package it is in, because the suffix alone is a name
90
+ * any package could have; the manifest two directories up has to say
91
+ * `@uniflowed/web`. The answer is remembered per directory, so the manifest is
92
+ * read once rather than once per module id.
93
+ */
94
+ const webPackageDirectories = new Map();
95
+ function isWebImageEndpoint(id) {
96
+ const file = id.split("?")[0];
97
+ if (
98
+ !file.endsWith(`${path.sep}internal${path.sep}image-endpoint.js`) &&
99
+ !file.endsWith("/internal/image-endpoint.js")
100
+ ) {
101
+ return false;
102
+ }
103
+ const directory = path.dirname(path.dirname(file));
104
+ if (!webPackageDirectories.has(directory)) {
105
+ let name = null;
106
+ try {
107
+ name = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")).name;
108
+ } catch {
109
+ name = null;
110
+ }
111
+ webPackageDirectories.set(directory, name === "@uniflowed/web");
112
+ }
113
+ return webPackageDirectories.get(directory);
114
+ }
115
+
116
+ /**
117
+ * The source `@uniflowed/web/internal/image-endpoint.js` is answered with.
118
+ *
119
+ * The same shape as the file, with the project's values: the endpoint's path
120
+ * under Vite's `base` when `remotePatterns` lists anything, and `null`
121
+ * otherwise, which is the file's own answer — so a project with no remote
122
+ * images renders exactly what it rendered before the endpoint existed. The
123
+ * widths and quality are the ones the endpoint will accept, defaulted the way
124
+ * `@uniflowed/server/image` defaults them, so the `srcset` `Image` writes
125
+ * names no width the endpoint refuses.
126
+ *
127
+ * @param {object} images `app.builtins.images`
128
+ * @param {string} base Vite's resolved `base`
129
+ */
130
+ export async function imageEndpointSource(images, base) {
131
+ const defaults = await import("@uniflowed/server/image");
132
+ const { widths, quality } = endpointSettings(images, defaults);
133
+ const endpoint = servesRemoteImages(images) ? `${base}__uf/image` : null;
134
+ return (
135
+ "// Generated by uf:asset from app.builtins.images. See @uniflowed/web's\n" +
136
+ "// internal/image-endpoint.js for the file this stands in for.\n" +
137
+ `export const IMAGE_ENDPOINT = ${JSON.stringify({ path: endpoint, widths, quality })};\n`
138
+ );
139
+ }
140
+
141
+ /** Where transformed assets are kept, relative to the project root. */
142
+ export const CACHE_DIR = ".uf/cache/assets";
143
+
144
+ /**
145
+ * The URL prefix a dev server answers transformed assets on.
146
+ *
147
+ * `@` first, following the convention Vite uses for everything that is not a
148
+ * file in the project: it cannot collide with a real path, and Vite's own
149
+ * middlewares leave it alone.
150
+ */
151
+ export const DEV_PREFIX = "@uf-asset/";
152
+
153
+ /**
154
+ * What stands in for the sprite until `generateBundle` knows what is in it.
155
+ *
156
+ * A string no source file would contain, replaced in the generated chunk once
157
+ * every module has been loaded. The module graph needs *something* at `load`
158
+ * time and the sprite is not knowable then; see the `sprite` branch of `load`.
159
+ */
160
+ const SPRITE_PLACEHOLDER = "__UF_ICON_SPRITE__";
161
+
162
+ /**
163
+ * What a `*.og.json` import resolves to.
164
+ *
165
+ * A card cannot keep its own id, and the reason is worth writing down because
166
+ * nothing about `enforce: "pre"` prevents it. Vite's JSON handling is a
167
+ * *native* rolldown plugin, `builtin:vite-json`, and it selects modules by
168
+ * **id**: anything still ending in `.json` when its `transform` runs is put
169
+ * through a JSON parser, whatever an earlier `load` returned. Ordering the
170
+ * hooks does not help, because the module this plugin loads is JavaScript
171
+ * under a name that says JSON — and the parser's answer is
172
+ * `expected value at line 1 column 1`.
173
+ *
174
+ * So the id changes rather than the order. The card resolves to
175
+ * `\0uf-og:<absolute path>.js`: `\0` is the convention for a module that is
176
+ * not a file, and the trailing extension is what takes it out of every
177
+ * `.json` filter in the pipeline.
178
+ */
179
+ const OG_PREFIX = "\0uf-og:";
180
+ /** Appended to that id so it does not end in `.json`. See [`OG_PREFIX`]. */
181
+ const OG_SUFFIX = ".js";
182
+
183
+ /**
184
+ * The module source for one transformed asset.
185
+ *
186
+ * A frozen object literal rather than a JSON blob assigned to a variable: this
187
+ * is what the component destructures, it is small, and a build that inlines it
188
+ * into the one component that used it is the right outcome.
189
+ */
190
+ export function assetModuleSource(manifest) {
191
+ return `export default Object.freeze(${JSON.stringify(manifest)});\n`;
192
+ }
193
+
194
+ /**
195
+ * The `srcSet` for one format, and the URLs that go in it.
196
+ *
197
+ * Written here rather than in the component so that a build and a dev server
198
+ * cannot produce different strings from the same manifest: the only input that
199
+ * differs between them is `baseUrl`, and it is an argument.
200
+ */
201
+ export function withUrls(image, baseUrl) {
202
+ const variants = image.variants.map((variant) => ({
203
+ ...variant,
204
+ url: `${baseUrl}${variant.file}`,
205
+ }));
206
+ // Widest last within a format, which is the order a `srcset` reads best in
207
+ // and the order `sizes` is evaluated against.
208
+ variants.sort((left, right) => left.width - right.width);
209
+
210
+ const formats = [];
211
+ for (const variant of variants) {
212
+ if (variant.format === image.format) continue;
213
+ if (!formats.includes(variant.format)) formats.push(variant.format);
214
+ }
215
+
216
+ const srcSetFor = (format) =>
217
+ variants
218
+ .filter((variant) => variant.format === format)
219
+ // `640w` and not `2x`: a density descriptor describes one layout width,
220
+ // and the whole point of the ladder is that the layout width is not
221
+ // known here. With `w`, the browser combines it with `sizes` and picks.
222
+ .map((variant) => `${variant.url} ${variant.width}w`)
223
+ .join(", ");
224
+
225
+ const fallbacks = variants.filter((variant) => variant.format === image.format);
226
+ const widest = fallbacks[fallbacks.length - 1] ?? variants[variants.length - 1];
227
+
228
+ return {
229
+ src: widest?.url ?? null,
230
+ width: image.width,
231
+ height: image.height,
232
+ srcSet: srcSetFor(image.format),
233
+ // Alternatives first: a browser takes the first `<source>` it understands,
234
+ // so the format every browser understands must not be offered before the
235
+ // ones that are smaller.
236
+ sources: formats.map((format) => ({
237
+ type: variants.find((variant) => variant.format === format).mime,
238
+ srcSet: srcSetFor(format),
239
+ })),
240
+ blurDataURL: image.blur,
241
+ // Carried through so a project can see what the pipeline decided and why,
242
+ // rather than having to infer it from what is missing: `hero.declined` is
243
+ // the widths where the alternative format was encoded and came out larger,
244
+ // with both byte counts. Nothing prints them — a line on every build about
245
+ // a format that was correctly not emitted is noise — and `uf explain build`
246
+ // is where the limit itself is stated.
247
+ declined: image.declined,
248
+ note: image.note,
249
+ };
250
+ }
251
+
252
+ /**
253
+ * uf's asset pipeline, as a Vite plugin.
254
+ *
255
+ * @param {object} options
256
+ * @param {object} [options.images] `app.builtins.images`
257
+ * @param {object} [options.fonts] `app.builtins.fonts`
258
+ * @param {object} [options.icons] `app.builtins.icons`
259
+ * @param {object} [options.og] `app.builtins.og`
260
+ * @param {string} [options.command] the `uf` binary to transform through
261
+ */
262
+ export function assetPlugin({ images = {}, fonts = {}, icons = {}, og = {}, command } = {}) {
263
+ // Both halves can be turned off independently, and a plugin that is off is
264
+ // still in the array: `uf inspect` lists the resolved pipeline, and a
265
+ // pipeline that changes shape when a feature is disabled is a pipeline whose
266
+ // listing cannot be compared between two projects.
267
+ const imagesOn = images.enabled !== false;
268
+ const fontsOn = fonts.enabled !== false;
269
+ const iconsOn = icons.enabled !== false;
270
+ const ogOn = og.enabled !== false;
271
+ const iconDir = icons.dir ?? "icons";
272
+
273
+ let root = process.cwd();
274
+ let base = "/";
275
+ let assetsDir = "assets";
276
+ let isBuild = false;
277
+ /** @type {import("vite").ViteDevServer | null} */
278
+ let server = null;
279
+ /** @type {AssetService | null} */
280
+ let service = null;
281
+ /**
282
+ * The manifest for each source path, so one image is transformed once.
283
+ *
284
+ * `uf build` runs Vite twice over the same modules — once for the browser
285
+ * bundle and once for the server one — from a single plugin array, so both
286
+ * passes share this map and the second decodes nothing. It survives
287
+ * `buildEnd` deliberately: clearing it there is what made the server pass
288
+ * redo every image, which is the whole cost this map exists to avoid.
289
+ */
290
+ const transformed = new Map();
291
+ /** Whether anything imported the sprite at all. */
292
+ let spriteRequested = false;
293
+ /**
294
+ * Every icon this build has reached, by symbol id.
295
+ *
296
+ * Here and not in the `uf assets` process, because this closure outlives it:
297
+ * a build closes the service in `buildEnd`, which runs *before*
298
+ * `generateBundle`, and a build with a client environment and a server one
299
+ * has two bundles and one set of icons between them. The plugin is what
300
+ * spans a build, so the plugin is what remembers.
301
+ */
302
+ const reachedIcons = new Map();
303
+
304
+ const cacheDir = () => path.resolve(root, CACHE_DIR);
305
+ /**
306
+ * The `uf assets` process, started on the first asset and not before.
307
+ *
308
+ * Lazily rather than in `buildStart`, which is where `uf:flow` starts its
309
+ * transform service: that one is going to be asked about every module in the
310
+ * project, and this one is asked about nothing at all in a project that
311
+ * imports no images or fonts. A build that has no use for an image codec
312
+ * should not spawn one.
313
+ */
314
+ const ensureService = () => {
315
+ service ??= new AssetService({ command, root });
316
+ return service;
317
+ };
318
+
319
+ /**
320
+ * Where a transformed file is served from.
321
+ *
322
+ * A build's URL is the bundler's output directory; a dev server's is this
323
+ * plugin's own middleware. This is the *only* thing that differs between the
324
+ * two schedules, and it is one string.
325
+ */
326
+ const baseUrl = () => (isBuild ? `${base}${assetsDir}/` : `${base}${DEV_PREFIX}`);
327
+
328
+ const claims = (id) => {
329
+ // A query is Vite's, not uf's. See the header.
330
+ if (id.includes("?")) return null;
331
+ if (id.startsWith("\0")) return null;
332
+ const kind = assetKind(id);
333
+ if (kind === "image" && !imagesOn) return null;
334
+ if (kind === "font" && !fontsOn) return null;
335
+ if (kind === "og" && !ogOn) return null;
336
+ if ((kind === "icon" || kind === "sprite") && !iconsOn) return null;
337
+ return kind;
338
+ };
339
+
340
+ /**
341
+ * The file one `uf:icon/<name>` names.
342
+ *
343
+ * The name is a path segment and nothing else. `..` in it would reach out of
344
+ * the icon directory and turn an import into a way to read the repository,
345
+ * so it is rejected rather than resolved — the same rule the dev middleware
346
+ * applies to an emitted file name.
347
+ */
348
+ const iconFile = (id) => {
349
+ const name = id.slice(ICON_PREFIX.length);
350
+ if (name === "" || name.includes("..") || path.isAbsolute(name)) return null;
351
+ return { name, file: path.resolve(root, iconDir, `${name}.svg`) };
352
+ };
353
+
354
+ /** Tell a dev server the sprite it already sent is missing an icon. */
355
+ const invalidateSprite = () => {
356
+ if (server == null || !spriteRequested) return;
357
+ const module = server.moduleGraph.getModuleById(ICON_SPRITE);
358
+ if (module != null) server.moduleGraph.invalidateModule(module);
359
+ };
360
+
361
+ return {
362
+ name: "uf:asset",
363
+ // Before Vite's own asset handling, which would otherwise claim the same
364
+ // extensions and return a URL string.
365
+ enforce: "pre",
366
+
367
+ configResolved(config) {
368
+ root = config.root;
369
+ base = config.base;
370
+ assetsDir = config.build?.assetsDir ?? "assets";
371
+ isBuild = config.command === "build";
372
+ },
373
+
374
+ // `uf:icon/…` and `uf:icon-sprite` are uf's own ids and resolve to
375
+ // themselves. Returning the id unchanged rather than a `\0`-prefixed one
376
+ // keeps it readable in a stack trace and in `vite --debug`, and nothing
377
+ // else in the pipeline claims the `uf:` scheme.
378
+ //
379
+ // A card is the opposite case: it has to *lose* its name, because the name
380
+ // is what the native JSON plugin claims it by. See `OG_PREFIX`.
381
+ async resolveId(id, importer, options) {
382
+ if (iconsOn && (id === ICON_SPRITE || id.startsWith(ICON_PREFIX))) return id;
383
+ if (!ogOn || !id.toLowerCase().endsWith(OG_EXTENSION)) return null;
384
+ // Compared against the id as written, so a query is never claimed:
385
+ // `./card.og.json?raw` and `?url` still reach the file, because a query
386
+ // is Vite's.
387
+ const resolved = await this.resolve(id, importer, { ...options, skipSelf: true });
388
+ if (resolved == null || resolved.external || !existsSync(resolved.id)) return resolved;
389
+ return `${OG_PREFIX}${resolved.id}${OG_SUFFIX}`;
390
+ },
391
+
392
+ async load(id) {
393
+ // `@uniflowed/web`'s idea of the image endpoint, answered with the
394
+ // project's. See `imageEndpointSource`.
395
+ if (isWebImageEndpoint(id)) {
396
+ return imageEndpointSource(imagesOn ? images : { enabled: false }, base);
397
+ }
398
+ if (id.startsWith(OG_PREFIX)) {
399
+ const file = id.slice(OG_PREFIX.length, -OG_SUFFIX.length);
400
+ // Watched by hand, because the module id is no longer the file's path
401
+ // and nothing else would associate the two. Without this a dev server
402
+ // never redraws a card whose template was edited.
403
+ this.addWatchFile(file);
404
+ return loadAsset.call(this, {
405
+ kind: "og",
406
+ file,
407
+ transformed,
408
+ service: ensureService(),
409
+ cacheDir: cacheDir(),
410
+ baseUrl: baseUrl(),
411
+ assetsDir,
412
+ isBuild,
413
+ images,
414
+ fonts,
415
+ });
416
+ }
417
+
418
+ const kind = claims(id);
419
+ if (kind == null) return null;
420
+
421
+ if (kind === "sprite") {
422
+ spriteRequested = true;
423
+ // A build cannot know the sprite here: `load` runs while the graph is
424
+ // still being walked, so the set of icons reached so far is not the
425
+ // set. It emits a placeholder that `generateBundle` — the first hook
426
+ // after every module has been loaded — replaces with the real markup.
427
+ //
428
+ // A dev server has no `generateBundle`, so it assembles from what has
429
+ // been reached and invalidates this module whenever a new icon turns
430
+ // up. That costs one extra reload the first time a page introduces an
431
+ // icon and is exactly right afterwards, which is the trade a dev
432
+ // server makes everywhere else too.
433
+ if (isBuild) return assetModuleSource({ markup: SPRITE_PLACEHOLDER });
434
+ const sprite = await ensureService().sprite({
435
+ outDir: cacheDir(),
436
+ icons: [...reachedIcons.values()],
437
+ });
438
+ return assetModuleSource({ markup: sprite.markup });
439
+ }
440
+
441
+ if (kind === "icon") {
442
+ const resolved = iconFile(id);
443
+ if (resolved == null) return null;
444
+ if (!existsSync(resolved.file)) {
445
+ this.error(
446
+ `${id} does not exist: uf looked for ${path.relative(root, resolved.file)}. ` +
447
+ "`app.builtins.icons.dir` is where `uf:icon/…` resolves against.",
448
+ );
449
+ }
450
+ const asset = await ensureService().icon(resolved.file, {
451
+ outDir: cacheDir(),
452
+ name: resolved.name,
453
+ });
454
+ this.addWatchFile(resolved.file);
455
+ reachedIcons.set(asset.id, asset);
456
+ invalidateSprite();
457
+ return assetModuleSource({
458
+ id: asset.id,
459
+ href: `#${asset.id}`,
460
+ viewBox: asset.viewBox,
461
+ width: asset.width,
462
+ height: asset.height,
463
+ });
464
+ }
465
+
466
+ const file = path.resolve(id);
467
+ // Not this plugin's to fail on: an id with one of these extensions that
468
+ // is not a file on disk is a virtual module somebody else owns.
469
+ if (!existsSync(file)) return null;
470
+
471
+ return loadAsset.call(this, {
472
+ kind,
473
+ file,
474
+ transformed,
475
+ service: ensureService(),
476
+ cacheDir: cacheDir(),
477
+ baseUrl: baseUrl(),
478
+ assetsDir,
479
+ isBuild,
480
+ images,
481
+ fonts,
482
+ });
483
+ },
484
+
485
+ // After every module has been loaded, which is the first moment the set of
486
+ // icons this build reached is the whole set. A sprite assembled in `load`
487
+ // would hold the icons reached *so far*, which is a different sprite on
488
+ // every run depending on module order.
489
+ async generateBundle(_options, bundle) {
490
+ if (!iconsOn || !spriteRequested) return;
491
+ const sprite = await ensureService().sprite({
492
+ outDir: cacheDir(),
493
+ icons: [...reachedIcons.values()],
494
+ });
495
+ // Inlined into the chunk and *not* emitted as a file of its own. An
496
+ // external sprite would be the better answer if it worked — one file
497
+ // cached across every page — but `<use href="sprite.svg#id">` does not
498
+ // resolve across documents in any version of Safari and is blocked
499
+ // cross-origin in Chrome, so the file would be dead weight in `dist/`
500
+ // and in `uf_bundle`'s size report. `uf assets` still writes it into the
501
+ // cache directory, which is where the dev server reads it from.
502
+ //
503
+ // The placeholder is replaced rather than the module re-run: by
504
+ // `generateBundle` the chunk is already generated, and the sprite is one
505
+ // string literal in it.
506
+ //
507
+ // A function replacement, because a plain string one would interpret
508
+ // `$&` and `$'` — and an icon is somebody else's markup.
509
+ const escaped = JSON.stringify(sprite.markup).slice(1, -1);
510
+ for (const chunk of Object.values(bundle)) {
511
+ if (chunk.type === "chunk" && chunk.code.includes(SPRITE_PLACEHOLDER)) {
512
+ chunk.code = chunk.code.replaceAll(SPRITE_PLACEHOLDER, () => escaped);
513
+ }
514
+ }
515
+ },
516
+
517
+ configureServer(devServer) {
518
+ server = devServer;
519
+ devServer.httpServer?.once("close", () => {
520
+ service?.close();
521
+ service = null;
522
+ });
523
+
524
+ // Before Vite's own middlewares: nothing else knows this prefix, and the
525
+ // files are outside the module graph, so there is nothing to wait for.
526
+ const directory = cacheDir();
527
+ devServer.middlewares.use((request, response, next) => {
528
+ const url = request.url ?? "";
529
+ const at = url.indexOf(DEV_PREFIX);
530
+ if (at === -1) return next();
531
+ const name = decodeURIComponent(url.slice(at + DEV_PREFIX.length).split("?")[0]);
532
+ // The name is a file name and nothing else. Every emitted name is one
533
+ // path segment by construction, so a request carrying a separator is
534
+ // not a name this plugin ever minted — refusing it rather than
535
+ // resolving it is what keeps the cache directory from being a way to
536
+ // read the rest of the disk.
537
+ if (name === "" || name.includes("/") || name.includes("\\") || name.includes("..")) {
538
+ response.statusCode = 400;
539
+ response.end("bad asset name");
540
+ return;
541
+ }
542
+ const target = path.join(directory, name);
543
+ if (!existsSync(target)) return next();
544
+ response.setHeader("Content-Type", contentTypeOf(name));
545
+ // The name is a content hash, so the bytes under it never change.
546
+ response.setHeader("Cache-Control", "public, max-age=31536000, immutable");
547
+ response.end(readFileSync(target));
548
+ });
549
+
550
+ // `/__uf/image`, so an `Image` with a remote `src` renders under
551
+ // `uf dev` exactly as it will under `uf start`: the same endpoint, the
552
+ // same allow-list, the same encoder. Mounted only for a project that
553
+ // listed remote hosts, and built on the first request for it rather
554
+ // than with the server. See `./image-endpoint.js`.
555
+ if (imagesOn && servesRemoteImages(images)) {
556
+ const endpointPath = `${base}__uf/image`;
557
+ let ready = null;
558
+ devServer.middlewares.use((request, response, next) => {
559
+ const url = request.url ?? "";
560
+ const queryAt = url.indexOf("?");
561
+ if ((queryAt === -1 ? url : url.slice(0, queryAt)) !== endpointPath) return next();
562
+ ready ??= Promise.all([
563
+ localImageEndpoint({ images, root, command }),
564
+ import("@uniflowed/server/node"),
565
+ ]);
566
+ ready
567
+ .then(async ([endpoint, { send }]) => {
568
+ // The endpoint reads the query and `Accept` and nothing else, so
569
+ // that is all the request it is handed carries.
570
+ const accept = request.headers.accept;
571
+ const asked = new Request(
572
+ `http://localhost/__uf/image${queryAt === -1 ? "" : url.slice(queryAt)}`,
573
+ {
574
+ method: request.method,
575
+ headers: typeof accept === "string" ? { accept } : {},
576
+ },
577
+ );
578
+ const answered = await endpoint(asked);
579
+ if (answered == null) return next();
580
+ await send(response, answered);
581
+ return undefined;
582
+ })
583
+ .catch(next);
584
+ return undefined;
585
+ });
586
+ }
587
+ },
588
+
589
+ watchChange(id) {
590
+ // The memo below is what stops `uf build` decoding every image twice,
591
+ // once per bundle. In a dev server it would also stop uf ever noticing
592
+ // that an image was edited: Vite invalidates the module and calls `load`
593
+ // again, and `load` would hand back the manifest it made before the
594
+ // change. Dropping both keys is cheap and the next `load` redoes the
595
+ // work — which, because the emitted names are content hashes, writes new
596
+ // files and leaves the old ones for anything still holding a URL.
597
+ transformed.delete(`image:${path.resolve(id)}`);
598
+ transformed.delete(`font:${path.resolve(id)}`);
599
+ transformed.delete(`og:${path.resolve(id)}`);
600
+ },
601
+
602
+ buildEnd() {
603
+ // A dev server keeps its service for the whole session; a build is done
604
+ // with it here. The same rule `uf:flow` follows next door.
605
+ //
606
+ // `transformed` is *not* cleared. A build's second pass over the same
607
+ // modules then needs no process at all — every answer is already in the
608
+ // map, and `ensureService` is never reached.
609
+ if (server == null) {
610
+ service?.close();
611
+ service = null;
612
+ }
613
+ },
614
+ };
615
+ }
616
+
617
+ /**
618
+ * Transform one asset and return the module that stands for it.
619
+ *
620
+ * Split out of the hook so the hook stays readable and so the memoisation is
621
+ * visible: `uf build` runs Vite twice over the same modules, once for the
622
+ * browser bundle and once for the server one, and an image transformed on both
623
+ * passes would be decoded twice for one build.
624
+ */
625
+ async function loadAsset(context) {
626
+ const { kind, file, transformed, service, cacheDir, baseUrl, assetsDir, isBuild, images, fonts } =
627
+ context;
628
+ const key = `${kind}:${file}`;
629
+ let manifest = transformed.get(key);
630
+ if (manifest == null) {
631
+ if (kind === "image") {
632
+ manifest = await service.image(file, {
633
+ outDir: cacheDir,
634
+ widths: images.widths,
635
+ quality: images.quality,
636
+ blur: images.placeholder,
637
+ });
638
+ } else if (kind === "og") {
639
+ manifest = await service.og(file, { outDir: cacheDir });
640
+ } else {
641
+ manifest = await service.font(file, {
642
+ outDir: cacheDir,
643
+ family: fonts.family,
644
+ display: fonts.display,
645
+ subset: fonts.subset,
646
+ preload: fonts.preload,
647
+ baseUrl,
648
+ });
649
+ }
650
+ transformed.set(key, manifest);
651
+ }
652
+
653
+ const files =
654
+ kind === "image"
655
+ ? manifest.variants.map((v) => v.file)
656
+ : kind === "og"
657
+ ? [manifest.file]
658
+ : // Every bucket, not just the primary: a `unicode-range` split emits
659
+ // one file per script and the browser fetches whichever the page
660
+ // needs. Emitting only the one the manifest calls primary would
661
+ // leave the others named in the stylesheet and absent from `dist/`.
662
+ manifest.faces.map((face) => face.file);
663
+ if (isBuild) {
664
+ // Handed to Rollup rather than copied by hand, so the bundler owns what
665
+ // lands in the output directory and `uf_bundle`'s size report — which
666
+ // walks that directory — counts every one of them.
667
+ for (const name of files) {
668
+ this.emitFile({
669
+ type: "asset",
670
+ // `fileName` rather than `name`: the name is already a content hash of
671
+ // the source and the parameters, and letting Rollup hash it again
672
+ // would move it on every encoder change while saying nothing new.
673
+ fileName: `${assetsDir}/${name}`,
674
+ source: readFileSync(path.join(cacheDir, name)),
675
+ });
676
+ }
677
+ }
678
+
679
+ if (kind === "image") {
680
+ return assetModuleSource(withUrls(manifest, baseUrl));
681
+ }
682
+ if (kind === "og") {
683
+ return assetModuleSource({
684
+ // The shape `Metadata.openGraph.images` and `OgImage` both read. A URL,
685
+ // a size and the alt text, which is all a card ever is to a page.
686
+ url: `${baseUrl}${manifest.file}`,
687
+ width: manifest.width,
688
+ height: manifest.height,
689
+ type: manifest.mime,
690
+ alt: manifest.alt,
691
+ bytes: manifest.bytes,
692
+ });
693
+ }
694
+ return assetModuleSource({
695
+ src: `${baseUrl}${manifest.file}`,
696
+ family: manifest.family,
697
+ fallbackFamily: manifest.fallbackFamily,
698
+ // The stack a page should set `font-family` to: the real face, then the
699
+ // metric-matched fallback, then the local face it was scaled from. Written
700
+ // here so no page has to remember that the fallback only ever applies when
701
+ // it is named after the real face.
702
+ fontFamily: [manifest.family, manifest.fallbackFamily, manifest.fallback?.local]
703
+ .filter((name) => name != null)
704
+ .map((name) => JSON.stringify(name))
705
+ .join(", "),
706
+ type: manifest.mime,
707
+ css: manifest.css,
708
+ metrics: manifest.metrics,
709
+ fallback: manifest.fallback,
710
+ fallbackDeclined: manifest.fallbackDeclined,
711
+ // Every emitted file with its URL, so `Font` can preload exactly the one
712
+ // marked rather than all of them — which is the one thing that would undo
713
+ // a `unicode-range` split.
714
+ faces: (manifest.faces ?? []).map((face) => ({
715
+ ...face,
716
+ url: `${baseUrl}${face.file}`,
717
+ })),
718
+ subset: manifest.subset ?? null,
719
+ // Carried through for the same reason `declined` is on an image: a project
720
+ // that asked for a subset and got the whole font is entitled to the
721
+ // sentence saying why, without reading this plugin.
722
+ subsetDeclined: manifest.subsetDeclined ?? null,
723
+ sourceBytes: manifest.sourceBytes ?? null,
724
+ });
725
+ }
726
+
727
+ /** The media type for one emitted file name. */
728
+ function contentTypeOf(name) {
729
+ const extension = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
730
+ const types = {
731
+ avif: "image/avif",
732
+ gif: "image/gif",
733
+ jpg: "image/jpeg",
734
+ jpeg: "image/jpeg",
735
+ otf: "font/otf",
736
+ png: "image/png",
737
+ svg: "image/svg+xml",
738
+ ttf: "font/ttf",
739
+ webp: "image/webp",
740
+ woff: "font/woff",
741
+ woff2: "font/woff2",
742
+ };
743
+ return types[extension] ?? "application/octet-stream";
744
+ }