@jayalfredprufrock/ansel 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jayalfredprufrock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # ansel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Responsive images for Vite, Astro and React, built around an image optimizer you host yourself.
4
+
5
+ > **Status:** pre-1.0. The Vite plugin and `<Img>` for Astro and React work. The optimizer (an AWS CDK construct) is not built yet: the dev server serves images locally, but production builds produce `/_img/…` URLs that nothing serves until it ships. Minor versions may include breaking changes until 1.0.
6
+
7
+ ## What it does
8
+
9
+ - **Typed image names.** Source images live in your repo. Image names are TypeScript types, so a misspelled name fails the type check.
10
+ - **Required alt text.** Every image a project uses is listed in `images.ts` with alt text, or with `decorative: true`.
11
+ - **`<Img>` for Astro and React.** `srcset` and `sizes` from fixed width steps, AVIF with WebP fallback, aspect ratio presets cropped around the image's focal point, and a placeholder inlined as a data URI. No JavaScript, and it works under a strict Content Security Policy.
12
+ - **A committed manifest.** The Vite plugin records each image's size, focal point, tiny preview and dominant color in `manifest.json`, so builds read it instead of decoding images. In CI, a stale manifest fails the build.
13
+ - **One URL format** (`/_img/…`) shared by the components, the dev server and the optimizer. Only fixed widths, ratios, formats and quality levels exist, so the number of variants stays small and URLs can't be invented.
14
+ - **Optional checks**, all off by default: reject camera or stock file names, GPS data, large files or huge images.
15
+
16
+ ## Setup
17
+
18
+ ```sh
19
+ pnpm add @jayalfredprufrock/ansel
20
+ ```
21
+
22
+ Add the Vite plugin. In Astro:
23
+
24
+ ```ts
25
+ // astro.config.ts
26
+ import { ansel } from "@jayalfredprufrock/ansel/vite";
27
+ import { defineConfig } from "astro/config";
28
+
29
+ export default defineConfig({
30
+ vite: { plugins: [ansel()] },
31
+ });
32
+ ```
33
+
34
+ Put images in `src/images/`, in any subfolder. File names use lowercase letters, digits and dashes (`team/dr-patel.jpg`); the name is the path without the extension (`team/dr-patel`). Formats: JPEG, PNG, WebP and AVIF.
35
+
36
+ List the images you use in `src/images/images.ts` (the plugin creates a starter file):
37
+
38
+ ```ts
39
+ import { defineImages } from "@jayalfredprufrock/ansel";
40
+
41
+ export default defineImages({
42
+ "team/dr-patel": { alt: "Dr. Patel smiling in the exam room" },
43
+ "office/pattern": { decorative: true },
44
+ // Override the detected focal point (percentages from the top left):
45
+ "office/waiting-room": { alt: "The waiting room", focal: [30, 60] },
46
+ });
47
+ ```
48
+
49
+ The plugin writes `manifest.json` and `types.d.ts` next to it. Commit all three.
50
+
51
+ ## Usage
52
+
53
+ Astro:
54
+
55
+ ```astro
56
+ ---
57
+ import Img from "@jayalfredprufrock/ansel/Img.astro";
58
+ ---
59
+
60
+ <Img name="team/dr-patel" priority />
61
+ <Img name="team/dr-patel" ratio="1:1" sizes="20rem" />
62
+ ```
63
+
64
+ React:
65
+
66
+ ```tsx
67
+ import "@jayalfredprufrock/ansel/styles.css"; // once, in your entry
68
+ import { Img } from "@jayalfredprufrock/ansel/react";
69
+ import drPatel from "./images/team/dr-patel.jpg?ansel";
70
+
71
+ <Img image={drPatel} ratio="4:3" sizes="(min-width: 40rem) 40rem, 100vw" />;
72
+ ```
73
+
74
+ React bundles include only the images a module imports.
75
+
76
+ ### Props
77
+
78
+ | Prop | Default | What it does |
79
+ | ------------- | -------------------------------------- | ------------------------------------------------------------------------------------ |
80
+ | `sizes` | `100vw` | How wide the image is shown. Set it for anything narrower than the viewport. |
81
+ | `ratio` | original | `1:1`, `4:3`, `3:4`, `3:2`, `2:3`, `16:9` or `21:9`, cropped around the focal point. |
82
+ | `priority` | `false` | Load right away with high priority. Use it for the main image above the fold. |
83
+ | `placeholder` | `blur` (`none` for transparent images) | `blur`, `pixelated`, `color` or `none`. |
84
+ | `quality` | `standard` | `low`, `standard` or `high`. |
85
+ | `alt` | from `images.ts` | Overrides the alt text for this use. |
86
+
87
+ Images load lazily unless `priority` is set. Styles live in `@layer ansel`, so your own CSS wins.
88
+
89
+ ## Plugin options
90
+
91
+ | Option | Default | What it does |
92
+ | ----------------- | ------------------------------------ | --------------------------------------------------------------------------------- |
93
+ | `dir` | `src/images` | Folder of source images, relative to the Vite root. |
94
+ | `manifest` | `check` if `CI` is set, else `write` | `write` updates the manifest and types; `check` fails the build if they're stale. |
95
+ | `rejectPoorNames` | `false` | Reject camera and stock names (`IMG_4821`, `DSC01234`, `pexels-photo-…`). |
96
+ | `rejectGps` | `false` | Reject images that still carry GPS location data. |
97
+ | `maxFileSize` | none | Reject files larger than this many bytes. |
98
+ | `maxPixels` | none | Reject images with more than this many pixels. |
99
+
100
+ Problems are warnings in dev and fail the build.
101
+
102
+ ## Exports
103
+
104
+ | Import | What it is |
105
+ | ------------------------------------- | ------------------------------------------ |
106
+ | `@jayalfredprufrock/ansel` | `defineImages` and types |
107
+ | `@jayalfredprufrock/ansel/vite` | Vite plugin |
108
+ | `@jayalfredprufrock/ansel/Img.astro` | `<Img>` for Astro |
109
+ | `@jayalfredprufrock/ansel/react` | `<Img>` for React |
110
+ | `@jayalfredprufrock/ansel/styles.css` | Styles (Astro's `<Img>` includes them) |
111
+ | `@jayalfredprufrock/ansel/url` | URL format: building and parsing `/_img/…` |
112
+
113
+ ## Requirements
114
+
115
+ Node 22.18 or newer, Vite 8, and Astro 7 or React 19.
116
+
117
+ ## License
118
+
119
+ MIT
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Image files found in the images folder. Filled in by the generated `types.d.ts`.
3
+ * @internal
4
+ */
5
+ export interface ImageFiles {}
6
+ /**
7
+ * The project's `images.ts` entries. Filled in by the generated `types.d.ts`, so image names
8
+ * are checked everywhere `<Img>` is used.
9
+ */
10
+ export interface ImageRegistry {}
11
+ /** An image file's name: its path inside the images folder, without the extension. */
12
+ export type ImageFileName = keyof ImageFiles extends never ? string : Extract<keyof ImageFiles, string>;
13
+ /** A usable image's name: one with an entry in `images.ts`. */
14
+ export type ImageName = keyof ImageRegistry extends never ? string : Extract<keyof ImageRegistry, string>;
15
+ /** A point in the image as whole percentages from the top-left corner: `[x, y]`. */
16
+ export type Focal = readonly [x: number, y: number];
17
+ interface EntryBase {
18
+ /** Overrides the automatically detected focal point that crops center on. */
19
+ focal?: Focal;
20
+ }
21
+ /** One image's hand-written data: alt text, or an explicit `decorative: true`. */
22
+ export type ImageEntry = (EntryBase & {
23
+ alt: string;
24
+ decorative?: never;
25
+ }) | (EntryBase & {
26
+ decorative: true;
27
+ alt?: never;
28
+ });
29
+ /**
30
+ * Lists the images a project can use, each with its alt text (or `decorative: true`).
31
+ * Keys must be image files in the images folder.
32
+ */
33
+ export declare function defineImages<const T extends { [K in ImageFileName]?: ImageEntry; }>(images: T & Record<Exclude<keyof T, ImageFileName>, never>): T;
34
+ /** Everything a component needs to render one image. Built by the Vite plugin. */
35
+ export interface AnselImage {
36
+ name: string;
37
+ /** URL hash: covers the content and the effective focal point. */
38
+ hash: string;
39
+ /** Last segment of the name, used in URLs. */
40
+ slug: string;
41
+ /** Original size after EXIF orientation. */
42
+ width: number;
43
+ height: number;
44
+ focal: Focal;
45
+ /** ~16 px WebP data URI for the blur and pixelated placeholders. */
46
+ preview: string;
47
+ /** Dominant color as `#rrggbb` for the color placeholder. */
48
+ color: string;
49
+ /** Has transparent areas: no placeholder by default. */
50
+ alpha: boolean;
51
+ /** Alt text from `images.ts`; absent for decorative images. */
52
+ alt?: string;
53
+ decorative: boolean;
54
+ }
55
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1,9 @@
1
+ // src/index.ts
2
+ /**
3
+ * Lists the images a project can use, each with its alt text (or `decorative: true`).
4
+ * Keys must be image files in the images folder.
5
+ */
6
+ function defineImages(images) {
7
+ return images;
8
+ }
9
+ export { defineImages };
@@ -0,0 +1,13 @@
1
+ import { AnselImage } from "./index.mjs";
2
+ import { ImgOptions } from "./render.mjs";
3
+ export interface ImgProps extends ImgOptions {
4
+ /** An image imported with `?ansel`: `import drPatel from "./images/team/dr-patel.jpg?ansel"`. */
5
+ image: AnselImage;
6
+ /** Class for the wrapper element (the box the image fills). */
7
+ className?: string | undefined;
8
+ }
9
+ /**
10
+ * Responsive image with AVIF and WebP sources and an inline placeholder. Import
11
+ * `@jayalfredprufrock/ansel/styles.css` once for the placeholder styles.
12
+ */
13
+ export declare function Img({ image, className, ...options }: ImgProps): import("react").JSX.Element;
package/dist/react.mjs ADDED
@@ -0,0 +1,30 @@
1
+ import { imgMarkup } from "./render.mjs";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ // src/react.tsx
4
+ /**
5
+ * Responsive image with AVIF and WebP sources and an inline placeholder. Import
6
+ * `@jayalfredprufrock/ansel/styles.css` once for the placeholder styles.
7
+ */
8
+ function Img({ image, className, ...options }) {
9
+ const { placeholder, placeholderSrc, sources, img } = imgMarkup(image, options);
10
+ const { fetchpriority, srcset, ...attributes } = img;
11
+ return /* @__PURE__ */ jsxs("span", {
12
+ className: className ? `ansel ${className}` : "ansel",
13
+ "data-placeholder": placeholder,
14
+ children: [placeholderSrc && /* @__PURE__ */ jsx("img", {
15
+ className: "ansel-placeholder",
16
+ src: placeholderSrc,
17
+ alt: "",
18
+ "aria-hidden": "true"
19
+ }), /* @__PURE__ */ jsxs("picture", { children: [sources.map(({ type, srcset: set, sizes }) => /* @__PURE__ */ jsx("source", {
20
+ type,
21
+ srcSet: set,
22
+ sizes
23
+ }, type)), /* @__PURE__ */ jsx("img", {
24
+ ...attributes,
25
+ srcSet: srcset,
26
+ fetchPriority: fetchpriority
27
+ })] })]
28
+ });
29
+ }
30
+ export { Img };
@@ -0,0 +1,41 @@
1
+ import { AnselImage } from "./index.mjs";
2
+ import { c as Ratio, o as Quality } from "./url-CusqnYrk.mjs";
3
+ export type Placeholder = "blur" | "pixelated" | "color" | "none";
4
+ export interface ImgOptions {
5
+ /** Crop to this aspect ratio, centered on the image's focal point. Default: the original's. */
6
+ ratio?: Ratio | undefined;
7
+ /** The `sizes` attribute: how wide the image is shown. Default: `100vw`. */
8
+ sizes?: string | undefined;
9
+ /** Default: `standard`. */
10
+ quality?: Quality | undefined;
11
+ /** Default: `blur`, or `none` for images with transparency. */
12
+ placeholder?: Placeholder | undefined;
13
+ /** Above-the-fold images: load eagerly with high priority instead of lazily. */
14
+ priority?: boolean | undefined;
15
+ /** Overrides the alt text from `images.ts` for this use. */
16
+ alt?: string | undefined;
17
+ }
18
+ export interface ImgMarkup {
19
+ placeholder: Placeholder;
20
+ /** Data URI shown under the image while it loads. */
21
+ placeholderSrc?: string;
22
+ /** `<source>` elements, best format first. */
23
+ sources: {
24
+ type: string;
25
+ srcset: string;
26
+ sizes: string;
27
+ }[];
28
+ img: {
29
+ src: string;
30
+ srcset: string;
31
+ sizes: string;
32
+ width: number;
33
+ height: number;
34
+ alt: string;
35
+ loading: "eager" | "lazy";
36
+ decoding: "async";
37
+ fetchpriority?: "high";
38
+ };
39
+ }
40
+ /** Everything `<Img>` renders, shared by the Astro and React components. */
41
+ export declare function imgMarkup(image: AnselImage, options?: ImgOptions): ImgMarkup;
@@ -0,0 +1,73 @@
1
+ import { FORMATS, WIDTHS, buildImageUrl, outputSize } from "./url.mjs";
2
+ // src/render.ts
3
+ /** Width steps worth offering: every step up to the first that reaches the largest output. */
4
+ function usefulWidths(image, ratio) {
5
+ const largest = outputSize({
6
+ width: 2560,
7
+ ratio
8
+ }, image).width;
9
+ const widths = [];
10
+ for (const width of WIDTHS) {
11
+ widths.push(width);
12
+ if (width >= largest) break;
13
+ }
14
+ return widths;
15
+ }
16
+ /** Everything `<Img>` renders, shared by the Astro and React components. */
17
+ function imgMarkup(image, options = {}) {
18
+ const { ratio, quality = "standard", priority = false } = options;
19
+ const sizes = options.sizes ?? "100vw";
20
+ const widths = usefulWidths(image, ratio);
21
+ const srcset = (format) => widths.map((width) => {
22
+ return `${buildImageUrl({
23
+ hash: image.hash,
24
+ name: image.slug,
25
+ width,
26
+ ratio,
27
+ quality,
28
+ format
29
+ })} ${outputSize({
30
+ width,
31
+ ratio
32
+ }, image).width}w`;
33
+ }).join(", ");
34
+ const fallbackWidth = widths.find((w) => w >= 960) ?? widths[widths.length - 1] ?? 960;
35
+ const largest = outputSize({
36
+ width: widths[widths.length - 1] ?? 2560,
37
+ ratio
38
+ }, image);
39
+ const placeholder = options.placeholder ?? (image.alpha ? "none" : "blur");
40
+ return {
41
+ placeholder,
42
+ ...placeholder !== "none" && { placeholderSrc: placeholder === "color" ? colorDataUri(image.color) : image.preview },
43
+ sources: FORMATS.filter((f) => f !== "webp").map((format) => ({
44
+ type: `image/${format}`,
45
+ srcset: srcset(format),
46
+ sizes
47
+ })),
48
+ img: {
49
+ src: buildImageUrl({
50
+ hash: image.hash,
51
+ name: image.slug,
52
+ width: fallbackWidth,
53
+ ratio,
54
+ quality,
55
+ format: "webp"
56
+ }),
57
+ srcset: srcset("webp"),
58
+ sizes,
59
+ width: largest.width,
60
+ height: largest.height,
61
+ alt: options.alt ?? image.alt ?? "",
62
+ loading: priority ? "eager" : "lazy",
63
+ decoding: "async",
64
+ ...priority && { fetchpriority: "high" }
65
+ }
66
+ };
67
+ }
68
+ /** A 1×1 SVG in the image's dominant color. */
69
+ function colorDataUri(color) {
70
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="${color}"/></svg>`;
71
+ return `data:image/svg+xml,${encodeURIComponent(svg)}`;
72
+ }
73
+ export { imgMarkup };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The image URL format shared by `<Img>`, the dev server and the optimizer, so they can't disagree.
3
+ *
4
+ * /_img/<hash>/w<width>[-r<ratio>]-q<quality>/<name>.<format>
5
+ * /_img/3f9a2c1b7e04/w1280-r4x3-q75/dr-patel.avif
6
+ *
7
+ * Everything is in the path (no query string). Every part comes from a fixed list or must match
8
+ * an uploaded original, so a URL is valid only if a build could have produced it.
9
+ */
10
+ /** Path prefix the optimizer is served under, on the site's own domain. */
11
+ declare const IMAGE_PATH_PREFIX = "/_img/";
12
+ /** Output widths. Requested widths snap up to the next step. */
13
+ declare const WIDTHS: readonly [320, 480, 640, 800, 960, 1280, 1600, 1920, 2560];
14
+ type Width = (typeof WIDTHS)[number];
15
+ /** Crop aspect ratios as `width:height`. Omit the ratio to keep the original's. */
16
+ declare const RATIOS: readonly ["1:1", "4:3", "3:4", "3:2", "2:3", "16:9", "21:9"];
17
+ type Ratio = (typeof RATIOS)[number];
18
+ declare const QUALITIES: {
19
+ readonly low: 55;
20
+ readonly standard: 75;
21
+ readonly high: 88;
22
+ };
23
+ type Quality = keyof typeof QUALITIES;
24
+ /** Output formats, best first: `<Img>` offers AVIF with a WebP fallback. */
25
+ declare const FORMATS: readonly ["avif", "webp"];
26
+ type Format = (typeof FORMATS)[number];
27
+ interface ImageVariant {
28
+ /** Hash of the original's content and focal point (12 lowercase hex characters). */
29
+ hash: string;
30
+ /** Last segment of the image name, for readable URLs: `team/dr-patel` → `dr-patel`. */
31
+ name: string;
32
+ width: Width;
33
+ /** Crop ratio; `undefined` keeps the original's. */
34
+ ratio?: Ratio | undefined;
35
+ quality: Quality;
36
+ format: Format;
37
+ }
38
+ /** The smallest width step at least `width` wide (the largest step if none is). */
39
+ declare function snapWidth(width: number): Width;
40
+ declare function buildImageUrl(variant: ImageVariant): string;
41
+ /** Parses a URL path; `undefined` for anything a build could not have produced. */
42
+ declare function parseImageUrl(path: string): ImageVariant | undefined;
43
+ /**
44
+ * The pixel size a variant actually comes out at, given the original's size. Never upscales:
45
+ * a crop is limited by the largest region of that ratio the original contains.
46
+ */
47
+ declare function outputSize(variant: Pick<ImageVariant, "width" | "ratio">, original: {
48
+ width: number;
49
+ height: number;
50
+ }): {
51
+ width: number;
52
+ height: number;
53
+ };
54
+ /**
55
+ * The region of the original that a cropped variant shows: the largest area of that ratio,
56
+ * centered on the focal point (given in whole percentages) and kept inside the image.
57
+ */
58
+ declare function cropRegion(original: {
59
+ width: number;
60
+ height: number;
61
+ }, ratio: Ratio, focal: readonly [x: number, y: number]): {
62
+ left: number;
63
+ top: number;
64
+ width: number;
65
+ height: number;
66
+ };
67
+ export { QUALITIES as a, Ratio as c, buildImageUrl as d, cropRegion as f, snapWidth as h, ImageVariant as i, WIDTHS as l, parseImageUrl as m, Format as n, Quality as o, outputSize as p, IMAGE_PATH_PREFIX as r, RATIOS as s, FORMATS as t, Width as u };
package/dist/url.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import { a as QUALITIES, c as Ratio, d as buildImageUrl, f as cropRegion, h as snapWidth, i as ImageVariant, l as WIDTHS, m as parseImageUrl, n as Format, o as Quality, p as outputSize, r as IMAGE_PATH_PREFIX, s as RATIOS, t as FORMATS, u as Width } from "./url-CusqnYrk.mjs";
2
+ export { FORMATS, Format, IMAGE_PATH_PREFIX, ImageVariant, QUALITIES, Quality, RATIOS, Ratio, WIDTHS, Width, buildImageUrl, cropRegion, outputSize, parseImageUrl, snapWidth };
package/dist/url.mjs ADDED
@@ -0,0 +1,118 @@
1
+ // src/url.ts
2
+ /**
3
+ * The image URL format shared by `<Img>`, the dev server and the optimizer, so they can't disagree.
4
+ *
5
+ * /_img/<hash>/w<width>[-r<ratio>]-q<quality>/<name>.<format>
6
+ * /_img/3f9a2c1b7e04/w1280-r4x3-q75/dr-patel.avif
7
+ *
8
+ * Everything is in the path (no query string). Every part comes from a fixed list or must match
9
+ * an uploaded original, so a URL is valid only if a build could have produced it.
10
+ */
11
+ /** Path prefix the optimizer is served under, on the site's own domain. */
12
+ const IMAGE_PATH_PREFIX = "/_img/";
13
+ /** Output widths. Requested widths snap up to the next step. */
14
+ const WIDTHS = [
15
+ 320,
16
+ 480,
17
+ 640,
18
+ 800,
19
+ 960,
20
+ 1280,
21
+ 1600,
22
+ 1920,
23
+ 2560
24
+ ];
25
+ /** Crop aspect ratios as `width:height`. Omit the ratio to keep the original's. */
26
+ const RATIOS = [
27
+ "1:1",
28
+ "4:3",
29
+ "3:4",
30
+ "3:2",
31
+ "2:3",
32
+ "16:9",
33
+ "21:9"
34
+ ];
35
+ const QUALITIES = {
36
+ low: 55,
37
+ standard: 75,
38
+ high: 88
39
+ };
40
+ /** Output formats, best first: `<Img>` offers AVIF with a WebP fallback. */
41
+ const FORMATS = ["avif", "webp"];
42
+ const HASH = /^[0-9a-f]{12}$/;
43
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
44
+ const URL_PATTERN = /^\/_img\/([^/]+)\/w(\d+)(?:-r(\d+)x(\d+))?-q(\d+)\/([^/]+)\.([a-z]+)$/;
45
+ const isWidth = (n) => WIDTHS.includes(n);
46
+ const isRatio = (s) => RATIOS.includes(s);
47
+ const isFormat = (s) => FORMATS.includes(s);
48
+ const isQuality = (s) => Object.hasOwn(QUALITIES, s);
49
+ /** The smallest width step at least `width` wide (the largest step if none is). */
50
+ function snapWidth(width) {
51
+ return WIDTHS.find((step) => step >= width) ?? 2560;
52
+ }
53
+ function buildImageUrl(variant) {
54
+ const { hash, name, width, ratio, quality, format } = variant;
55
+ if (!HASH.test(hash)) throw new Error(`Invalid image hash "${hash}"`);
56
+ if (!NAME.test(name)) throw new Error(`Invalid image name "${name}"`);
57
+ if (!isWidth(width)) throw new Error(`Invalid width ${String(width)}`);
58
+ if (ratio !== void 0 && !isRatio(ratio)) throw new Error(`Invalid ratio "${String(ratio)}"`);
59
+ if (!isQuality(quality)) throw new Error(`Invalid quality "${String(quality)}"`);
60
+ if (!isFormat(format)) throw new Error(`Invalid format "${String(format)}"`);
61
+ const r = ratio ? `-r${ratio.replace(":", "x")}` : "";
62
+ return `${IMAGE_PATH_PREFIX}${hash}/w${width}${r}-q${QUALITIES[quality]}/${name}.${format}`;
63
+ }
64
+ /** Parses a URL path; `undefined` for anything a build could not have produced. */
65
+ function parseImageUrl(path) {
66
+ const match = URL_PATTERN.exec(path);
67
+ if (!match) return void 0;
68
+ const [, hash = "", w = "", rw, rh, q = "", name = "", format = ""] = match;
69
+ const width = Number(w);
70
+ const ratio = rw === void 0 ? void 0 : `${rw}:${rh}`;
71
+ const quality = Object.keys(QUALITIES).find((k) => String(QUALITIES[k]) === q);
72
+ if (!HASH.test(hash) || !NAME.test(name) || String(width) !== w || !isWidth(width) || ratio !== void 0 && !isRatio(ratio) || quality === void 0 || !isFormat(format)) return;
73
+ return {
74
+ hash,
75
+ name,
76
+ width,
77
+ ratio,
78
+ quality,
79
+ format
80
+ };
81
+ }
82
+ /**
83
+ * The pixel size a variant actually comes out at, given the original's size. Never upscales:
84
+ * a crop is limited by the largest region of that ratio the original contains.
85
+ */
86
+ function outputSize(variant, original) {
87
+ if (!variant.ratio) {
88
+ const width = Math.min(variant.width, original.width);
89
+ return {
90
+ width,
91
+ height: Math.round(width * original.height / original.width)
92
+ };
93
+ }
94
+ const [rw = 1, rh = 1] = variant.ratio.split(":").map(Number);
95
+ const maxWidth = Math.min(original.width, Math.floor(original.height * rw / rh));
96
+ const width = Math.min(variant.width, maxWidth);
97
+ return {
98
+ width,
99
+ height: Math.round(width * rh / rw)
100
+ };
101
+ }
102
+ /**
103
+ * The region of the original that a cropped variant shows: the largest area of that ratio,
104
+ * centered on the focal point (given in whole percentages) and kept inside the image.
105
+ */
106
+ function cropRegion(original, ratio, focal) {
107
+ const [rw = 1, rh = 1] = ratio.split(":").map(Number);
108
+ const width = Math.min(original.width, Math.floor(original.height * rw / rh));
109
+ const height = Math.min(original.height, Math.round(width * rh / rw));
110
+ const clamp = (n, max) => Math.min(Math.max(n, 0), max);
111
+ return {
112
+ left: clamp(Math.round(focal[0] / 100 * original.width - width / 2), original.width - width),
113
+ top: clamp(Math.round(focal[1] / 100 * original.height - height / 2), original.height - height),
114
+ width,
115
+ height
116
+ };
117
+ }
118
+ export { FORMATS, IMAGE_PATH_PREFIX, QUALITIES, RATIOS, WIDTHS, buildImageUrl, cropRegion, outputSize, parseImageUrl, snapWidth };
@@ -0,0 +1,24 @@
1
+ import { Plugin } from "vite";
2
+ export interface AnselOptions {
3
+ /** Folder of source images, relative to the Vite root. Default: `src/images`. */
4
+ dir?: string;
5
+ /**
6
+ * `write` keeps `manifest.json` and `types.d.ts` up to date. `check` never writes and fails
7
+ * the build if they are out of date. Default: `check` when the `CI` environment variable is
8
+ * set, `write` otherwise.
9
+ */
10
+ manifest?: "write" | "check";
11
+ /** Reject camera and stock-site file names (`IMG_4821`, `DSC01234`, `pexels-photo-…`). */
12
+ rejectPoorNames?: boolean;
13
+ /** Reject images that still carry GPS location data. */
14
+ rejectGps?: boolean;
15
+ /** Reject source files larger than this many bytes. */
16
+ maxFileSize?: number;
17
+ /** Reject source images with more than this many pixels (width × height). */
18
+ maxPixels?: number;
19
+ }
20
+ /**
21
+ * Keeps the image manifest and types up to date, provides image data to `<Img>`, and serves
22
+ * `/_img/*` locally in dev with the same output as the optimizer.
23
+ */
24
+ export declare function ansel(options?: AnselOptions): Plugin;
package/dist/vite.mjs ADDED
@@ -0,0 +1,491 @@
1
+ import { cropRegion, outputSize, parseImageUrl } from "./url.mjs";
2
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { createHash } from "node:crypto";
6
+ import sharp from "sharp";
7
+ // src/manifest.ts
8
+ const MANIFEST_FILE = "manifest.json";
9
+ const TYPES_FILE = "types.d.ts";
10
+ const ENTRIES_FILE = "images.ts";
11
+ const IMAGE_EXTENSIONS = [
12
+ ".jpg",
13
+ ".jpeg",
14
+ ".png",
15
+ ".webp",
16
+ ".avif"
17
+ ];
18
+ /** Longest side of the inline preview used by the blur and pixelated placeholders. */
19
+ const PREVIEW_SIZE = 16;
20
+ /** Size of the copy the focal point is detected on. */
21
+ const FOCAL_SIZE = 256;
22
+ /** Name segments: lowercase letters and digits joined by single dashes. */
23
+ const NAME_SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
24
+ /** Finds the image files in `dir` (recursively) and derives their names. */
25
+ async function scanImages(dir) {
26
+ const entries = await readdir(dir, {
27
+ recursive: true,
28
+ withFileTypes: true
29
+ }).catch((error) => {
30
+ if (error.code === "ENOENT") return [];
31
+ throw error;
32
+ });
33
+ const images = [];
34
+ const invalid = [];
35
+ const seen = /* @__PURE__ */ new Map();
36
+ const files = entries.filter((entry) => entry.isFile()).map((entry) => relative(dir, join(entry.parentPath, entry.name)).split(sep).join("/")).sort();
37
+ for (const file of files) {
38
+ const dot = file.lastIndexOf(".");
39
+ const extension = dot === -1 ? "" : file.slice(dot).toLowerCase();
40
+ if (!IMAGE_EXTENSIONS.includes(extension)) continue;
41
+ const name = file.slice(0, dot);
42
+ if (!name.split("/").every((segment) => NAME_SEGMENT.test(segment))) {
43
+ const suggestion = suggestName(name);
44
+ invalid.push({
45
+ file,
46
+ reason: `use lowercase letters, digits and dashes, e.g. "${suggestion}${extension}"`,
47
+ suggestion
48
+ });
49
+ continue;
50
+ }
51
+ const other = seen.get(name);
52
+ if (other) {
53
+ invalid.push({
54
+ file,
55
+ reason: `same name as ${other}; rename one of them`
56
+ });
57
+ continue;
58
+ }
59
+ seen.set(name, file);
60
+ images.push({
61
+ name,
62
+ file
63
+ });
64
+ }
65
+ images.sort((a, b) => a.name.localeCompare(b.name));
66
+ return {
67
+ images,
68
+ invalid
69
+ };
70
+ }
71
+ /** Camera, phone and stock-site default names, and names that are mostly a long number. */
72
+ const POOR_NAME = /^(img|dsc[nf]?|pxl|mvimg|gopr|dji|screenshot|screen-shot|untitled|image|photo|pexels-photo|pexels|unsplash|shutterstock|adobestock|istock|istockphoto|gettyimages|depositphotos)(-|$)|\d{5,}|^\d+$/;
73
+ /** Whether a valid image name's last segment is a camera or stock default (`team/img-4821`). */
74
+ function isPoorName(name) {
75
+ return POOR_NAME.test(name.split("/").pop() ?? name);
76
+ }
77
+ /** A valid name close to `name`: `Dr Patel (Portrait)` → `dr-patel-portrait`. */
78
+ function suggestName(name) {
79
+ return name.split("/").map((segment) => segment.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "image").join("/");
80
+ }
81
+ function contentHash(bytes) {
82
+ return createHash("sha256").update(bytes).digest("hex").slice(0, 12);
83
+ }
84
+ /** The hash used in image URLs: covers the content and the focal point crops center on. */
85
+ function urlHash(content, focal) {
86
+ return createHash("sha256").update(`${content}:${focal[0]},${focal[1]}`).digest("hex").slice(0, 12);
87
+ }
88
+ /** Measures an image and builds its manifest entry. */
89
+ async function analyzeImage(file, bytes) {
90
+ const metadata = await sharp(bytes).metadata();
91
+ const width = metadata.autoOrient.width;
92
+ const height = metadata.autoOrient.height;
93
+ const [focal, preview, stats] = await Promise.all([
94
+ detectFocal(bytes),
95
+ sharp(bytes).autoOrient().resize(PREVIEW_SIZE, PREVIEW_SIZE, { fit: "inside" }).webp({ quality: 50 }).toBuffer(),
96
+ sharp(bytes).stats()
97
+ ]);
98
+ const exif = metadata.exif ? readExif(metadata.exif) : {
99
+ gps: false,
100
+ embedded: {}
101
+ };
102
+ const xmp = metadata.xmp ? readXmp(metadata.xmp.toString("utf8")) : {
103
+ gps: false,
104
+ embedded: {}
105
+ };
106
+ const { r, g, b } = stats.dominant;
107
+ return {
108
+ file,
109
+ content: contentHash(bytes),
110
+ width,
111
+ height,
112
+ bytes: bytes.byteLength,
113
+ focal,
114
+ preview: `data:image/webp;base64,${preview.toString("base64")}`,
115
+ color: `#${[
116
+ r,
117
+ g,
118
+ b
119
+ ].map((c) => c.toString(16).padStart(2, "0")).join("")}`,
120
+ alpha: metadata.hasAlpha && !stats.isOpaque,
121
+ gps: exif.gps || xmp.gps,
122
+ embedded: {
123
+ ...exif.embedded,
124
+ ...xmp.embedded
125
+ }
126
+ };
127
+ }
128
+ /** Finds the most interesting point with sharp's attention strategy, as whole percentages. */
129
+ async function detectFocal(bytes) {
130
+ const { data, info } = await sharp(bytes).autoOrient().resize(FOCAL_SIZE, FOCAL_SIZE, { fit: "inside" }).raw().toBuffer({ resolveWithObject: true });
131
+ const side = Math.min(info.width, info.height);
132
+ const { info: result } = await sharp(data, { raw: info }).resize(side, side, {
133
+ fit: "cover",
134
+ position: "attention"
135
+ }).toBuffer({ resolveWithObject: true });
136
+ const x = (result.attentionX ?? info.width / 2) / info.width * 100;
137
+ const y = (result.attentionY ?? info.height / 2) / info.height * 100;
138
+ return [clampPercent(x), clampPercent(y)];
139
+ }
140
+ const clampPercent = (n) => Math.min(100, Math.max(0, Math.round(n)));
141
+ /** Reads the GPS pointer and the description, artist and copyright tags from EXIF IFD0. */
142
+ function readExif(exif) {
143
+ const findings = {
144
+ gps: false,
145
+ embedded: {}
146
+ };
147
+ const tiff = exif.subarray(0, 6).toString("latin1") === "Exif\0\0" ? exif.subarray(6) : exif;
148
+ if (tiff.length < 8) return findings;
149
+ const little = tiff.toString("latin1", 0, 2) === "II";
150
+ const u16 = (o) => little ? tiff.readUInt16LE(o) : tiff.readUInt16BE(o);
151
+ const u32 = (o) => little ? tiff.readUInt32LE(o) : tiff.readUInt32BE(o);
152
+ try {
153
+ const ifd = u32(4);
154
+ const count = u16(ifd);
155
+ for (let i = 0; i < count; i++) {
156
+ const at = ifd + 2 + i * 12;
157
+ const tag = u16(at);
158
+ if (tag === 34853) findings.gps = true;
159
+ const key = {
160
+ 270: "alt",
161
+ 315: "creator",
162
+ 33432: "copyright"
163
+ }[tag];
164
+ if (!key || u16(at + 2) !== 2) continue;
165
+ const length = u32(at + 4);
166
+ const start = length <= 4 ? at + 8 : u32(at + 8);
167
+ const value = tiff.toString("utf8", start, start + length).replace(/\0+$/, "").trim();
168
+ if (value) findings.embedded[key] = value;
169
+ }
170
+ } catch {}
171
+ return findings;
172
+ }
173
+ /** Reads GPS presence, alt text/description, creator and rights from an XMP packet. */
174
+ function readXmp(xmp) {
175
+ const first = (tag) => {
176
+ const block = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`).exec(xmp)?.[1];
177
+ if (block === void 0) return void 0;
178
+ const li = /<rdf:li[^>]*>([\s\S]*?)<\/rdf:li>/.exec(block)?.[1] ?? block;
179
+ return decodeXml(li).trim() || void 0;
180
+ };
181
+ const embedded = {};
182
+ const alt = first("Iptc4xmpCore:AltTextAccessibility") ?? first("dc:description");
183
+ const creator = first("dc:creator");
184
+ const copyright = first("dc:rights");
185
+ if (alt) embedded.alt = alt;
186
+ if (creator) embedded.creator = creator;
187
+ if (copyright) embedded.copyright = copyright;
188
+ return {
189
+ gps: /exif:GPS(Latitude|Longitude)/.test(xmp),
190
+ embedded
191
+ };
192
+ }
193
+ const decodeXml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&apos;/g, "'").replace(/&amp;/g, "&");
194
+ /**
195
+ * Brings the manifest up to date with the folder. Only new or changed files are analyzed;
196
+ * a renamed file reuses its old entry (matched by content hash).
197
+ */
198
+ async function syncManifest(dir, previous) {
199
+ const { images, invalid } = await scanImages(dir);
200
+ const old = previous?.images ?? {};
201
+ const byContent = new Map(Object.values(old).map((entry) => [entry.content, entry]));
202
+ const next = {
203
+ version: 1,
204
+ images: {}
205
+ };
206
+ const updated = [];
207
+ await Promise.all(images.map(async ({ name, file }) => {
208
+ const bytes = await readFile(join(dir, file));
209
+ const content = contentHash(bytes);
210
+ const reused = old[name]?.content === content ? old[name] : byContent.get(content);
211
+ if (reused) {
212
+ next.images[name] = {
213
+ ...reused,
214
+ file
215
+ };
216
+ if (reused.file !== file) updated.push(name);
217
+ } else {
218
+ next.images[name] = await analyzeImage(file, bytes);
219
+ updated.push(name);
220
+ }
221
+ }));
222
+ next.images = Object.fromEntries(Object.entries(next.images).sort(([a], [b]) => a.localeCompare(b)));
223
+ const removed = Object.keys(old).filter((name) => !(name in next.images));
224
+ return {
225
+ manifest: next,
226
+ updated: updated.sort(),
227
+ removed,
228
+ invalid
229
+ };
230
+ }
231
+ async function readManifest(dir) {
232
+ try {
233
+ const parsed = JSON.parse(await readFile(join(dir, MANIFEST_FILE), "utf8"));
234
+ return parsed.version === 1 ? parsed : void 0;
235
+ } catch {
236
+ return;
237
+ }
238
+ }
239
+ function serializeManifest(manifest) {
240
+ return `${JSON.stringify(manifest, null, 2).replace(/\[\s+(\d+),\s+(\d+)\s+\]/g, "[$1, $2]")}\n`;
241
+ }
242
+ async function writeIfChanged(path, content) {
243
+ if (await readFile(path, "utf8").catch(() => void 0) === content) return false;
244
+ await writeFile(path, content);
245
+ return true;
246
+ }
247
+ // src/transform.ts
248
+ /**
249
+ * Encoder settings per quality level. AVIF reaches the same visual quality at lower numbers
250
+ * than WebP, so each format gets its own scale.
251
+ */
252
+ const ENCODER_QUALITY = {
253
+ avif: {
254
+ low: 40,
255
+ standard: 55,
256
+ high: 70
257
+ },
258
+ webp: {
259
+ low: 55,
260
+ standard: 75,
261
+ high: 88
262
+ }
263
+ };
264
+ /**
265
+ * Produces one variant from an original. Shared by the dev server and the optimizer, so local
266
+ * output matches production. Metadata (EXIF, GPS, XMP) is never copied to the output.
267
+ */
268
+ async function transformImage(original, variant, focal) {
269
+ const image = sharp(original).autoOrient();
270
+ const { autoOrient } = await sharp(original).metadata();
271
+ const size = outputSize(variant, autoOrient);
272
+ if (variant.ratio) image.extract(cropRegion(autoOrient, variant.ratio, focal));
273
+ image.resize(size.width, size.height, { fit: "fill" });
274
+ const quality = ENCODER_QUALITY[variant.format][variant.quality];
275
+ return variant.format === "avif" ? image.avif({
276
+ quality,
277
+ effort: 4
278
+ }).toBuffer() : image.webp({ quality }).toBuffer();
279
+ }
280
+ // src/vite.ts
281
+ const PACKAGE_NAME = "@jayalfredprufrock/ansel";
282
+ const VIRTUAL_ALL = "virtual:ansel";
283
+ const RESOLVED_ALL = `\0${VIRTUAL_ALL}`;
284
+ const QUERY = "?ansel";
285
+ const RESOLVED_ONE = "\0ansel:";
286
+ const POOR_NAME_PROBLEM = "the name doesn't say what the image shows; rename it in lowercase letters, digits and dashes, e.g. \"team/dr-patel.jpg\"";
287
+ /**
288
+ * Keeps the image manifest and types up to date, provides image data to `<Img>`, and serves
289
+ * `/_img/*` locally in dev with the same output as the optimizer.
290
+ */
291
+ function ansel(options = {}) {
292
+ const mode = options.manifest ?? (process.env.CI ? "check" : "write");
293
+ let config;
294
+ let dir;
295
+ let syncing;
296
+ let entriesVersion = 0;
297
+ const isBuild = () => config.command === "build";
298
+ const rel = (path) => relative(config.root, path);
299
+ async function sync() {
300
+ const problems = [];
301
+ const result = await syncManifest(dir, await readManifest(dir));
302
+ const { manifest } = result;
303
+ for (const { file, reason, suggestion } of result.invalid) {
304
+ const poor = options.rejectPoorNames && suggestion !== void 0 && isPoorName(suggestion);
305
+ problems.push(`${file}: ${poor ? POOR_NAME_PROBLEM : reason}`);
306
+ }
307
+ const entries = await loadEntries();
308
+ const manifestPath = join(dir, MANIFEST_FILE);
309
+ const typesPath = join(dir, TYPES_FILE);
310
+ const manifestText = serializeManifest(manifest);
311
+ const typesText = generateTypes(manifest, entries !== void 0);
312
+ if (mode === "write") {
313
+ const wrote = await writeIfChanged(manifestPath, manifestText);
314
+ await writeIfChanged(typesPath, typesText);
315
+ const changes = [...result.updated.map((n) => `+ ${n}`), ...result.removed.map((n) => `- ${n}`)];
316
+ if (wrote && changes.length) config.logger.info(`ansel: updated ${MANIFEST_FILE}\n ${changes.join("\n ")}`);
317
+ } else if (await readText(manifestPath) !== manifestText || await readText(typesPath) !== typesText) {
318
+ const changed = [...result.updated, ...result.removed];
319
+ problems.push(`${rel(manifestPath)} is out of date${changed.length ? ` (${changed.join(", ")})` : ""}. Run the dev server or a local build, then commit ${MANIFEST_FILE} and ${TYPES_FILE}.`);
320
+ }
321
+ const images = {};
322
+ for (const [name, entry] of Object.entries(entries ?? {})) {
323
+ const data = manifest.images[name];
324
+ if (!data) problems.push(`${ENTRIES_FILE}: "${name}" has no image file in ${rel(dir)}`);
325
+ else if (entry.decorative !== true && !entry.alt?.trim()) problems.push(`${ENTRIES_FILE}: "${name}" needs alt text, or \`decorative: true\``);
326
+ else images[name] = toImage(name, data, entry);
327
+ }
328
+ for (const [name, data] of Object.entries(manifest.images)) {
329
+ problems.push(...checkImage(name, data));
330
+ if (!entries?.[name] && !isBuild()) {
331
+ const hint = data.embedded.alt ? ` (embedded description: "${data.embedded.alt}")` : "";
332
+ config.logger.warn(`ansel: ${data.file} isn't in ${ENTRIES_FILE}, so it can't be used yet${hint}`);
333
+ }
334
+ }
335
+ if (problems.length && !isBuild()) config.logger.warn(`ansel:\n ${problems.join("\n ")}`);
336
+ return {
337
+ problems,
338
+ manifest,
339
+ images,
340
+ byFile: new Map(Object.keys(images).map((name) => [join(dir, manifest.images[name].file), name])),
341
+ byHash: new Map(Object.values(images).map((image) => [image.hash, image.name]))
342
+ };
343
+ }
344
+ function checkImage(name, data) {
345
+ const problems = [];
346
+ if (options.rejectPoorNames && isPoorName(name)) problems.push(`${data.file}: ${POOR_NAME_PROBLEM}`);
347
+ if (options.rejectGps && data.gps) problems.push(`${data.file}: contains GPS location data; strip it before adding the image`);
348
+ if (options.maxFileSize && data.bytes > options.maxFileSize) problems.push(`${data.file}: ${formatBytes(data.bytes)} is over the ${formatBytes(options.maxFileSize)} limit`);
349
+ if (options.maxPixels && data.width * data.height > options.maxPixels) problems.push(`${data.file}: ${data.width}×${data.height} is over the ${options.maxPixels.toLocaleString("en")} pixel limit`);
350
+ return problems;
351
+ }
352
+ /** Loads `images.ts` with Node's type stripping. `undefined` if there is none (check mode). */
353
+ async function loadEntries() {
354
+ const file = join(dir, ENTRIES_FILE);
355
+ if (await readText(file) === void 0) {
356
+ if (mode !== "write") return void 0;
357
+ await mkdir(dir, { recursive: true });
358
+ await writeFile(file, STARTER_ENTRIES);
359
+ config.logger.info(`ansel: created ${rel(file)}`);
360
+ }
361
+ return (await nativeImport(`${pathToFileURL(file).href}?v=${entriesVersion}`)).default ?? {};
362
+ }
363
+ function current() {
364
+ syncing ??= sync();
365
+ return syncing;
366
+ }
367
+ function refresh(server) {
368
+ const before = syncing;
369
+ syncing = void 0;
370
+ Promise.all([before, current()]).then(([old, next]) => {
371
+ const ids = /* @__PURE__ */ new Set([RESOLVED_ALL]);
372
+ for (const state of [old, next]) for (const file of state?.byFile.keys() ?? []) ids.add(RESOLVED_ONE + file);
373
+ for (const environment of Object.values(server.environments)) for (const id of ids) {
374
+ const module = environment.moduleGraph.getModuleById(id);
375
+ if (module) environment.moduleGraph.invalidateModule(module);
376
+ }
377
+ server.ws.send({ type: "full-reload" });
378
+ }, (error) => config.logger.error(String(error)));
379
+ }
380
+ /** Transforms with a disk cache next to Vite's own, keyed by URL. */
381
+ async function cachedTransform(state, image, variant) {
382
+ const cacheDir = join(config.cacheDir, "ansel");
383
+ const key = `${variant.hash}-w${variant.width}-${variant.ratio?.replace(":", "x") ?? "o"}-${variant.quality}.${variant.format}`;
384
+ const cached = await readFile(join(cacheDir, key)).catch(() => void 0);
385
+ if (cached) return cached;
386
+ const output = await transformImage(await readFile(join(dir, state.manifest.images[image.name].file)), variant, image.focal);
387
+ await mkdir(cacheDir, { recursive: true });
388
+ await writeFile(join(cacheDir, key), output);
389
+ return output;
390
+ }
391
+ return {
392
+ name: "ansel",
393
+ enforce: "pre",
394
+ configResolved(resolved) {
395
+ config = resolved;
396
+ dir = resolve(config.root, options.dir ?? "src/images");
397
+ },
398
+ async buildStart() {
399
+ const { problems } = await current();
400
+ if (isBuild() && problems.length) this.error(`ansel:\n ${problems.join("\n ")}`);
401
+ },
402
+ resolveId(id, importer) {
403
+ if (id === VIRTUAL_ALL) return RESOLVED_ALL;
404
+ if (!id.endsWith(QUERY)) return void 0;
405
+ const path = id.slice(0, -6);
406
+ return RESOLVED_ONE + resolve(importer ? join(importer, "..") : config.root, path);
407
+ },
408
+ async load(id) {
409
+ if (id === RESOLVED_ALL) return `export const images = ${JSON.stringify((await current()).images)};`;
410
+ if (!id.startsWith(RESOLVED_ONE)) return void 0;
411
+ const file = id.slice(7);
412
+ const state = await current();
413
+ const name = state.byFile.get(file);
414
+ if (!name) throw new Error(`ansel: ${rel(file)} isn't a usable image: it must be in ${rel(dir)} and listed in ${ENTRIES_FILE}`);
415
+ return `export default ${JSON.stringify(state.images[name])};`;
416
+ },
417
+ configureServer(server) {
418
+ server.watcher.add(dir);
419
+ const onChange = (file) => {
420
+ if (!file.startsWith(dir)) return;
421
+ if (file.endsWith("manifest.json") || file.endsWith("types.d.ts")) return;
422
+ if (file.endsWith("images.ts")) entriesVersion++;
423
+ refresh(server);
424
+ };
425
+ server.watcher.on("add", onChange);
426
+ server.watcher.on("change", onChange);
427
+ server.watcher.on("unlink", onChange);
428
+ server.middlewares.use((req, res, next) => {
429
+ if (!req.url?.startsWith("/_img/")) return next();
430
+ (async () => {
431
+ const variant = parseImageUrl(req.url ?? "");
432
+ const state = await current();
433
+ const name = variant && state.byHash.get(variant.hash);
434
+ const image = name ? state.images[name] : void 0;
435
+ if (!variant || !image || image.slug !== variant.name) {
436
+ res.statusCode = 404;
437
+ res.end("Not found");
438
+ return;
439
+ }
440
+ const output = await cachedTransform(state, image, variant);
441
+ res.setHeader("Content-Type", `image/${variant.format}`);
442
+ res.setHeader("Cache-Control", "no-cache");
443
+ res.end(output);
444
+ })().catch(next);
445
+ });
446
+ }
447
+ };
448
+ }
449
+ function toImage(name, data, entry) {
450
+ const focal = entry.focal ?? data.focal;
451
+ return {
452
+ name,
453
+ hash: urlHash(data.content, focal),
454
+ slug: name.split("/").pop() ?? name,
455
+ width: data.width,
456
+ height: data.height,
457
+ focal,
458
+ preview: data.preview,
459
+ color: data.color,
460
+ alpha: data.alpha,
461
+ ...entry.alt !== void 0 && { alt: entry.alt },
462
+ decorative: entry.decorative === true
463
+ };
464
+ }
465
+ function generateTypes(manifest, hasEntries) {
466
+ const files = Object.keys(manifest.images).map((name) => ` ${JSON.stringify(name)}: true;`).join("\n");
467
+ return `// Generated by ansel. Do not edit.
468
+ /// <reference types="${PACKAGE_NAME}/client" />
469
+ ${hasEntries ? `type Entries = (typeof import("./images"))["default"];\n` : ""}
470
+ declare module "${PACKAGE_NAME}" {
471
+ interface ImageFiles {
472
+ ${files}
473
+ }${hasEntries ? "\n interface ImageRegistry extends Entries {}" : ""}
474
+ }
475
+
476
+ export {};
477
+ `;
478
+ }
479
+ const STARTER_ENTRIES = `import { defineImages } from "${PACKAGE_NAME}";
480
+
481
+ // Every image the site uses, with alt text (or \`decorative: true\`).
482
+ export default defineImages({});
483
+ `;
484
+ /**
485
+ * Node's own `import()`. When a Vite config is loaded through Vite's module runner (as Astro
486
+ * does), a plain `import()` here would be routed through that runner instead of Node.
487
+ */
488
+ const nativeImport = new Function("url", "return import(url)");
489
+ const readText = (path) => readFile(path, "utf8").catch(() => void 0);
490
+ const formatBytes = (bytes) => bytes >= 1e6 ? `${(bytes / 1e6).toFixed(1)} MB` : `${Math.round(bytes / 1e3)} kB`;
491
+ export { ansel };
package/package.json CHANGED
@@ -1,6 +1,180 @@
1
1
  {
2
2
  "name": "@jayalfredprufrock/ansel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Responsive images for Vite, Astro and React: a typed image manifest, build-time placeholders, an <Img> component and a shared URL format for an image optimizer",
5
+ "homepage": "https://github.com/jayalfredprufrock/ansel#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/jayalfredprufrock/ansel/issues"
8
+ },
9
+ "license": "MIT",
10
+ "author": "jayalfredprufrock",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/jayalfredprufrock/ansel.git"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src/astro",
18
+ "src/client.d.ts",
19
+ "src/styles.css"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.mts",
26
+ "default": "./dist/index.mjs"
27
+ },
28
+ "./url": {
29
+ "types": "./dist/url.d.mts",
30
+ "default": "./dist/url.mjs"
31
+ },
32
+ "./vite": {
33
+ "types": "./dist/vite.d.mts",
34
+ "default": "./dist/vite.mjs"
35
+ },
36
+ "./react": {
37
+ "types": "./dist/react.d.mts",
38
+ "default": "./dist/react.mjs"
39
+ },
40
+ "./Img.astro": "./src/astro/Img.astro",
41
+ "./client": {
42
+ "types": "./src/client.d.ts"
43
+ },
44
+ "./render": {
45
+ "types": "./dist/render.d.mts",
46
+ "default": "./dist/render.mjs"
47
+ },
48
+ "./styles.css": "./src/styles.css",
49
+ "./package.json": "./package.json"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "dependencies": {
55
+ "sharp": "^0.35.5"
56
+ },
57
+ "devDependencies": {
58
+ "@semantic-release/exec": "^7.1.0",
59
+ "@types/node": "^26.6.6",
60
+ "@types/react": "^19.3.0",
61
+ "conventional-changelog-conventionalcommits": "^9.3.1",
62
+ "react": "^19.3.1",
63
+ "semantic-release": "^25.0.9",
64
+ "typescript": "^6.0.3",
65
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.6.0",
66
+ "vite-plus": "1.6.0"
67
+ },
68
+ "peerDependencies": {
69
+ "astro": "^7.0.0",
70
+ "react": "^19.0.0",
71
+ "vite": ">=8.0.0"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "astro": {
75
+ "optional": true
76
+ },
77
+ "react": {
78
+ "optional": true
79
+ },
80
+ "vite": {
81
+ "optional": true
82
+ }
83
+ },
84
+ "release": {
85
+ "branches": [
86
+ "main"
87
+ ],
88
+ "tagFormat": "v${version}",
89
+ "plugins": [
90
+ [
91
+ "@semantic-release/commit-analyzer",
92
+ {
93
+ "preset": "conventionalcommits",
94
+ "releaseRules": [
95
+ {
96
+ "breaking": true,
97
+ "release": "minor"
98
+ },
99
+ {
100
+ "type": "feat",
101
+ "release": "minor"
102
+ },
103
+ {
104
+ "release": "patch"
105
+ }
106
+ ]
107
+ }
108
+ ],
109
+ [
110
+ "@semantic-release/release-notes-generator",
111
+ {
112
+ "preset": "conventionalcommits",
113
+ "presetConfig": {
114
+ "types": [
115
+ {
116
+ "type": "feat",
117
+ "section": "Features"
118
+ },
119
+ {
120
+ "type": "fix",
121
+ "section": "Bug Fixes"
122
+ },
123
+ {
124
+ "type": "perf",
125
+ "section": "Performance"
126
+ },
127
+ {
128
+ "type": "revert",
129
+ "section": "Reverts"
130
+ },
131
+ {
132
+ "type": "refactor",
133
+ "section": "Refactoring"
134
+ },
135
+ {
136
+ "type": "docs",
137
+ "section": "Docs"
138
+ },
139
+ {
140
+ "type": "style",
141
+ "section": "Other"
142
+ },
143
+ {
144
+ "type": "build",
145
+ "section": "Other"
146
+ },
147
+ {
148
+ "type": "ci",
149
+ "section": "Other"
150
+ },
151
+ {
152
+ "type": "test",
153
+ "section": "Other"
154
+ },
155
+ {
156
+ "type": "chore",
157
+ "section": "Other"
158
+ }
159
+ ]
160
+ }
161
+ }
162
+ ],
163
+ [
164
+ "@semantic-release/exec",
165
+ {
166
+ "prepareCmd": "npm pkg set version=${nextRelease.version}",
167
+ "publishCmd": "pnpm publish --no-git-checks"
168
+ }
169
+ ],
170
+ "@semantic-release/github"
171
+ ]
172
+ },
173
+ "engines": {
174
+ "node": ">=22.18"
175
+ },
176
+ "scripts": {
177
+ "build": "vp pack",
178
+ "ci": "vp check && vp test && vp pack && vp run -r check:astro && vp run -r build"
179
+ }
6
180
  }
@@ -0,0 +1,30 @@
1
+ ---
2
+ import type { ImageName } from "@jayalfredprufrock/ansel";
3
+ import { imgMarkup, type ImgOptions } from "@jayalfredprufrock/ansel/render";
4
+ import { images } from "virtual:ansel";
5
+ import "@jayalfredprufrock/ansel/styles.css";
6
+
7
+ interface Props extends ImgOptions {
8
+ /** An image listed in `images.ts`. */
9
+ name: ImageName;
10
+ /** Class for the wrapper element (the box the image fills). */
11
+ class?: string | undefined;
12
+ }
13
+
14
+ const { name, class: className, ...options } = Astro.props;
15
+ const image = images[name];
16
+ if (!image) throw new Error(`<Img>: no image "${name}" in images.ts`);
17
+ const { placeholder, placeholderSrc, sources, img } = imgMarkup(image, options);
18
+ ---
19
+
20
+ <span class:list={["ansel", className]} data-placeholder={placeholder}>
21
+ {placeholderSrc && (
22
+ <img class="ansel-placeholder" src={placeholderSrc} alt="" aria-hidden="true" />
23
+ )}
24
+ <picture>
25
+ {sources.map((source) => (
26
+ <source {...source} />
27
+ ))}
28
+ <img {...img} />
29
+ </picture>
30
+ </span>
@@ -0,0 +1,9 @@
1
+ // Types for `?ansel` imports. Referenced by the generated `types.d.ts`.
2
+ declare module "*?ansel" {
3
+ const image: import("@jayalfredprufrock/ansel").AnselImage;
4
+ export default image;
5
+ }
6
+
7
+ declare module "virtual:ansel" {
8
+ export const images: Record<string, import("@jayalfredprufrock/ansel").AnselImage>;
9
+ }
package/src/styles.css ADDED
@@ -0,0 +1,34 @@
1
+ /*
2
+ * Styles for <Img>, in `@layer ansel` so unlayered site styles always win. The placeholder sits
3
+ * under the image and is covered once the image loads: no JavaScript, no inline styles.
4
+ */
5
+ @layer ansel {
6
+ .ansel {
7
+ display: block;
8
+ position: relative;
9
+ overflow: hidden;
10
+ }
11
+ .ansel picture {
12
+ display: contents;
13
+ }
14
+ .ansel img {
15
+ display: block;
16
+ inline-size: 100%;
17
+ block-size: auto;
18
+ position: relative;
19
+ }
20
+ .ansel .ansel-placeholder {
21
+ position: absolute;
22
+ inset: 0;
23
+ inline-size: 100%;
24
+ block-size: 100%;
25
+ object-fit: cover;
26
+ }
27
+ .ansel[data-placeholder="blur"] .ansel-placeholder {
28
+ filter: blur(1.5rem);
29
+ scale: 1.15;
30
+ }
31
+ .ansel[data-placeholder="pixelated"] .ansel-placeholder {
32
+ image-rendering: pixelated;
33
+ }
34
+ }