foldkit-media 0.3.1 → 0.4.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.
- package/README.md +65 -4
- package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
- package/dist/asset.d.ts.map +1 -0
- package/dist/asset.js +66 -0
- package/dist/asset.js.map +1 -0
- package/dist/browser/index.d.ts +15 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +69 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
- package/dist/browser/upload.d.ts.map +1 -0
- package/dist/browser/upload.js +87 -0
- package/dist/browser/upload.js.map +1 -0
- package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
- package/dist/cloudflare/index.d.ts.map +1 -0
- package/dist/cloudflare/{index.mjs → index.js} +35 -15
- package/dist/cloudflare/index.js.map +1 -0
- package/dist/describe.d.ts +32 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +30 -0
- package/dist/describe.js.map +1 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
- package/dist/format.js.map +1 -0
- package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
- package/dist/icon.d.ts.map +1 -0
- package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
- package/dist/icon.js.map +1 -0
- package/dist/icons/{index.d.mts → index.d.ts} +2 -2
- package/dist/icons/index.d.ts.map +1 -0
- package/dist/icons/{index.mjs → index.js} +2 -2
- package/dist/icons/index.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/layout.d.ts +60 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +72 -0
- package/dist/layout.js.map +1 -0
- package/dist/limits.d.ts +3 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
- package/dist/limits.js.map +1 -0
- package/dist/picture.d.ts +88 -0
- package/dist/picture.d.ts.map +1 -0
- package/dist/picture.js +113 -0
- package/dist/picture.js.map +1 -0
- package/dist/placeholder.d.ts +16 -0
- package/dist/placeholder.d.ts.map +1 -0
- package/dist/placeholder.js +38 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +93 -0
- package/dist/provider.js.map +1 -0
- package/dist/server/admission.d.ts +31 -0
- package/dist/server/admission.d.ts.map +1 -0
- package/dist/server/admission.js +41 -0
- package/dist/server/admission.js.map +1 -0
- package/dist/server/api.d.ts +14 -0
- package/dist/server/api.d.ts.map +1 -0
- package/dist/server/api.js +21 -0
- package/dist/server/api.js.map +1 -0
- package/dist/server/diagnostics.d.ts +53 -0
- package/dist/server/diagnostics.d.ts.map +1 -0
- package/dist/server/diagnostics.js +50 -0
- package/dist/server/diagnostics.js.map +1 -0
- package/dist/server/errors.d.ts +24 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
- package/dist/server/errors.js.map +1 -0
- package/dist/server/facts.d.ts +36 -0
- package/dist/server/facts.d.ts.map +1 -0
- package/dist/server/facts.js +126 -0
- package/dist/server/facts.js.map +1 -0
- package/dist/server/fetch.d.ts +29 -0
- package/dist/server/fetch.d.ts.map +1 -0
- package/dist/server/fetch.js +32 -0
- package/dist/server/fetch.js.map +1 -0
- package/dist/server/handlers.d.ts +48 -0
- package/dist/server/handlers.d.ts.map +1 -0
- package/dist/server/handlers.js +151 -0
- package/dist/server/handlers.js.map +1 -0
- package/dist/server/headers.d.ts +47 -0
- package/dist/server/headers.d.ts.map +1 -0
- package/dist/server/headers.js +134 -0
- package/dist/server/headers.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/materialize.d.ts +36 -0
- package/dist/server/materialize.d.ts.map +1 -0
- package/dist/server/materialize.js +62 -0
- package/dist/server/materialize.js.map +1 -0
- package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
- package/dist/server/services.d.ts.map +1 -0
- package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
- package/dist/server/services.js.map +1 -0
- package/dist/server/stores.d.ts +27 -0
- package/dist/server/stores.d.ts.map +1 -0
- package/dist/server/stores.js +62 -0
- package/dist/server/stores.js.map +1 -0
- package/dist/server/upload.d.ts +113 -0
- package/dist/server/upload.d.ts.map +1 -0
- package/dist/server/upload.js +185 -0
- package/dist/server/upload.js.map +1 -0
- package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
- package/dist/sharp/index.d.ts.map +1 -0
- package/dist/sharp/{index.mjs → index.js} +11 -9
- package/dist/sharp/index.js.map +1 -0
- package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
- package/dist/unpic/index.d.ts.map +1 -0
- package/dist/unpic/{index.mjs → index.js} +3 -3
- package/dist/unpic/index.js.map +1 -0
- package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
- package/dist/variant.d.ts.map +1 -0
- package/dist/variant.js +75 -0
- package/dist/variant.js.map +1 -0
- package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
- package/dist/vite/icons.d.ts.map +1 -0
- package/dist/vite/{index.mjs → icons.js} +7 -168
- package/dist/vite/icons.js.map +1 -0
- package/dist/vite/images.d.ts +20 -0
- package/dist/vite/images.d.ts.map +1 -0
- package/dist/vite/images.js +167 -0
- package/dist/vite/images.js.map +1 -0
- package/dist/vite/index.d.ts +3 -0
- package/dist/vite/index.js +3 -0
- package/dist/widths.d.ts +22 -0
- package/dist/widths.d.ts.map +1 -0
- package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
- package/dist/widths.js.map +1 -0
- package/package.json +22 -21
- package/dist/asset-BLo8VWmd.d.mts.map +0 -1
- package/dist/browser/index.d.mts.map +0 -1
- package/dist/browser/index.mjs +0 -150
- package/dist/browser/index.mjs.map +0 -1
- package/dist/cloudflare/index.d.mts.map +0 -1
- package/dist/cloudflare/index.mjs.map +0 -1
- package/dist/describe-BOgc0xbR.d.mts +0 -52
- package/dist/describe-BOgc0xbR.d.mts.map +0 -1
- package/dist/describe-C6sWA_8p.mjs +0 -171
- package/dist/describe-C6sWA_8p.mjs.map +0 -1
- package/dist/errors-BhEgXJ4m.mjs.map +0 -1
- package/dist/format-BCRTFU9j.mjs.map +0 -1
- package/dist/icon-0A2dBtqj.mjs.map +0 -1
- package/dist/icon-BGtxExTN.d.mts.map +0 -1
- package/dist/icons/index.d.mts.map +0 -1
- package/dist/icons/index.mjs.map +0 -1
- package/dist/index.d.mts +0 -157
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -322
- package/dist/index.mjs.map +0 -1
- package/dist/limits-B4hHpyfE.mjs.map +0 -1
- package/dist/provider-CB0nqu0m.d.mts.map +0 -1
- package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
- package/dist/server/index.d.mts +0 -170
- package/dist/server/index.d.mts.map +0 -1
- package/dist/server/index.mjs +0 -231
- package/dist/server/index.mjs.map +0 -1
- package/dist/services-7B4hsQM7.mjs.map +0 -1
- package/dist/services-BZoK2VOY.d.mts.map +0 -1
- package/dist/sharp/index.d.mts.map +0 -1
- package/dist/sharp/index.mjs.map +0 -1
- package/dist/stores-CxraN3kt.mjs +0 -490
- package/dist/stores-CxraN3kt.mjs.map +0 -1
- package/dist/unpic/index.d.mts.map +0 -1
- package/dist/unpic/index.mjs.map +0 -1
- package/dist/upload-lVLMRJoC.d.mts +0 -160
- package/dist/upload-lVLMRJoC.d.mts.map +0 -1
- package/dist/variant-B-vyMmFB.d.mts.map +0 -1
- package/dist/vite/index.d.mts.map +0 -1
- package/dist/vite/index.mjs.map +0 -1
- package/dist/widths-qp3jshiF.mjs.map +0 -1
- package/dist/widths-upkgLdek.d.mts +0 -36
- package/dist/widths-upkgLdek.d.mts.map +0 -1
|
@@ -1,30 +1,28 @@
|
|
|
1
|
-
import { i as Format, t as Widths } from "./widths-upkgLdek.mjs";
|
|
2
1
|
import { Option, Schema } from "effect";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}
|
|
2
|
+
import { Format } from "./format.js";
|
|
3
|
+
import * as Widths$1 from "./widths.js";
|
|
6
4
|
/**
|
|
7
5
|
* Where a hosted variant lives: the original's content hash, then the variant.
|
|
8
6
|
* The server routes this path and `Provider.hosted` fills it in, so the two
|
|
9
7
|
* read one string. It ends in the format's extension, so a variant written
|
|
10
8
|
* out as a file is served with its type by any static host.
|
|
11
9
|
*/
|
|
12
|
-
declare const PATH = "/_image/:hash/:variant";
|
|
10
|
+
export declare const PATH = "/_image/:hash/:variant";
|
|
13
11
|
/** An original's SHA-256, in lowercase hex: its name in the store. */
|
|
14
|
-
declare const ContentHash: Schema.String;
|
|
12
|
+
export declare const ContentHash: Schema.String;
|
|
15
13
|
/** A quality from 1 to 100. */
|
|
16
|
-
declare const Quality: Schema.Int;
|
|
14
|
+
export declare const Quality: Schema.Int;
|
|
17
15
|
/**
|
|
18
16
|
* The grammar every release reads, whatever its space: a spelling it matches
|
|
19
17
|
* may be one another release offers, so refusing it says nothing for good.
|
|
20
18
|
*/
|
|
21
|
-
declare const Spelling: Schema.String;
|
|
19
|
+
export declare const Spelling: Schema.String;
|
|
22
20
|
/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */
|
|
23
|
-
declare const revisionOf: (spelling: string) => number;
|
|
21
|
+
export declare const revisionOf: (spelling: string) => number;
|
|
24
22
|
/** `spelling` at `revision`: the same variant, as that revision writes it. */
|
|
25
|
-
declare const respell: (spelling: string, revision: number) => string;
|
|
23
|
+
export declare const respell: (spelling: string, revision: number) => string;
|
|
26
24
|
/** A variant as its server reads it. */
|
|
27
|
-
interface Variant {
|
|
25
|
+
export interface Variant {
|
|
28
26
|
readonly width: number;
|
|
29
27
|
readonly format: Format;
|
|
30
28
|
/** None: the encoder's own default. */
|
|
@@ -36,8 +34,8 @@ interface Variant {
|
|
|
36
34
|
* request outside it is refused before any work, so an original has at most
|
|
37
35
|
* `size` variants, whoever asks.
|
|
38
36
|
*/
|
|
39
|
-
interface Space {
|
|
40
|
-
readonly widths: Widths;
|
|
37
|
+
export interface Space {
|
|
38
|
+
readonly widths: Widths$1.Widths;
|
|
41
39
|
readonly formats: ReadonlyArray<Format>;
|
|
42
40
|
/** Qualities a URL may name; empty, no URL names one. */
|
|
43
41
|
readonly qualities: ReadonlyArray<number>;
|
|
@@ -56,13 +54,12 @@ interface Space {
|
|
|
56
54
|
* A space from its ladders. Refuses no formats, a repeated format or
|
|
57
55
|
* quality, and a quality outside 1 to 100.
|
|
58
56
|
*/
|
|
59
|
-
declare const space: (options?: {
|
|
60
|
-
readonly widths?: Widths;
|
|
57
|
+
export declare const space: (options?: {
|
|
58
|
+
readonly widths?: Widths$1.Widths;
|
|
61
59
|
readonly formats?: ReadonlyArray<Format>;
|
|
62
60
|
readonly qualities?: ReadonlyArray<number>;
|
|
63
61
|
readonly revision?: number;
|
|
64
62
|
}) => Space;
|
|
65
63
|
/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */
|
|
66
|
-
declare const standard: Space;
|
|
67
|
-
|
|
68
|
-
//# sourceMappingURL=variant-B-vyMmFB.d.mts.map
|
|
64
|
+
export declare const standard: Space;
|
|
65
|
+
//# sourceMappingURL=variant.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variant.d.ts","names":["Widths"],"sources":["../src/variant.ts"],"mappings":";;;;;;;;;qBAUa;;qBAGA,aAAW,OAAA;;qBAGX,SAAO,OAAA;;;;;qBAUP,UAAQ,OAAA;;qBAGR,aAAU;;qBAGV,UAAO,kBAAoB;;iBAIvB;WACN;WACA,QAAQ;;WAER,SAAS,OAAO;;;;;;;;iBASV;WACN,QAAQA,SAAO;WACf,SAAS,cAAc;;WAEvB,WAAW;;;;;;WAMX;;WAEA,QAAQ,OAAO,MAAM;;WAErB;;;;;;qBAYE,QAAK;WAEL,SAASA,SAAO;WAChB,UAAU,cAAc;WACxB,YAAY;WACZ;MAEV;;qBA2DU,UAAU"}
|
package/dist/variant.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { Option, Schema, SchemaGetter } from "effect";
|
|
2
|
+
import "./format.js";
|
|
3
|
+
import * as Widths$1 from "./widths.js";
|
|
4
|
+
// src/variant.ts
|
|
5
|
+
/**
|
|
6
|
+
* Where a hosted variant lives: the original's content hash, then the variant.
|
|
7
|
+
* The server routes this path and `Provider.hosted` fills it in, so the two
|
|
8
|
+
* read one string. It ends in the format's extension, so a variant written
|
|
9
|
+
* out as a file is served with its type by any static host.
|
|
10
|
+
*/
|
|
11
|
+
const PATH = "/_image/:hash/:variant";
|
|
12
|
+
/** An original's SHA-256, in lowercase hex: its name in the store. */
|
|
13
|
+
const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/));
|
|
14
|
+
/** A quality from 1 to 100. */
|
|
15
|
+
const Quality = Schema.Int.check(Schema.isBetween({
|
|
16
|
+
minimum: 1,
|
|
17
|
+
maximum: 100
|
|
18
|
+
}));
|
|
19
|
+
const SPELLING = /^w([1-9]\d{0,4})(?:q([1-9]\d?|100))?(?:\.r([1-9]\d{0,3}))?\.(avif|webp|jpeg|png)$/;
|
|
20
|
+
/**
|
|
21
|
+
* The grammar every release reads, whatever its space: a spelling it matches
|
|
22
|
+
* may be one another release offers, so refusing it says nothing for good.
|
|
23
|
+
*/
|
|
24
|
+
const Spelling = Schema.String.check(Schema.isPattern(SPELLING));
|
|
25
|
+
/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */
|
|
26
|
+
const revisionOf = (spelling) => Number(SPELLING.exec(spelling)?.[3] ?? 0);
|
|
27
|
+
/** `spelling` at `revision`: the same variant, as that revision writes it. */
|
|
28
|
+
const respell = (spelling, revision) => spelling.replace(/(?:\.r\d+)?(\.[a-z]+)$/, revision === 0 ? "$1" : `.r${revision}$1`);
|
|
29
|
+
const distinct = (label, values) => {
|
|
30
|
+
if (new Set(values).size !== values.length) throw new Error(`Variant.space: a ${label} appears twice`);
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* A space from its ladders. Refuses no formats, a repeated format or
|
|
34
|
+
* quality, and a quality outside 1 to 100.
|
|
35
|
+
*/
|
|
36
|
+
const space = (options = {}) => {
|
|
37
|
+
const { widths = Widths$1.standard, formats = ["avif", "webp"], qualities = [], revision = 0 } = options;
|
|
38
|
+
if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`);
|
|
39
|
+
const unspellableWidth = widths.values.find((width) => width > 99999);
|
|
40
|
+
if (unspellableWidth !== void 0) throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`);
|
|
41
|
+
if (formats.length === 0) throw new Error("Variant.space: a space needs at least one format");
|
|
42
|
+
distinct("format", formats);
|
|
43
|
+
distinct("quality", qualities);
|
|
44
|
+
for (const quality of qualities) if (!Schema.is(Quality)(quality)) throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`);
|
|
45
|
+
return {
|
|
46
|
+
widths,
|
|
47
|
+
formats,
|
|
48
|
+
qualities,
|
|
49
|
+
revision,
|
|
50
|
+
schema: Spelling.check(Schema.makeFilter((spelling) => revisionOf(spelling) === revision || `not revision ${revision}`)).pipe(Schema.decodeTo(Schema.Struct({
|
|
51
|
+
width: widths.Schema,
|
|
52
|
+
format: Schema.Literals(formats),
|
|
53
|
+
quality: Schema.Option(Schema.Literals(qualities))
|
|
54
|
+
}), {
|
|
55
|
+
decode: SchemaGetter.transform((spelling) => {
|
|
56
|
+
const [, width, quality, , format] = SPELLING.exec(spelling);
|
|
57
|
+
return {
|
|
58
|
+
width: Number(width),
|
|
59
|
+
format,
|
|
60
|
+
quality: Option.map(Option.fromNullishOr(quality), Number)
|
|
61
|
+
};
|
|
62
|
+
}),
|
|
63
|
+
encode: SchemaGetter.transform(({ width, format, quality }) => `w${width}${Option.match(quality, {
|
|
64
|
+
onNone: () => "",
|
|
65
|
+
onSome: (value) => `q${value}`
|
|
66
|
+
})}${revision === 0 ? "" : `.r${revision}`}.${format}`)
|
|
67
|
+
})),
|
|
68
|
+
size: widths.values.length * formats.length * (1 + qualities.length)
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */
|
|
72
|
+
const standard = space();
|
|
73
|
+
export { ContentHash, PATH, Quality, Spelling, respell, revisionOf, space, standard };
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=variant.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variant.js","names":["Widths"],"sources":["../src/variant.ts"],"sourcesContent":["import { Option, Schema, SchemaGetter } from 'effect'\nimport { Format } from './format.js'\nimport * as Widths from './widths.js'\n\n/**\n * Where a hosted variant lives: the original's content hash, then the variant.\n * The server routes this path and `Provider.hosted` fills it in, so the two\n * read one string. It ends in the format's extension, so a variant written\n * out as a file is served with its type by any static host.\n */\nexport const PATH = '/_image/:hash/:variant'\n\n/** An original's SHA-256, in lowercase hex: its name in the store. */\nexport const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/))\n\n/** A quality from 1 to 100. */\nexport const Quality = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n\n// No leading zero anywhere: one request has one spelling, so one cache key. The output's\n// revision is written only above 0, so every URL written before revisions keeps its spelling.\nconst SPELLING = /^w([1-9]\\d{0,4})(?:q([1-9]\\d?|100))?(?:\\.r([1-9]\\d{0,3}))?\\.(avif|webp|jpeg|png)$/\n\n/**\n * The grammar every release reads, whatever its space: a spelling it matches\n * may be one another release offers, so refusing it says nothing for good.\n */\nexport const Spelling = Schema.String.check(Schema.isPattern(SPELLING))\n\n/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */\nexport const revisionOf = (spelling: string): number => Number(SPELLING.exec(spelling)?.[3] ?? 0)\n\n/** `spelling` at `revision`: the same variant, as that revision writes it. */\nexport const respell = (spelling: string, revision: number): string =>\n spelling.replace(/(?:\\.r\\d+)?(\\.[a-z]+)$/, revision === 0 ? '$1' : `.r${revision}$1`)\n\n/** A variant as its server reads it. */\nexport interface Variant {\n readonly width: number\n readonly format: Format\n /** None: the encoder's own default. */\n readonly quality: Option.Option<number>\n}\n\n/**\n * Every variant a server will make: the widths, the formats and the qualities\n * it accepts, and the Schema that reads a variant's spelling against them. A\n * request outside it is refused before any work, so an original has at most\n * `size` variants, whoever asks.\n */\nexport interface Space {\n readonly widths: Widths.Widths\n readonly formats: ReadonlyArray<Format>\n /** Qualities a URL may name; empty, no URL names one. */\n readonly qualities: ReadonlyArray<number>\n /**\n * The generation of what its variants are: raised when the output changes (the encoder's\n * settings, its resizing), so a changed variant has a new URL rather than new bytes behind\n * an old one. 0 writes no revision.\n */\n readonly revision: number\n /** `w640.avif`, `w640q75.webp` or `w640.r1.avif`, decoded to a `Variant` of this space's revision. */\n readonly schema: Schema.Codec<Variant, string>\n /** How many variants one original can have. */\n readonly size: number\n}\n\nconst distinct = <A>(label: string, values: ReadonlyArray<A>) => {\n if (new Set(values).size !== values.length)\n throw new Error(`Variant.space: a ${label} appears twice`)\n}\n\n/**\n * A space from its ladders. Refuses no formats, a repeated format or\n * quality, and a quality outside 1 to 100.\n */\nexport const space = (\n options: {\n readonly widths?: Widths.Widths\n readonly formats?: ReadonlyArray<Format>\n readonly qualities?: ReadonlyArray<number>\n readonly revision?: number\n } = {},\n): Space => {\n const {\n widths = Widths.standard,\n formats = ['avif', 'webp'],\n qualities = [],\n revision = 0,\n } = options\n if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) {\n throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`)\n }\n const unspellableWidth = widths.values.find(width => width > 99_999)\n if (unspellableWidth !== undefined) {\n throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`)\n }\n if (formats.length === 0) throw new Error('Variant.space: a space needs at least one format')\n distinct('format', formats)\n distinct('quality', qualities)\n for (const quality of qualities) {\n if (!Schema.is(Quality)(quality)) {\n throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`)\n }\n }\n const schema = Spelling.check(\n Schema.makeFilter(spelling => revisionOf(spelling) === revision || `not revision ${revision}`),\n ).pipe(\n Schema.decodeTo(\n Schema.Struct({\n width: widths.Schema,\n format: Schema.Literals(formats),\n quality: Schema.Option(Schema.Literals(qualities)),\n }),\n {\n decode: SchemaGetter.transform(spelling => {\n const [, width, quality, , format] = SPELLING.exec(spelling)!\n return {\n width: Number(width),\n // The spelling's pattern admits only formats; the struct checks this space's.\n format: format as Format,\n quality: Option.map(Option.fromNullishOr(quality), Number),\n }\n }),\n encode: SchemaGetter.transform(\n ({ width, format, quality }) =>\n `w${width}${Option.match(quality, { onNone: () => '', onSome: value => `q${value}` })}${revision === 0 ? '' : `.r${revision}`}.${format}`,\n ),\n },\n ),\n )\n return {\n widths,\n formats,\n qualities,\n revision,\n schema,\n size: widths.values.length * formats.length * (1 + qualities.length),\n }\n}\n\n/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */\nexport const standard: Space = space()\n"],"mappings":";;;;;;;;;;AAUA,MAAa,OAAO;;AAGpB,MAAa,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC;;AAGjF,MAAa,UAAU,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAI,CAAC,CAAC;AAItF,MAAM,WAAW;;;;;AAMjB,MAAa,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,QAAQ,CAAC;;AAGtE,MAAa,cAAc,aAA6B,OAAO,SAAS,KAAK,QAAQ,CAAC,GAAG,MAAM,CAAC;;AAGhG,MAAa,WAAW,UAAkB,aACxC,SAAS,QAAQ,0BAA0B,aAAa,IAAI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MAAM;IAC3D;GACF,CAAC;GACD,QAAQ,aAAa,WAClB,EAAE,OAAO,QAAQ,cAChB,IAAI,QAAQ,OAAO,MAAM,SAAS;IAAE,cAAc;IAAI,SAAQ,UAAS,IAAI;GAAQ,CAAC,IAAI,aAAa,IAAI,KAAK,KAAK,WAAW,GAAG,QACrI;EACF,CACF,CAOK;EACL,MAAM,OAAO,OAAO,SAAS,QAAQ,UAAU,IAAI,UAAU;CAC/D;AACF;;AAGA,MAAa,WAAkB,MAAM"}
|
|
@@ -1,21 +1,4 @@
|
|
|
1
|
-
import { i as Format, t as Widths } from "../widths-upkgLdek.mjs";
|
|
2
1
|
import { Plugin } from "vite";
|
|
3
|
-
interface ImagesOptions {
|
|
4
|
-
/** The widths offered, up to each original's own: `Widths.standard` unless given. */
|
|
5
|
-
readonly widths?: Widths | undefined;
|
|
6
|
-
/** Formats offered as `source`s, most preferred first: `['avif']` unless given. */
|
|
7
|
-
readonly sources?: ReadonlyArray<Format> | undefined;
|
|
8
|
-
/** The `img`'s own format: `webp` unless given. */
|
|
9
|
-
readonly fallback?: Format | undefined;
|
|
10
|
-
/** The encoder's quality, 1 to 100; its own default unless given. */
|
|
11
|
-
readonly quality?: number | undefined;
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* The plugin: an import with `?image` becomes the image's facts and a
|
|
15
|
-
* provider over its variants. sharp is read on the first such import, so an
|
|
16
|
-
* application that imports none needs no sharp.
|
|
17
|
-
*/
|
|
18
|
-
export declare const images: (options?: ImagesOptions) => Plugin;
|
|
19
2
|
export interface IconsOptions {
|
|
20
3
|
/** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */
|
|
21
4
|
readonly iconify?: ReadonlyArray<string> | undefined;
|
|
@@ -33,5 +16,4 @@ export declare const exportName: (name: string) => string;
|
|
|
33
16
|
* says why, so only importing that icon fails.
|
|
34
17
|
*/
|
|
35
18
|
export declare const icons: (options?: IconsOptions) => Plugin;
|
|
36
|
-
|
|
37
|
-
//# sourceMappingURL=index.d.mts.map
|
|
19
|
+
//# sourceMappingURL=icons.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icons.d.ts","names":[],"sources":["../../src/vite/icons.ts"],"mappings":";iBAoBiB;;WAEN,UAAU;;WAEV,UAAU,SAAS;;WAEnB;;;qBAWE,aAAU;;;;;;;qBAwDV,QAAK,UAAa,iBAAoB"}
|
|
@@ -1,170 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as ImageAsset, n as describe } from "../describe-C6sWA_8p.mjs";
|
|
3
|
-
import { IconifySet, fromIconify, namesOf, parse } from "../icons/index.mjs";
|
|
4
|
-
import { n as Transformer } from "../services-7B4hsQM7.mjs";
|
|
5
|
-
import { createRequire } from "node:module";
|
|
6
|
-
import { Cause, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from "effect";
|
|
7
|
-
import { availableParallelism } from "node:os";
|
|
1
|
+
import { Schema } from "effect";
|
|
8
2
|
import { readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
// src/vite/
|
|
13
|
-
/**
|
|
14
|
-
* Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,
|
|
15
|
-
* provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.
|
|
16
|
-
* The build reads the file's facts once (`describe`, through sharp), writes a
|
|
17
|
-
* file for each ladder width up to the original's own in each format, and
|
|
18
|
-
* names them by content, so a host may keep them for good. The development
|
|
19
|
-
* server makes the same variants when a page asks for them.
|
|
20
|
-
*/
|
|
21
|
-
const QUERY = "image";
|
|
22
|
-
const CACHE_REVISION = "r2";
|
|
23
|
-
const DEV_PREFIX = "/@foldkit-media/image/";
|
|
24
|
-
const DEV_PATH = /^\/@foldkit-media\/image\/([0-9a-f]{64})\/w(\d+)\.(avif|webp|jpeg|png)$/;
|
|
25
|
-
/** The widths a build writes of an original: the ladder's below its own, then its own. */
|
|
26
|
-
const widthsFor = (ladder, width) => [...ladder.values.filter((value) => value < width), width];
|
|
27
|
-
/**
|
|
28
|
-
* Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build
|
|
29
|
-
* stopped halfway leaves no cut-short file that a later build would trust.
|
|
30
|
-
*/
|
|
31
|
-
const keep = async (file, bytes) => {
|
|
32
|
-
const partial = `${file}.${randomUUID()}.partial`;
|
|
33
|
-
await writeFile(partial, bytes);
|
|
34
|
-
await rename(partial, file);
|
|
35
|
-
};
|
|
36
|
-
const run = async (media, effect, what) => {
|
|
37
|
-
const exit = await media.runPromiseExit(effect);
|
|
38
|
-
if (Exit.isSuccess(exit)) return exit.value;
|
|
39
|
-
throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`);
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* The plugin: an import with `?image` becomes the image's facts and a
|
|
43
|
-
* provider over its variants. sharp is read on the first such import, so an
|
|
44
|
-
* application that imports none needs no sharp.
|
|
45
|
-
*/
|
|
46
|
-
const images = (options = {}) => {
|
|
47
|
-
const ladder = options.widths ?? standard;
|
|
48
|
-
const sources = options.sources ?? ["avif"];
|
|
49
|
-
const fallback = options.fallback ?? "webp";
|
|
50
|
-
const formats = [.../* @__PURE__ */ new Set([...sources, fallback])];
|
|
51
|
-
const quality = Option.fromNullishOr(options.quality);
|
|
52
|
-
if (Option.isSome(quality) && !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)) throw new Error(`foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`);
|
|
53
|
-
let root = process.cwd();
|
|
54
|
-
let cache = join(root, "node_modules", ".vite", "foldkit-media", CACHE_REVISION);
|
|
55
|
-
let serving = false;
|
|
56
|
-
/** The originals the development server has been asked to vary, by content hash. */
|
|
57
|
-
const originals = /* @__PURE__ */ new Map();
|
|
58
|
-
const inspecting = Semaphore.makeUnsafe(availableParallelism());
|
|
59
|
-
let media;
|
|
60
|
-
const mediaOf = () => media ??= import("../sharp/index.mjs").then(({ inspectorSharp, transformerSharp }) => ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())), (cause) => {
|
|
61
|
-
throw new Error(`foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`);
|
|
62
|
-
});
|
|
63
|
-
const factsOf = async (key, bytes, hash) => {
|
|
64
|
-
const file = join(cache, hash, "asset.json");
|
|
65
|
-
try {
|
|
66
|
-
return Schema.decodeUnknownSync(ImageAsset)({
|
|
67
|
-
...JSON.parse(await readFile(file, "utf8")),
|
|
68
|
-
key
|
|
69
|
-
});
|
|
70
|
-
} catch {
|
|
71
|
-
const asset = await run(await mediaOf(), Semaphore.withPermit(inspecting)(describe(key, bytes)), `${key} could not be read`);
|
|
72
|
-
await mkdir(join(cache, hash), { recursive: true });
|
|
73
|
-
await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)));
|
|
74
|
-
return asset;
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
const variantOf = async (key, bytes, hash, width, format) => {
|
|
78
|
-
const name = `w${width}${Option.match(quality, {
|
|
79
|
-
onNone: () => "",
|
|
80
|
-
onSome: (q) => `q${q}`
|
|
81
|
-
})}.${format}`;
|
|
82
|
-
const file = join(cache, hash, name);
|
|
83
|
-
try {
|
|
84
|
-
return new Uint8Array(await readFile(file));
|
|
85
|
-
} catch {
|
|
86
|
-
const variant = {
|
|
87
|
-
width,
|
|
88
|
-
format,
|
|
89
|
-
quality
|
|
90
|
-
};
|
|
91
|
-
const made = await run(await mediaOf(), Transformer.use((transformer) => transformer.transform({
|
|
92
|
-
body: new Blob([bytes]).stream(),
|
|
93
|
-
size: bytes.byteLength
|
|
94
|
-
}, variant)), `${key} could not be made ${width} wide in ${format}`);
|
|
95
|
-
await mkdir(join(cache, hash), { recursive: true });
|
|
96
|
-
await keep(file, made.bytes);
|
|
97
|
-
return made.bytes;
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
return {
|
|
101
|
-
name: "foldkit-media:images",
|
|
102
|
-
enforce: "pre",
|
|
103
|
-
configResolved(config) {
|
|
104
|
-
root = config.root;
|
|
105
|
-
cache = join(config.cacheDir, "foldkit-media", CACHE_REVISION);
|
|
106
|
-
serving = config.command === "serve";
|
|
107
|
-
},
|
|
108
|
-
async load(id) {
|
|
109
|
-
const [file, query] = id.split("?");
|
|
110
|
-
if (query === void 0 || !new URLSearchParams(query).has(QUERY)) return void 0;
|
|
111
|
-
const bytes = new Uint8Array(await readFile(file));
|
|
112
|
-
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
113
|
-
const key = relative(root, file).split(sep).join("/");
|
|
114
|
-
const asset = await factsOf(key, bytes, hash);
|
|
115
|
-
const widths = widthsFor(ladder, asset.width);
|
|
116
|
-
if (serving) originals.set(hash, {
|
|
117
|
-
bytes,
|
|
118
|
-
widths
|
|
119
|
-
});
|
|
120
|
-
const stem = key.split("/").pop().replace(/\.[^.]+$/, "");
|
|
121
|
-
const files = await Promise.all(widths.flatMap((width) => formats.map(async (format) => {
|
|
122
|
-
let url;
|
|
123
|
-
if (serving) url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`);
|
|
124
|
-
else {
|
|
125
|
-
const source = await variantOf(key, bytes, hash, width, format);
|
|
126
|
-
const contentHash = createHash("sha256").update(source).digest("hex");
|
|
127
|
-
url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({
|
|
128
|
-
type: "asset",
|
|
129
|
-
fileName: `${stem}-${width}-${contentHash}.${format}`,
|
|
130
|
-
source
|
|
131
|
-
})}`;
|
|
132
|
-
}
|
|
133
|
-
return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`;
|
|
134
|
-
})));
|
|
135
|
-
return [
|
|
136
|
-
`import { Schema } from 'effect'`,
|
|
137
|
-
`import { HashedAsset, Provider } from 'foldkit-media'`,
|
|
138
|
-
`export default {`,
|
|
139
|
-
` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,
|
|
140
|
-
` provider: Provider.fromFiles([${files.join(", ")}], ${JSON.stringify({
|
|
141
|
-
sources,
|
|
142
|
-
fallback
|
|
143
|
-
})}),`,
|
|
144
|
-
`}`
|
|
145
|
-
].join("\n");
|
|
146
|
-
},
|
|
147
|
-
configureServer(server) {
|
|
148
|
-
server.middlewares.use((request, response, next) => {
|
|
149
|
-
const match = DEV_PATH.exec(request.url?.split("?")[0] ?? "");
|
|
150
|
-
if (match === null) return next();
|
|
151
|
-
const [, hash, width, asked] = match;
|
|
152
|
-
const original = originals.get(hash);
|
|
153
|
-
const format = formats.find((offered) => offered === asked);
|
|
154
|
-
if (original === void 0 || format === void 0 || !original.widths.includes(Number(width))) {
|
|
155
|
-
response.statusCode = 404;
|
|
156
|
-
return response.end();
|
|
157
|
-
}
|
|
158
|
-
variantOf(hash, original.bytes, hash, Number(width), format).then((bytes) => {
|
|
159
|
-
response.setHeader("Content-Type", `image/${format}`);
|
|
160
|
-
response.setHeader("Cache-Control", "no-store");
|
|
161
|
-
response.end(bytes);
|
|
162
|
-
}, next);
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
};
|
|
166
|
-
};
|
|
167
|
-
// src/vite/index.ts
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
5
|
+
import { IconifySet, fromIconify, namesOf, parse } from "../icons/index.js";
|
|
6
|
+
// src/vite/icons.ts
|
|
168
7
|
/**
|
|
169
8
|
* Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`
|
|
170
9
|
* gives the icon's `IconData`, read from an Iconify set or a folder of the
|
|
@@ -334,6 +173,6 @@ const icons = (options = {}) => {
|
|
|
334
173
|
}
|
|
335
174
|
};
|
|
336
175
|
};
|
|
337
|
-
export { exportName, icons
|
|
176
|
+
export { exportName, icons };
|
|
338
177
|
|
|
339
|
-
//# sourceMappingURL=
|
|
178
|
+
//# sourceMappingURL=icons.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icons.js","names":[],"sources":["../../src/vite/icons.ts"],"sourcesContent":["/**\n * Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`\n * gives the icon's `IconData`, read from an Iconify set or a folder of the\n * application's own SVG files when the build reads the import. The import is\n * the selection, and the bundler drops what nothing imports. A declaration\n * file names every icon of every set, so a misspelt name is a type error.\n */\nimport { readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { extname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { Schema } from 'effect'\nimport type { Plugin } from 'vite'\nimport type { IconData } from '../icon.js'\nimport { fromIconify, IconifySet, namesOf, parse } from '../icons/index.js'\n\nconst PREFIX = 'virtual:foldkit-icons/'\n// Rollup's mark for a module no file holds, which other plugins leave alone.\nconst RESOLVED = `${String.fromCharCode(0)}${PREFIX}`\nconst SET_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/\n\nexport interface IconsOptions {\n /** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */\n readonly iconify?: ReadonlyArray<string> | undefined\n /** The application's own sets: a name, and a folder whose SVG files are its icons, each named by its file. */\n readonly folders?: Readonly<Record<string, string>> | undefined\n /** Where the declaration of every set is written, from the root: `foldkit-icons.d.ts` unless given; `false` writes none. */\n readonly dts?: string | false | undefined\n}\n\n/** An icon set ready to be a module: each icon under the name it is imported by. */\ninterface ReadSet {\n readonly icons: ReadonlyArray<readonly [exported: string, icon: IconData]>\n /** The icons of an Iconify set the parser refused, and why: left out, so importing one fails. */\n readonly refused: ReadonlyArray<readonly [name: string, reason: string]>\n}\n\n/** `arrow-left` is `arrowLeft`, and `1-circle` `_1Circle`; JavaScript's reserved words export as they are. */\nexport const exportName = (name: string): string => {\n const camel = name.replace(/[-_:.]+([a-zA-Z0-9])/g, (_, next: string) => next.toUpperCase())\n return /^[0-9]/.test(camel) ? `_${camel}` : camel\n}\n\nconst named = (\n set: string,\n entries: ReadonlyArray<readonly [name: string, icon: IconData]>,\n): ReadSet['icons'] => {\n const seen = new Map<string, string>()\n return entries.map(([name, icon]) => {\n const exported = exportName(name)\n if (!/^[A-Za-z_$][\\w$]*$/.test(exported)) {\n throw new Error(`foldkit-media/vite: the icon \"${set}:${name}\" has no name to import it by.`)\n }\n const earlier = seen.get(exported)\n if (earlier !== undefined) {\n throw new Error(\n `foldkit-media/vite: the icons \"${set}:${earlier}\" and \"${set}:${name}\" would both be imported as ${exported}.`,\n )\n }\n seen.set(exported, name)\n return [exported, icon] as const\n })\n}\n\nconst moduleOf = ({ icons }: ReadSet): string =>\n [\n ...icons.map(([, icon], at) => `const i${at} = ${JSON.stringify(icon)}`),\n `export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n ].join('\\n')\n\nconst declarationOf = (sets: ReadonlyMap<string, ReadSet>): string =>\n [\n '// Written by foldkit-media/vite from the icon sets it is given. Do not edit.',\n ...[...sets].map(([name, { icons, refused }]) =>\n [\n `declare module '${PREFIX}${name}' {`,\n \" import type { IconData } from 'foldkit-media'\",\n ...refused.map(\n ([icon, reason]) => ` // Left out, ${icon}: ${reason.replace(/\\s+/g, ' ')}`,\n ),\n ...icons.map((_, at) => ` const i${at}: IconData`),\n ` export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n '}',\n ].join('\\n'),\n ),\n '',\n ].join('\\n')\n\n/**\n * The plugin: give it the sets the application imports from. An SVG in a\n * folder that the parser refuses fails the build, naming the file; an icon of\n * an Iconify set that it refuses is left out of the set, and its declaration\n * says why, so only importing that icon fails.\n */\nexport const icons = (options: IconsOptions = {}): Plugin => {\n const iconify = options.iconify ?? []\n const folders = Object.entries(options.folders ?? {})\n for (const name of [...iconify, ...folders.map(([name]) => name)]) {\n if (!SET_NAME.test(name)) {\n throw new Error(\n `foldkit-media/vite: \"${name}\" is not a set name (lowercase words and hyphens).`,\n )\n }\n }\n const twice = [...iconify, ...folders.map(([name]) => name)].find(\n (name, at, all) => all.indexOf(name) !== at,\n )\n if (twice !== undefined) throw new Error(`foldkit-media/vite: the set \"${twice}\" is given twice.`)\n\n let root = process.cwd()\n const read = new Map<string, ReadSet>()\n const folderDirs = new Map(folders)\n const folderOf = (name: string) => resolve(root, folderDirs.get(name)!)\n\n const readIconify = (prefix: string): ReadSet => {\n const require = createRequire(join(root, 'package.json'))\n let file: string\n try {\n file = require.resolve(`@iconify-json/${prefix}/icons.json`)\n } catch {\n throw new Error(\n `foldkit-media/vite: the Iconify set \"${prefix}\" is not installed: add @iconify-json/${prefix}.`,\n )\n }\n let set: IconifySet\n try {\n set = Schema.decodeUnknownSync(IconifySet)(JSON.parse(readFileSync(file, 'utf8')))\n } catch (error) {\n throw new Error(\n `foldkit-media/vite: ${file} is not an Iconify set: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const icons: Array<readonly [string, IconData]> = []\n const refused: Array<readonly [string, string]> = []\n // The icon each name draws in the end, through its aliases.\n const drawn = (name: string): string => {\n let current = name\n for (\n let step = 0;\n step < 16 && set.aliases !== undefined && Object.hasOwn(set.aliases, current);\n step++\n )\n current = set.aliases[current]!.parent\n return current\n }\n // Which icon each export name already stands for.\n const exported = new Map<string, string>()\n for (const name of namesOf(set)) {\n // An alias spelt only differently from the icon it names (Lucide's\n // `arrow-down-01` for `arrow-down-0-1`) would be imported by the same\n // name as that icon, and it is that icon: leave the alias out. Two\n // different icons under one name still fail, in `named`.\n const as = exportName(name)\n if (exported.get(as) === drawn(name)) continue\n exported.set(as, drawn(name))\n try {\n icons.push([name, fromIconify(set, name)])\n } catch (error) {\n refused.push([name, error instanceof Error ? error.message : String(error)])\n }\n }\n return { icons: named(prefix, icons), refused }\n }\n\n const readFolder = (name: string): ReadSet => {\n const folder = folderOf(name)\n const files = readdirSync(folder)\n .filter(file => extname(file) === '.svg')\n .sort()\n return {\n icons: named(\n name,\n files.map(file => {\n const path = join(folder, file)\n return [\n file.slice(0, -4),\n parse(readFileSync(path, 'utf8'), relative(root, path)),\n ] as const\n }),\n ),\n refused: [],\n }\n }\n\n const setOf = (name: string): ReadSet => {\n const known = read.get(name)\n if (known !== undefined) return known\n const made = iconify.includes(name) ? readIconify(name) : readFolder(name)\n read.set(name, made)\n return made\n }\n\n const all = () => [...iconify, ...folders.map(([name]) => name)]\n\n const writeDeclaration = () => {\n if (options.dts === false) return\n const path = resolve(root, options.dts ?? 'foldkit-icons.d.ts')\n const text = declarationOf(new Map(all().map(name => [name, setOf(name)])))\n let current: string | undefined\n try {\n current = readFileSync(path, 'utf8')\n } catch {\n current = undefined\n }\n // Written only when it changes, so a watcher on the file does not see a write of every build.\n if (current !== text) writeFileSync(path, text)\n }\n\n return {\n name: 'foldkit-media:icons',\n configResolved(config) {\n root = config.root\n },\n buildStart() {\n read.clear()\n writeDeclaration()\n for (const [name] of folders) this.addWatchFile(folderOf(name))\n },\n resolveId(id) {\n if (!id.startsWith(PREFIX)) return undefined\n const name = id.slice(PREFIX.length)\n if (!all().includes(name)) {\n throw new Error(\n `foldkit-media/vite: there is no icon set \"${name}\"; the sets given are ${all().join(', ') || 'none'}.`,\n )\n }\n return `${RESOLVED}${name}`\n },\n load(id) {\n if (!id.startsWith(RESOLVED)) return undefined\n const name = id.slice(RESOLVED.length)\n if (folders.some(([folder]) => folder === name)) {\n for (const file of readdirSync(folderOf(name)))\n this.addWatchFile(join(folderOf(name), file))\n }\n return moduleOf(setOf(name))\n },\n configureServer(server) {\n const dirs = folders.map(([name]) => [name, folderOf(name)] as const)\n server.watcher.add(dirs.map(([, dir]) => dir))\n server.watcher.on('all', (_, file) => {\n const changed = dirs.find(([, dir]) => {\n const path = relative(dir, file)\n return !isAbsolute(path) && !path.startsWith('..')\n })\n if (changed === undefined || extname(file) !== '.svg') return\n read.delete(changed[0])\n try {\n writeDeclaration()\n } catch (error) {\n // A throw here would end the server; the set's next load fails with it, where the page shows it.\n server.config.logger.error(error instanceof Error ? error.message : String(error))\n }\n for (const environment of Object.values(server.environments)) {\n const module = environment.moduleGraph.getModuleById(`${RESOLVED}${changed[0]}`)\n if (module !== undefined) environment.moduleGraph.invalidateModule(module)\n }\n server.ws.send({ type: 'full-reload' })\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,SAAS;AAEf,MAAM,WAAW,GAAG,OAAO,aAAa,CAAC,IAAI;AAC7C,MAAM,WAAW;;AAmBjB,MAAa,cAAc,SAAyB;CAClD,MAAM,QAAQ,KAAK,QAAQ,0BAA0B,GAAG,SAAiB,KAAK,YAAY,CAAC;CAC3F,OAAO,SAAS,KAAK,KAAK,IAAI,IAAI,UAAU;AAC9C;AAEA,MAAM,SACJ,KACA,YACqB;CACrB,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO,QAAQ,KAAK,CAAC,MAAM,UAAU;EACnC,MAAM,WAAW,WAAW,IAAI;EAChC,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,MAAM,IAAI,MAAM,iCAAiC,IAAI,GAAG,KAAK,+BAA+B;EAE9F,MAAM,UAAU,KAAK,IAAI,QAAQ;EACjC,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MACR,kCAAkC,IAAI,GAAG,QAAQ,SAAS,IAAI,GAAG,KAAK,8BAA8B,SAAS,EAC/G;EAEF,KAAK,IAAI,UAAU,IAAI;EACvB,OAAO,CAAC,UAAU,IAAI;CACxB,CAAC;AACH;AAEA,MAAM,YAAY,EAAE,YAClB,CACE,GAAG,MAAM,KAAK,GAAG,OAAO,OAAO,UAAU,GAAG,KAAK,KAAK,UAAU,IAAI,GAAG,GACvE,YAAY,MAAM,KAAK,CAAC,WAAW,OAAO,IAAI,GAAG,MAAM,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE,GAChF,CAAC,CAAC,KAAK,IAAI;AAEb,MAAM,iBAAiB,SACrB;CACE;CACA,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,K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from "../format.js";
|
|
2
|
+
import * as Widths$1 from "../widths.js";
|
|
3
|
+
import { Plugin } from "vite";
|
|
4
|
+
export interface ImagesOptions {
|
|
5
|
+
/** The widths offered, up to each original's own: `Widths.standard` unless given. */
|
|
6
|
+
readonly widths?: Widths$1.Widths | undefined;
|
|
7
|
+
/** Formats offered as `source`s, most preferred first: `['avif']` unless given. */
|
|
8
|
+
readonly sources?: ReadonlyArray<Format> | undefined;
|
|
9
|
+
/** The `img`'s own format: `webp` unless given. */
|
|
10
|
+
readonly fallback?: Format | undefined;
|
|
11
|
+
/** The encoder's quality, 1 to 100; its own default unless given. */
|
|
12
|
+
readonly quality?: number | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The plugin: an import with `?image` becomes the image's facts and a
|
|
16
|
+
* provider over its variants. sharp is read on the first such import, so an
|
|
17
|
+
* application that imports none needs no sharp.
|
|
18
|
+
*/
|
|
19
|
+
export declare const images: (options?: ImagesOptions) => Plugin;
|
|
20
|
+
//# sourceMappingURL=images.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.d.ts","names":["Widths"],"sources":["../../src/vite/images.ts"],"mappings":";;;iBA8BiB;;WAEN,SAASA,SAAO;;WAEhB,UAAU,cAAc;;WAExB,WAAW;;WAEX;;;;;;;qBAoCE,SAAM,UAAa,kBAAqB"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { Cause, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from "effect";
|
|
2
|
+
import { ImageAsset } from "../asset.js";
|
|
3
|
+
import { describe } from "../describe.js";
|
|
4
|
+
import * as Widths$1 from "../widths.js";
|
|
5
|
+
import { Transformer } from "../server/services.js";
|
|
6
|
+
import { availableParallelism } from "node:os";
|
|
7
|
+
import { join, relative, sep } from "node:path";
|
|
8
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
10
|
+
// src/vite/images.ts
|
|
11
|
+
/**
|
|
12
|
+
* Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,
|
|
13
|
+
* provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.
|
|
14
|
+
* The build reads the file's facts once (`describe`, through sharp), writes a
|
|
15
|
+
* file for each ladder width up to the original's own in each format, and
|
|
16
|
+
* names them by content, so a host may keep them for good. The development
|
|
17
|
+
* server makes the same variants when a page asks for them.
|
|
18
|
+
*/
|
|
19
|
+
const QUERY = "image";
|
|
20
|
+
const CACHE_REVISION = "r2";
|
|
21
|
+
const DEV_PREFIX = "/@foldkit-media/image/";
|
|
22
|
+
const DEV_PATH = /^\/@foldkit-media\/image\/([0-9a-f]{64})\/w(\d+)\.(avif|webp|jpeg|png)$/;
|
|
23
|
+
/** The widths a build writes of an original: the ladder's below its own, then its own. */
|
|
24
|
+
const widthsFor = (ladder, width) => [...ladder.values.filter((value) => value < width), width];
|
|
25
|
+
/**
|
|
26
|
+
* Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build
|
|
27
|
+
* stopped halfway leaves no cut-short file that a later build would trust.
|
|
28
|
+
*/
|
|
29
|
+
const keep = async (file, bytes) => {
|
|
30
|
+
const partial = `${file}.${randomUUID()}.partial`;
|
|
31
|
+
await writeFile(partial, bytes);
|
|
32
|
+
await rename(partial, file);
|
|
33
|
+
};
|
|
34
|
+
const run = async (media, effect, what) => {
|
|
35
|
+
const exit = await media.runPromiseExit(effect);
|
|
36
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
37
|
+
throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`);
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The plugin: an import with `?image` becomes the image's facts and a
|
|
41
|
+
* provider over its variants. sharp is read on the first such import, so an
|
|
42
|
+
* application that imports none needs no sharp.
|
|
43
|
+
*/
|
|
44
|
+
const images = (options = {}) => {
|
|
45
|
+
const ladder = options.widths ?? Widths$1.standard;
|
|
46
|
+
const sources = options.sources ?? ["avif"];
|
|
47
|
+
const fallback = options.fallback ?? "webp";
|
|
48
|
+
const formats = [.../* @__PURE__ */ new Set([...sources, fallback])];
|
|
49
|
+
const quality = Option.fromNullishOr(options.quality);
|
|
50
|
+
if (Option.isSome(quality) && !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)) throw new Error(`foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`);
|
|
51
|
+
let root = process.cwd();
|
|
52
|
+
let cache = join(root, "node_modules", ".vite", "foldkit-media", CACHE_REVISION);
|
|
53
|
+
let serving = false;
|
|
54
|
+
/** The originals the development server has been asked to vary, by content hash. */
|
|
55
|
+
const originals = /* @__PURE__ */ new Map();
|
|
56
|
+
const inspecting = Semaphore.makeUnsafe(availableParallelism());
|
|
57
|
+
let media;
|
|
58
|
+
const mediaOf = () => media ??= import("../sharp/index.js").then(({ inspectorSharp, transformerSharp }) => ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())), (cause) => {
|
|
59
|
+
throw new Error(`foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`);
|
|
60
|
+
});
|
|
61
|
+
const factsOf = async (key, bytes, hash) => {
|
|
62
|
+
const file = join(cache, hash, "asset.json");
|
|
63
|
+
try {
|
|
64
|
+
return Schema.decodeUnknownSync(ImageAsset)({
|
|
65
|
+
...JSON.parse(await readFile(file, "utf8")),
|
|
66
|
+
key
|
|
67
|
+
});
|
|
68
|
+
} catch {
|
|
69
|
+
const asset = await run(await mediaOf(), Semaphore.withPermit(inspecting)(describe(key, bytes)), `${key} could not be read`);
|
|
70
|
+
await mkdir(join(cache, hash), { recursive: true });
|
|
71
|
+
await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)));
|
|
72
|
+
return asset;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const variantOf = async (key, bytes, hash, width, format) => {
|
|
76
|
+
const name = `w${width}${Option.match(quality, {
|
|
77
|
+
onNone: () => "",
|
|
78
|
+
onSome: (q) => `q${q}`
|
|
79
|
+
})}.${format}`;
|
|
80
|
+
const file = join(cache, hash, name);
|
|
81
|
+
try {
|
|
82
|
+
return new Uint8Array(await readFile(file));
|
|
83
|
+
} catch {
|
|
84
|
+
const variant = {
|
|
85
|
+
width,
|
|
86
|
+
format,
|
|
87
|
+
quality
|
|
88
|
+
};
|
|
89
|
+
const made = await run(await mediaOf(), Transformer.use((transformer) => transformer.transform({
|
|
90
|
+
body: new Blob([bytes]).stream(),
|
|
91
|
+
size: bytes.byteLength
|
|
92
|
+
}, variant)), `${key} could not be made ${width} wide in ${format}`);
|
|
93
|
+
await mkdir(join(cache, hash), { recursive: true });
|
|
94
|
+
await keep(file, made.bytes);
|
|
95
|
+
return made.bytes;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
name: "foldkit-media:images",
|
|
100
|
+
enforce: "pre",
|
|
101
|
+
configResolved(config) {
|
|
102
|
+
root = config.root;
|
|
103
|
+
cache = join(config.cacheDir, "foldkit-media", CACHE_REVISION);
|
|
104
|
+
serving = config.command === "serve";
|
|
105
|
+
},
|
|
106
|
+
async load(id) {
|
|
107
|
+
const [file, query] = id.split("?");
|
|
108
|
+
if (query === void 0 || !new URLSearchParams(query).has(QUERY)) return void 0;
|
|
109
|
+
const bytes = new Uint8Array(await readFile(file));
|
|
110
|
+
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
111
|
+
const key = relative(root, file).split(sep).join("/");
|
|
112
|
+
const asset = await factsOf(key, bytes, hash);
|
|
113
|
+
const widths = widthsFor(ladder, asset.width);
|
|
114
|
+
if (serving) originals.set(hash, {
|
|
115
|
+
bytes,
|
|
116
|
+
widths
|
|
117
|
+
});
|
|
118
|
+
const stem = key.split("/").pop().replace(/\.[^.]+$/, "");
|
|
119
|
+
const files = await Promise.all(widths.flatMap((width) => formats.map(async (format) => {
|
|
120
|
+
let url;
|
|
121
|
+
if (serving) url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`);
|
|
122
|
+
else {
|
|
123
|
+
const source = await variantOf(key, bytes, hash, width, format);
|
|
124
|
+
const contentHash = createHash("sha256").update(source).digest("hex");
|
|
125
|
+
url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({
|
|
126
|
+
type: "asset",
|
|
127
|
+
fileName: `${stem}-${width}-${contentHash}.${format}`,
|
|
128
|
+
source
|
|
129
|
+
})}`;
|
|
130
|
+
}
|
|
131
|
+
return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`;
|
|
132
|
+
})));
|
|
133
|
+
return [
|
|
134
|
+
`import { Schema } from 'effect'`,
|
|
135
|
+
`import { HashedAsset, Provider } from 'foldkit-media'`,
|
|
136
|
+
`export default {`,
|
|
137
|
+
` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,
|
|
138
|
+
` provider: Provider.fromFiles([${files.join(", ")}], ${JSON.stringify({
|
|
139
|
+
sources,
|
|
140
|
+
fallback
|
|
141
|
+
})}),`,
|
|
142
|
+
`}`
|
|
143
|
+
].join("\n");
|
|
144
|
+
},
|
|
145
|
+
configureServer(server) {
|
|
146
|
+
server.middlewares.use((request, response, next) => {
|
|
147
|
+
const match = DEV_PATH.exec(request.url?.split("?")[0] ?? "");
|
|
148
|
+
if (match === null) return next();
|
|
149
|
+
const [, hash, width, asked] = match;
|
|
150
|
+
const original = originals.get(hash);
|
|
151
|
+
const format = formats.find((offered) => offered === asked);
|
|
152
|
+
if (original === void 0 || format === void 0 || !original.widths.includes(Number(width))) {
|
|
153
|
+
response.statusCode = 404;
|
|
154
|
+
return response.end();
|
|
155
|
+
}
|
|
156
|
+
variantOf(hash, original.bytes, hash, Number(width), format).then((bytes) => {
|
|
157
|
+
response.setHeader("Content-Type", `image/${format}`);
|
|
158
|
+
response.setHeader("Cache-Control", "no-store");
|
|
159
|
+
response.end(bytes);
|
|
160
|
+
}, next);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
export { images };
|
|
166
|
+
|
|
167
|
+
//# sourceMappingURL=images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"images.js","names":["Widths"],"sources":["../../src/vite/images.ts"],"sourcesContent":["/**\n * Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,\n * provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.\n * The build reads the file's facts once (`describe`, through sharp), writes a\n * file for each ladder width up to the original's own in each format, and\n * names them by content, so a host may keep them for good. The development\n * server makes the same variants when a page asks for them.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { availableParallelism } from 'node:os'\nimport { join, relative, sep } from 'node:path'\nimport { Cause, Effect, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from 'effect'\nimport type { Plugin } from 'vite'\nimport { ImageAsset } from '../asset.js'\nimport type { Format } from '../format.js'\nimport type { Variant } from '../variant.js'\nimport * as Widths from '../widths.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { Transformer } from '../server/services.js'\n\nconst QUERY = 'image'\n// The kept facts' and variants' generation: raised when what `describe` reads or the encoder\n// makes changes, so every build re-reads once, and one that changes neither encodes nothing\n// again. sharp's own version is not in it: a patch release would re-encode every AVIF for\n// nothing anyone sees. r2: an original is read as its EXIF orientation shows it.\nconst CACHE_REVISION = 'r2'\nconst DEV_PREFIX = '/@foldkit-media/image/'\nconst DEV_PATH = /^\\/@foldkit-media\\/image\\/([0-9a-f]{64})\\/w(\\d+)\\.(avif|webp|jpeg|png)$/\n\nexport interface ImagesOptions {\n /** The widths offered, up to each original's own: `Widths.standard` unless given. */\n readonly widths?: Widths.Widths | undefined\n /** Formats offered as `source`s, most preferred first: `['avif']` unless given. */\n readonly sources?: ReadonlyArray<Format> | undefined\n /** The `img`'s own format: `webp` unless given. */\n readonly fallback?: Format | undefined\n /** The encoder's quality, 1 to 100; its own default unless given. */\n readonly quality?: number | undefined\n}\n\ntype Media = ManagedRuntime.ManagedRuntime<Inspector | Transformer, never>\n\n/** The widths a build writes of an original: the ladder's below its own, then its own. */\nconst widthsFor = (ladder: Widths.Widths, width: number): ReadonlyArray<number> => [\n ...ladder.values.filter(value => value < width),\n width,\n]\n\n/**\n * Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build\n * stopped halfway leaves no cut-short file that a later build would trust.\n */\nconst keep = async (file: string, bytes: Uint8Array | string) => {\n const partial = `${file}.${randomUUID()}.partial`\n await writeFile(partial, bytes)\n await rename(partial, file)\n}\n\nconst run = async <A, E>(\n media: Media,\n effect: Effect.Effect<A, E, Inspector | Transformer>,\n what: string,\n) => {\n const exit = await media.runPromiseExit(effect)\n if (Exit.isSuccess(exit)) return exit.value\n throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`)\n}\n\n/**\n * The plugin: an import with `?image` becomes the image's facts and a\n * provider over its variants. sharp is read on the first such import, so an\n * application that imports none needs no sharp.\n */\nexport const images = (options: ImagesOptions = {}): Plugin => {\n const ladder = options.widths ?? Widths.standard\n const sources = options.sources ?? ['avif']\n const fallback = options.fallback ?? 'webp'\n const formats = [...new Set([...sources, fallback])]\n const quality = Option.fromNullishOr(options.quality)\n if (\n Option.isSome(quality) &&\n !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)\n ) {\n throw new Error(\n `foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`,\n )\n }\n\n let root = process.cwd()\n let cache = join(root, 'node_modules', '.vite', 'foldkit-media', CACHE_REVISION)\n let serving = false\n /** The originals the development server has been asked to vary, by content hash. */\n const originals = new Map<\n string,\n { readonly bytes: Uint8Array<ArrayBuffer>; readonly widths: ReadonlyArray<number> }\n >()\n\n // Each read decodes a whole original, and a build loads every import at once: as many at a\n // time as there are cores, as the Transformer's own bound.\n const inspecting = Semaphore.makeUnsafe(availableParallelism())\n let media: Promise<Media> | undefined\n const mediaOf = () =>\n (media ??= import('../sharp/index.js').then(\n ({ inspectorSharp, transformerSharp }) =>\n ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())),\n cause => {\n throw new Error(\n `foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`,\n )\n },\n ))\n\n const factsOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n ): Promise<ImageAsset> => {\n const file = join(cache, hash, 'asset.json')\n try {\n return Schema.decodeUnknownSync(ImageAsset)({\n ...JSON.parse(await readFile(file, 'utf8')),\n key,\n })\n } catch {\n // Not kept yet, or kept by an older version: the facts are made again, as a cache's are.\n const asset = await run(\n await mediaOf(),\n Semaphore.withPermit(inspecting)(describe(key, bytes)),\n `${key} could not be read`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)))\n return asset\n }\n }\n\n const variantOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n width: number,\n format: Format,\n ): Promise<Uint8Array<ArrayBuffer>> => {\n const name = `w${width}${Option.match(quality, { onNone: () => '', onSome: q => `q${q}` })}.${format}`\n const file = join(cache, hash, name)\n try {\n return new Uint8Array(await readFile(file))\n } catch {\n // Not kept yet: made, and kept for the next build.\n const variant: Variant = { width, format, quality }\n const made = await run(\n await mediaOf(),\n Transformer.use(transformer =>\n transformer.transform(\n { body: new Blob([bytes]).stream(), size: bytes.byteLength },\n variant,\n ),\n ),\n `${key} could not be made ${width} wide in ${format}`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, made.bytes)\n return made.bytes\n }\n }\n\n return {\n name: 'foldkit-media:images',\n // Before Vite's own asset handling, which takes a `.jpg` import of any query as a URL.\n enforce: 'pre',\n configResolved(config) {\n root = config.root\n cache = join(config.cacheDir, 'foldkit-media', CACHE_REVISION)\n serving = config.command === 'serve'\n },\n async load(id) {\n const [file, query] = id.split('?')\n if (query === undefined || !new URLSearchParams(query).has(QUERY)) return undefined\n const bytes = new Uint8Array(await readFile(file!))\n const hash = createHash('sha256').update(bytes).digest('hex')\n const key = relative(root, file!).split(sep).join('/')\n const asset = await factsOf(key, bytes, hash)\n const widths = widthsFor(ladder, asset.width)\n if (serving) originals.set(hash, { bytes, widths })\n const stem = key\n .split('/')\n .pop()!\n .replace(/\\.[^.]+$/, '')\n // Made together: the Transformer bounds how many run at once, and AVIF is slow one by one.\n const files = await Promise.all(\n widths.flatMap(width =>\n formats.map(async format => {\n let url: string\n if (serving) {\n url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`)\n } else {\n const source = await variantOf(key, bytes, hash, width, format)\n const contentHash = createHash('sha256').update(source).digest('hex')\n url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({\n type: 'asset',\n fileName: `${stem}-${width}-${contentHash}.${format}`,\n source,\n })}`\n }\n return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`\n }),\n ),\n )\n return [\n `import { Schema } from 'effect'`,\n `import { HashedAsset, Provider } from 'foldkit-media'`,\n `export default {`,\n ` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,\n ` provider: Provider.fromFiles([${files.join(', ')}], ${JSON.stringify({ sources, fallback })}),`,\n `}`,\n ].join('\\n')\n },\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n const match = DEV_PATH.exec(request.url?.split('?')[0] ?? '')\n if (match === null) return next()\n const [, hash, width, asked] = match\n const original = originals.get(hash!)\n const format = formats.find(offered => offered === asked)\n if (\n original === undefined ||\n format === undefined ||\n !original.widths.includes(Number(width))\n ) {\n response.statusCode = 404\n return response.end()\n }\n variantOf(hash!, original.bytes, hash!, Number(width), format).then(bytes => {\n response.setHeader('Content-Type', `image/${format}`)\n response.setHeader('Cache-Control', 'no-store')\n response.end(bytes)\n }, next)\n })\n },\n }\n}\n"],"mappings":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