foldkit-media 0.3.1 → 0.5.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 +23 -22
- 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
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { ImageAsset } from "./asset.js";
|
|
3
|
+
import * as Layout from "./layout.js";
|
|
4
|
+
import { Provider } from "./provider.js";
|
|
5
|
+
import { Level } from "./placeholder.js";
|
|
6
|
+
/** A `source` element's attributes: one format's candidates. */
|
|
7
|
+
export interface Source {
|
|
8
|
+
readonly type: string;
|
|
9
|
+
readonly srcset: string;
|
|
10
|
+
}
|
|
11
|
+
/** The `img` element's attributes. */
|
|
12
|
+
export interface Img {
|
|
13
|
+
readonly src: string;
|
|
14
|
+
readonly srcset: string;
|
|
15
|
+
readonly sizes: string;
|
|
16
|
+
readonly width: number;
|
|
17
|
+
readonly height: number;
|
|
18
|
+
readonly loading: 'lazy' | 'eager';
|
|
19
|
+
readonly decoding: Option.Option<'async'>;
|
|
20
|
+
readonly fetchPriority: Option.Option<'high'>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Everything an image's markup says, derived from its facts, its provider and
|
|
24
|
+
* its layout. A view writes these; it decides nothing.
|
|
25
|
+
*/
|
|
26
|
+
export interface Picture {
|
|
27
|
+
/** One per format the provider offers before the `img`'s own; none, a bare `img`. */
|
|
28
|
+
readonly sources: ReadonlyArray<Source>;
|
|
29
|
+
readonly img: Img;
|
|
30
|
+
/** The original's aspect ratio, as CSS writes one. */
|
|
31
|
+
readonly ratio: string;
|
|
32
|
+
/** Where a crop keeps the subject, as `object-position` writes it. */
|
|
33
|
+
readonly focus: Option.Option<string>;
|
|
34
|
+
/**
|
|
35
|
+
* The CSS `background` to paint behind the image until it loads. None for
|
|
36
|
+
* an image with transparent pixels, which would show it through them.
|
|
37
|
+
*/
|
|
38
|
+
readonly placeholder: Option.Option<string>;
|
|
39
|
+
}
|
|
40
|
+
/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */
|
|
41
|
+
export interface Input<Asset extends ImageAsset = ImageAsset> {
|
|
42
|
+
readonly asset: Asset;
|
|
43
|
+
readonly provider: Provider<NoInfer<Asset>>;
|
|
44
|
+
readonly layout: Layout.Layout;
|
|
45
|
+
/** The page's largest image: fetched first, not lazily. */
|
|
46
|
+
readonly priority?: boolean;
|
|
47
|
+
/** In place of the layout's `sizes`, when the page knows the drawn width better. */
|
|
48
|
+
readonly sizes?: string;
|
|
49
|
+
/**
|
|
50
|
+
* How much of a ThumbHash to paint. By default its picture for a `priority`
|
|
51
|
+
* image, the one a reader waits on, and its average color for the rest, so
|
|
52
|
+
* a grid of thumbnails adds colors to the HTML, not pictures.
|
|
53
|
+
*/
|
|
54
|
+
readonly placeholder?: Level;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The attributes of one image, or none when the provider has no URL for any
|
|
58
|
+
* of its candidates in the `img`'s own encoding (a build table that never made
|
|
59
|
+
* this image). Candidates the provider lacks are left out, never written as a
|
|
60
|
+
* broken URL.
|
|
61
|
+
*/
|
|
62
|
+
export declare const derive: <Asset extends ImageAsset>(input: Input<Asset>) => Option.Option<Picture>;
|
|
63
|
+
/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */
|
|
64
|
+
export interface Preloaded {
|
|
65
|
+
/** A `source`'s media type, so a browser that cannot show it skips the preload. */
|
|
66
|
+
readonly type: Option.Option<string>;
|
|
67
|
+
readonly srcset: string;
|
|
68
|
+
readonly sizes: string;
|
|
69
|
+
}
|
|
70
|
+
/** The `<link rel="preload">` naming `preloaded`, its values escaped for the attribute. */
|
|
71
|
+
export declare const preloadLink: ({ type, srcset, sizes }: Preloaded) => string;
|
|
72
|
+
/**
|
|
73
|
+
* A `<link rel="preload">` for a page's `head`, so the browser fetches its
|
|
74
|
+
* largest image before it reaches the `img`. It names the candidates the
|
|
75
|
+
* browser will choose from: the first `source`'s, with its `type`, so a
|
|
76
|
+
* browser that cannot show that format skips the preload rather than fetching
|
|
77
|
+
* a file it will not use; the `img`'s when there is no `source`. Only for the
|
|
78
|
+
* image drawn with `priority`.
|
|
79
|
+
*/
|
|
80
|
+
export declare const preload: ({ sources, img }: Picture) => string;
|
|
81
|
+
/**
|
|
82
|
+
* An image for a page's Open Graph `og:image`: at the first ladder width of
|
|
83
|
+
* at least 1200, as JPEG when the provider makes it, else WebP or PNG, never
|
|
84
|
+
* AVIF, as an absolute URL against `origin`. None when the provider has no
|
|
85
|
+
* such variant.
|
|
86
|
+
*/
|
|
87
|
+
export declare const ogImage: <Asset extends ImageAsset>(asset: Asset, provider: Provider<NoInfer<Asset>>, origin: string) => Option.Option<string>;
|
|
88
|
+
//# sourceMappingURL=picture.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"picture.d.ts","names":[],"sources":["../src/picture.ts"],"mappings":";;;;;;iBASiB;WACN;WACA;;;iBAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU,OAAO;WACjB,eAAe,OAAO;;;;;;iBAOhB;;WAEN,SAAS,cAAc;WACvB,KAAK;;WAEL;;WAEA,OAAO,OAAO;;;;;WAKd,aAAa,OAAO;;;iBAId,MAAM,cAAc,aAAa;WACvC,OAAO;WACP,UAAU,SAAS,QAAQ;WAC3B,QAAQ,OAAO;;WAEf;;WAEA;;;;;;WAMA,cAAc;;;;;;;;qBASZ,SAAU,cAAc,YAAU,OAAS,MAAM,WAAS,OAAO,OAAO;;iBA0DpE;;WAEN,MAAM,OAAO;WACb;WACA;;;qBAIE,gBAAW,MAAA,QAAA,SAA6B;;;;;;;;;qBAoBxC,YAAO,SAAA,OAAsB;;;;;;;qBAkB7B,UAAW,cAAc,YAAU,OACvC,OAAK,UACF,SAAS,QAAQ,SAAO,mBAEjC,OAAO"}
|
package/dist/picture.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { mimeType } from "./format.js";
|
|
3
|
+
import * as Layout from "./layout.js";
|
|
4
|
+
import * as Widths$1 from "./widths.js";
|
|
5
|
+
import { background } from "./placeholder.js";
|
|
6
|
+
// src/picture.ts
|
|
7
|
+
/**
|
|
8
|
+
* The attributes of one image, or none when the provider has no URL for any
|
|
9
|
+
* of its candidates in the `img`'s own encoding (a build table that never made
|
|
10
|
+
* this image). Candidates the provider lacks are left out, never written as a
|
|
11
|
+
* broken URL.
|
|
12
|
+
*/
|
|
13
|
+
const derive = (input) => {
|
|
14
|
+
const { asset, provider, layout, priority = false } = input;
|
|
15
|
+
const candidates = Layout.candidates(layout, provider.widths, asset.width);
|
|
16
|
+
const entries = (encoding) => candidates.flatMap((candidate) => Option.match(provider.url(asset, {
|
|
17
|
+
width: candidate.request,
|
|
18
|
+
encoding
|
|
19
|
+
}), {
|
|
20
|
+
onNone: () => [],
|
|
21
|
+
onSome: (url) => [{
|
|
22
|
+
url,
|
|
23
|
+
described: candidate.described
|
|
24
|
+
}]
|
|
25
|
+
}));
|
|
26
|
+
const srcsetOf = (list) => list.map(({ url, described }) => `${url} ${described}w`).join(", ");
|
|
27
|
+
const own = entries(provider.fallback);
|
|
28
|
+
if (own.length === 0) return Option.none();
|
|
29
|
+
const drawn = Layout.Schema.match(layout, {
|
|
30
|
+
Fixed: ({ width }) => width,
|
|
31
|
+
Constrained: ({ width }) => width,
|
|
32
|
+
FullWidth: () => Number.POSITIVE_INFINITY
|
|
33
|
+
});
|
|
34
|
+
const src = (own.find((entry) => entry.described >= drawn) ?? own[own.length - 1]).url;
|
|
35
|
+
const sources = provider.sources.flatMap((format) => {
|
|
36
|
+
const list = entries(format);
|
|
37
|
+
return list.length === 0 ? [] : [{
|
|
38
|
+
type: mimeType(format),
|
|
39
|
+
srcset: srcsetOf(list)
|
|
40
|
+
}];
|
|
41
|
+
});
|
|
42
|
+
const sizes = input.sizes ?? Layout.sizes(layout);
|
|
43
|
+
const box = Layout.box(layout, asset);
|
|
44
|
+
return Option.some({
|
|
45
|
+
sources,
|
|
46
|
+
img: {
|
|
47
|
+
src,
|
|
48
|
+
srcset: srcsetOf(own),
|
|
49
|
+
sizes: priority || sizes.startsWith("auto") ? sizes : `auto, ${sizes}`,
|
|
50
|
+
width: box.width,
|
|
51
|
+
height: box.height,
|
|
52
|
+
loading: priority ? "eager" : "lazy",
|
|
53
|
+
decoding: priority ? Option.none() : Option.some("async"),
|
|
54
|
+
fetchPriority: priority ? Option.some("high") : Option.none()
|
|
55
|
+
},
|
|
56
|
+
ratio: Layout.ratio(asset),
|
|
57
|
+
focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),
|
|
58
|
+
placeholder: asset.alpha ? Option.none() : background(asset, provider, input.placeholder ?? (priority ? "detail" : "average"))
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
const escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
62
|
+
/** The `<link rel="preload">` naming `preloaded`, its values escaped for the attribute. */
|
|
63
|
+
const preloadLink = ({ type, srcset, sizes }) => {
|
|
64
|
+
return `<link ${[
|
|
65
|
+
["rel", "preload"],
|
|
66
|
+
["as", "image"],
|
|
67
|
+
...Option.match(type, {
|
|
68
|
+
onNone: () => [],
|
|
69
|
+
onSome: (value) => [["type", value]]
|
|
70
|
+
}),
|
|
71
|
+
["imagesrcset", srcset],
|
|
72
|
+
["imagesizes", sizes],
|
|
73
|
+
["fetchpriority", "high"]
|
|
74
|
+
].map(([name, value]) => `${name}="${escapeAttribute(value)}"`).join(" ")}>`;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* A `<link rel="preload">` for a page's `head`, so the browser fetches its
|
|
78
|
+
* largest image before it reaches the `img`. It names the candidates the
|
|
79
|
+
* browser will choose from: the first `source`'s, with its `type`, so a
|
|
80
|
+
* browser that cannot show that format skips the preload rather than fetching
|
|
81
|
+
* a file it will not use; the `img`'s when there is no `source`. Only for the
|
|
82
|
+
* image drawn with `priority`.
|
|
83
|
+
*/
|
|
84
|
+
const preload = ({ sources, img }) => {
|
|
85
|
+
const [first] = sources;
|
|
86
|
+
return preloadLink({
|
|
87
|
+
type: Option.map(Option.fromNullishOr(first), (source) => source.type),
|
|
88
|
+
srcset: first === void 0 ? img.srcset : first.srcset,
|
|
89
|
+
sizes: img.sizes
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
const OPEN_GRAPH_ENCODINGS = [
|
|
93
|
+
"jpeg",
|
|
94
|
+
"webp",
|
|
95
|
+
"png"
|
|
96
|
+
];
|
|
97
|
+
/**
|
|
98
|
+
* An image for a page's Open Graph `og:image`: at the first ladder width of
|
|
99
|
+
* at least 1200, as JPEG when the provider makes it, else WebP or PNG, never
|
|
100
|
+
* AVIF, as an absolute URL against `origin`. None when the provider has no
|
|
101
|
+
* such variant.
|
|
102
|
+
*/
|
|
103
|
+
const ogImage = (asset, provider, origin) => {
|
|
104
|
+
const width = Widths$1.atLeast(provider.widths, 1200);
|
|
105
|
+
const encodings = provider.fallback === "auto" ? ["auto"] : OPEN_GRAPH_ENCODINGS;
|
|
106
|
+
return Option.map(Option.firstSomeOf(encodings.map((encoding) => provider.url(asset, {
|
|
107
|
+
width,
|
|
108
|
+
encoding
|
|
109
|
+
}))), (url) => new URL(url, origin).href);
|
|
110
|
+
};
|
|
111
|
+
export { derive, ogImage, preload, preloadLink };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=picture.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"picture.js","names":["Widths"],"sources":["../src/picture.ts"],"sourcesContent":["import { Option } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { mimeType, type Encoding } from './format.js'\nimport * as Layout from './layout.js'\nimport { background, type Level } from './placeholder.js'\nimport type { Provider } from './provider.js'\nimport * as Widths from './widths.js'\n\n/** A `source` element's attributes: one format's candidates. */\nexport interface Source {\n readonly type: string\n readonly srcset: string\n}\n\n/** The `img` element's attributes. */\nexport interface Img {\n readonly src: string\n readonly srcset: string\n readonly sizes: string\n readonly width: number\n readonly height: number\n readonly loading: 'lazy' | 'eager'\n readonly decoding: Option.Option<'async'>\n readonly fetchPriority: Option.Option<'high'>\n}\n\n/**\n * Everything an image's markup says, derived from its facts, its provider and\n * its layout. A view writes these; it decides nothing.\n */\nexport interface Picture {\n /** One per format the provider offers before the `img`'s own; none, a bare `img`. */\n readonly sources: ReadonlyArray<Source>\n readonly img: Img\n /** The original's aspect ratio, as CSS writes one. */\n readonly ratio: string\n /** Where a crop keeps the subject, as `object-position` writes it. */\n readonly focus: Option.Option<string>\n /**\n * The CSS `background` to paint behind the image until it loads. None for\n * an image with transparent pixels, which would show it through them.\n */\n readonly placeholder: Option.Option<string>\n}\n\n/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */\nexport interface Input<Asset extends ImageAsset = ImageAsset> {\n readonly asset: Asset\n readonly provider: Provider<NoInfer<Asset>>\n readonly layout: Layout.Layout\n /** The page's largest image: fetched first, not lazily. */\n readonly priority?: boolean\n /** In place of the layout's `sizes`, when the page knows the drawn width better. */\n readonly sizes?: string\n /**\n * How much of a ThumbHash to paint. By default its picture for a `priority`\n * image, the one a reader waits on, and its average color for the rest, so\n * a grid of thumbnails adds colors to the HTML, not pictures.\n */\n readonly placeholder?: Level\n}\n\n/**\n * The attributes of one image, or none when the provider has no URL for any\n * of its candidates in the `img`'s own encoding (a build table that never made\n * this image). Candidates the provider lacks are left out, never written as a\n * broken URL.\n */\nexport const derive = <Asset extends ImageAsset>(input: Input<Asset>): Option.Option<Picture> => {\n const { asset, provider, layout, priority = false } = input\n const candidates = Layout.candidates(layout, provider.widths, asset.width)\n\n const entries = (encoding: Encoding) =>\n candidates.flatMap(candidate =>\n Option.match(provider.url(asset, { width: candidate.request, encoding }), {\n onNone: () => [],\n onSome: url => [{ url, described: candidate.described }],\n }),\n )\n const srcsetOf = (list: ReadonlyArray<{ readonly url: string; readonly described: number }>) =>\n list.map(({ url, described }) => `${url} ${described}w`).join(', ')\n\n const own = entries(provider.fallback)\n if (own.length === 0) return Option.none()\n\n // A browser that ignores `srcset` fetches `src`: the first width at least\n // as wide as the image is drawn, or the largest there is.\n const drawn = Layout.Schema.match(layout, {\n Fixed: ({ width }) => width,\n Constrained: ({ width }) => width,\n FullWidth: () => Number.POSITIVE_INFINITY,\n })\n const src = (own.find(entry => entry.described >= drawn) ?? own[own.length - 1]!).url\n\n const sources = provider.sources.flatMap(format => {\n const list = entries(format)\n return list.length === 0 ? [] : [{ type: mimeType(format), srcset: srcsetOf(list) }]\n })\n\n const sizes = input.sizes ?? Layout.sizes(layout)\n const box = Layout.box(layout, asset)\n return Option.some({\n sources,\n img: {\n src,\n srcset: srcsetOf(own),\n // A lazy image may let the browser use its laid-out width instead.\n sizes: priority || sizes.startsWith('auto') ? sizes : `auto, ${sizes}`,\n width: box.width,\n height: box.height,\n loading: priority ? 'eager' : 'lazy',\n decoding: priority ? Option.none() : Option.some('async'),\n fetchPriority: priority ? Option.some('high') : Option.none(),\n },\n ratio: Layout.ratio(asset),\n focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),\n placeholder: asset.alpha\n ? Option.none()\n : background(asset, provider, input.placeholder ?? (priority ? 'detail' : 'average')),\n })\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')\n\n/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */\nexport interface Preloaded {\n /** A `source`'s media type, so a browser that cannot show it skips the preload. */\n readonly type: Option.Option<string>\n readonly srcset: string\n readonly sizes: string\n}\n\n/** The `<link rel=\"preload\">` naming `preloaded`, its values escaped for the attribute. */\nexport const preloadLink = ({ type, srcset, sizes }: Preloaded): string => {\n const attributes: ReadonlyArray<readonly [string, string]> = [\n ['rel', 'preload'],\n ['as', 'image'],\n ...Option.match(type, { onNone: () => [], onSome: value => [['type', value] as const] }),\n ['imagesrcset', srcset],\n ['imagesizes', sizes],\n ['fetchpriority', 'high'],\n ]\n return `<link ${attributes.map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`).join(' ')}>`\n}\n\n/**\n * A `<link rel=\"preload\">` for a page's `head`, so the browser fetches its\n * largest image before it reaches the `img`. It names the candidates the\n * browser will choose from: the first `source`'s, with its `type`, so a\n * browser that cannot show that format skips the preload rather than fetching\n * a file it will not use; the `img`'s when there is no `source`. Only for the\n * image drawn with `priority`.\n */\nexport const preload = ({ sources, img }: Picture): string => {\n const [first] = sources\n return preloadLink({\n type: Option.map(Option.fromNullishOr(first), source => source.type),\n srcset: first === undefined ? img.srcset : first.srcset,\n sizes: img.sizes,\n })\n}\n\n// Link-preview fetchers read JPEG; many read WebP and PNG; not all read AVIF.\nconst OPEN_GRAPH_ENCODINGS = ['jpeg', 'webp', 'png'] as const\n\n/**\n * An image for a page's Open Graph `og:image`: at the first ladder width of\n * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never\n * AVIF, as an absolute URL against `origin`. None when the provider has no\n * such variant.\n */\nexport const ogImage = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<NoInfer<Asset>>,\n origin: string,\n): Option.Option<string> => {\n const width = Widths.atLeast(provider.widths, 1200)\n // A provider that picks the format reads the fetcher's `Accept`; the rest are asked in turn.\n const encodings: ReadonlyArray<Encoding> =\n provider.fallback === 'auto' ? ['auto'] : OPEN_GRAPH_ENCODINGS\n return Option.map(\n Option.firstSomeOf(encodings.map(encoding => provider.url(asset, { width, encoding }))),\n url => new URL(url, origin).href,\n )\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { ImageAsset } from "./asset.js";
|
|
3
|
+
import { Provider } from "./provider.js";
|
|
4
|
+
/**
|
|
5
|
+
* How much of a ThumbHash a placeholder paints: its blurred picture
|
|
6
|
+
* (`detail`), or its average color (`average`).
|
|
7
|
+
*/
|
|
8
|
+
export type Level = 'detail' | 'average';
|
|
9
|
+
/**
|
|
10
|
+
* The CSS `background` an image's placeholder paints, whatever the image: a
|
|
11
|
+
* color, a ThumbHash at `level`, or the provider's smallest width of the
|
|
12
|
+
* image. None when the image has no placeholder, or the provider has no URL
|
|
13
|
+
* for the smallest width.
|
|
14
|
+
*/
|
|
15
|
+
export declare const background: <Asset extends ImageAsset>(asset: Asset, provider: Provider<Asset>, level: Level) => Option.Option<string>;
|
|
16
|
+
//# sourceMappingURL=placeholder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"placeholder.d.ts","names":[],"sources":["../src/placeholder.ts"],"mappings":";;;;;;;YAoCY;;;;;;;qBAQC,aAAc,cAAc,YAAU,OAC1C,OAAK,UACF,SAAS,QAAM,OAClB,UACN,OAAO"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
import { thumbHashToAverageRGBA, thumbHashToDataURL } from "thumbhash";
|
|
3
|
+
import { Placeholder } from "./asset.js";
|
|
4
|
+
// src/placeholder.ts
|
|
5
|
+
const DECODED_LIMIT = 256;
|
|
6
|
+
const decoded = /* @__PURE__ */ new Map();
|
|
7
|
+
const bytesOf = (hash) => Uint8Array.from(atob(hash), (char) => char.charCodeAt(0));
|
|
8
|
+
const decode = (hash) => {
|
|
9
|
+
const cached = decoded.get(hash);
|
|
10
|
+
if (cached !== void 0) return cached;
|
|
11
|
+
const url = thumbHashToDataURL(bytesOf(hash));
|
|
12
|
+
if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value);
|
|
13
|
+
decoded.set(hash, url);
|
|
14
|
+
return url;
|
|
15
|
+
};
|
|
16
|
+
const cssUrl = (url) => `url("${url.replace(/["\\\n\r]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`)}")`;
|
|
17
|
+
const average = (hash) => {
|
|
18
|
+
const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash));
|
|
19
|
+
const channel = (value) => Math.round(value * 255);
|
|
20
|
+
return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The CSS `background` an image's placeholder paints, whatever the image: a
|
|
24
|
+
* color, a ThumbHash at `level`, or the provider's smallest width of the
|
|
25
|
+
* image. None when the image has no placeholder, or the provider has no URL
|
|
26
|
+
* for the smallest width.
|
|
27
|
+
*/
|
|
28
|
+
const background = (asset, provider, level) => Option.flatMap(asset.placeholder, (placeholder) => Placeholder.match(placeholder, {
|
|
29
|
+
Color: ({ value }) => Option.some(value),
|
|
30
|
+
ThumbHash: ({ hash }) => Option.some(level === "detail" ? cssUrl(decode(hash)) : average(hash)),
|
|
31
|
+
LowRes: () => Option.map(provider.url(asset, {
|
|
32
|
+
width: provider.widths.values[0],
|
|
33
|
+
encoding: provider.fallback
|
|
34
|
+
}), cssUrl)
|
|
35
|
+
}));
|
|
36
|
+
export { background };
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=placeholder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"placeholder.js","names":[],"sources":["../src/placeholder.ts"],"sourcesContent":["import { Option } from 'effect'\nimport { thumbHashToAverageRGBA, thumbHashToDataURL } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { Provider } from './provider.js'\n\n// A list redraws the same images, and decoding draws a PNG each time; a few\n// hundred recent ones cover a page without growing for the life of the app.\nconst DECODED_LIMIT = 256\nconst decoded = new Map<string, string>()\n\nconst bytesOf = (hash: string) => Uint8Array.from(atob(hash), char => char.charCodeAt(0))\n\nconst decode = (hash: string): string => {\n const cached = decoded.get(hash)\n if (cached !== undefined) return cached\n const url = thumbHashToDataURL(bytesOf(hash))\n if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value!)\n decoded.set(hash, url)\n return url\n}\n\n// Percent-encode what would end or escape a quoted CSS `url()`.\nconst cssUrl = (url: string): string =>\n `url(\"${url.replace(/[\"\\\\\\n\\r]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}\")`\n\n// A ThumbHash's average color, which costs a few bytes of HTML where its picture costs kilobytes.\nconst average = (hash: string): string => {\n const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash))\n const channel = (value: number) => Math.round(value * 255)\n return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`\n}\n\n/**\n * How much of a ThumbHash a placeholder paints: its blurred picture\n * (`detail`), or its average color (`average`).\n */\nexport type Level = 'detail' | 'average'\n\n/**\n * The CSS `background` an image's placeholder paints, whatever the image: a\n * color, a ThumbHash at `level`, or the provider's smallest width of the\n * image. None when the image has no placeholder, or the provider has no URL\n * for the smallest width.\n */\nexport const background = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<Asset>,\n level: Level,\n): Option.Option<string> =>\n Option.flatMap(asset.placeholder, placeholder =>\n Placeholder.match(placeholder, {\n Color: ({ value }) => Option.some(value),\n ThumbHash: ({ hash }) =>\n Option.some(level === 'detail' ? cssUrl(decode(hash)) : average(hash)),\n LowRes: () =>\n Option.map(\n provider.url(asset, { width: provider.widths.values[0]!, encoding: provider.fallback }),\n cssUrl,\n ),\n }),\n )\n"],"mappings":";;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,0BAAU,IAAI,IAAoB;AAExC,MAAM,WAAW,SAAiB,WAAW,KAAK,KAAK,IAAI,IAAG,SAAQ,KAAK,WAAW,CAAC,CAAC;AAExF,MAAM,UAAU,SAAyB;CACvC,MAAM,SAAS,QAAQ,IAAI,IAAI;CAC/B,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,MAAM,mBAAmB,QAAQ,IAAI,CAAC;CAC5C,IAAI,QAAQ,QAAQ,eAAe,QAAQ,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;CAC9E,QAAQ,IAAI,MAAM,GAAG;CACrB,OAAO;AACT;AAGA,MAAM,UAAU,QACd,QAAQ,IAAI,QAAQ,eAAc,SAAQ,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG,EAAE;AAGlH,MAAM,WAAW,SAAyB;CACxC,MAAM,EAAE,GAAG,GAAG,GAAG,MAAM,uBAAuB,QAAQ,IAAI,CAAC;CAC3D,MAAM,WAAW,UAAkB,KAAK,MAAM,QAAQ,GAAG;CACzD,OAAO,OAAO,QAAQ,CAAC,EAAE,GAAG,QAAQ,CAAC,EAAE,GAAG,QAAQ,CAAC,EAAE,KAAK,KAAK,MAAM,IAAI,GAAG,IAAI,IAAI;AACtF;;;;;;;AAcA,MAAa,cACX,OACA,UACA,UAEA,OAAO,QAAQ,MAAM,cAAa,gBAChC,YAAY,MAAM,aAAa;CAC7B,QAAQ,EAAE,YAAY,OAAO,KAAK,KAAK;CACvC,YAAY,EAAE,WACZ,OAAO,KAAK,UAAU,WAAW,OAAO,OAAO,IAAI,CAAC,IAAI,QAAQ,IAAI,CAAC;CACvE,cACE,OAAO,IACL,SAAS,IAAI,OAAO;EAAE,OAAO,SAAS,OAAO,OAAO;EAAK,UAAU,SAAS;CAAS,CAAC,GACtF,MACF;AACJ,CAAC,CACH"}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { n as HashedAsset, r as ImageAsset } from "./asset-BLo8VWmd.mjs";
|
|
2
|
-
import { i as Format, r as Encoding, t as Widths } from "./widths-upkgLdek.mjs";
|
|
3
|
-
import { t as Space } from "./variant-B-vyMmFB.mjs";
|
|
4
1
|
import { Option } from "effect";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
}
|
|
2
|
+
import * as Variant$1 from "./variant.js";
|
|
3
|
+
import { HashedAsset, ImageAsset } from "./asset.js";
|
|
4
|
+
import { Encoding, Format } from "./format.js";
|
|
5
|
+
import * as Widths$1 from "./widths.js";
|
|
8
6
|
/** One variant asked of a provider: a ladder width, in an encoding. */
|
|
9
|
-
interface Request {
|
|
7
|
+
export interface Request {
|
|
10
8
|
readonly width: number;
|
|
11
9
|
readonly encoding: Encoding;
|
|
12
10
|
}
|
|
@@ -15,8 +13,8 @@ interface Request {
|
|
|
15
13
|
* URL scheme, the widths it makes, and the encodings worth offering. `Asset`
|
|
16
14
|
* is the facts it needs: `HashedAsset` for one that names originals by hash.
|
|
17
15
|
*/
|
|
18
|
-
interface Provider<in Asset extends ImageAsset = ImageAsset> {
|
|
19
|
-
readonly widths: Widths;
|
|
16
|
+
export interface Provider<in Asset extends ImageAsset = ImageAsset> {
|
|
17
|
+
readonly widths: Widths$1.Widths;
|
|
20
18
|
/** Formats offered as `source`s before the `img`, most preferred first. */
|
|
21
19
|
readonly sources: ReadonlyArray<Format>;
|
|
22
20
|
/** What the `img` itself asks for; `auto` lets the host choose. */
|
|
@@ -25,7 +23,7 @@ interface Provider<in Asset extends ImageAsset = ImageAsset> {
|
|
|
25
23
|
readonly url: (asset: Asset, request: Request) => Option.Option<string>;
|
|
26
24
|
}
|
|
27
25
|
/** A file a build emitted: one width of one original, in one format. */
|
|
28
|
-
interface File {
|
|
26
|
+
export interface File {
|
|
29
27
|
readonly width: number;
|
|
30
28
|
readonly format: Format;
|
|
31
29
|
readonly url: string;
|
|
@@ -35,7 +33,7 @@ interface File {
|
|
|
35
33
|
* files, no URL scheme. Its ladder is the widths it has, and it answers none
|
|
36
34
|
* for a variant it lacks. Refuses no files, and two files for one variant.
|
|
37
35
|
*/
|
|
38
|
-
declare const fromFiles: (files: ReadonlyArray<File>, formats: {
|
|
36
|
+
export declare const fromFiles: (files: ReadonlyArray<File>, formats: {
|
|
39
37
|
readonly sources: ReadonlyArray<Format>;
|
|
40
38
|
readonly fallback: Format;
|
|
41
39
|
}) => Provider;
|
|
@@ -45,16 +43,16 @@ declare const fromFiles: (files: ReadonlyArray<File>, formats: {
|
|
|
45
43
|
* `key` (a path on the zone, or an absolute URL it may fetch), scales it down
|
|
46
44
|
* without enlarging, and picks the format from `Accept`.
|
|
47
45
|
*/
|
|
48
|
-
declare const cdnCgi: (options?: {
|
|
46
|
+
export declare const cdnCgi: (options?: {
|
|
49
47
|
/** The zone's host; omitted, URLs are relative to the page's. */
|
|
50
48
|
readonly zone?: string;
|
|
51
|
-
readonly widths?: Widths;
|
|
49
|
+
readonly widths?: Widths$1.Widths;
|
|
52
50
|
/** 1 to 100. Cloudflare's default when omitted. */
|
|
53
51
|
readonly quality?: number;
|
|
54
52
|
}) => Provider;
|
|
55
53
|
/** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */
|
|
56
|
-
interface Hosted extends Provider<HashedAsset> {
|
|
57
|
-
readonly space: Space;
|
|
54
|
+
export interface Hosted extends Provider<HashedAsset> {
|
|
55
|
+
readonly space: Variant$1.Space;
|
|
58
56
|
}
|
|
59
57
|
/**
|
|
60
58
|
* Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under
|
|
@@ -65,16 +63,15 @@ interface Hosted extends Provider<HashedAsset> {
|
|
|
65
63
|
* than answered with a 400 on every image. Give the same value to the server
|
|
66
64
|
* (`serveFetch`'s `images.provider`), which reads its space from it.
|
|
67
65
|
*/
|
|
68
|
-
declare const hosted: (options?: {
|
|
66
|
+
export declare const hosted: (options?: {
|
|
69
67
|
/** The server's origin, such as `https://img.example.com`; omitted, the page's. */
|
|
70
68
|
readonly baseUrl?: string;
|
|
71
69
|
/** The server's space; the same value its handler decodes with. */
|
|
72
|
-
readonly space?: Space;
|
|
70
|
+
readonly space?: Variant$1.Space;
|
|
73
71
|
/** Formats offered as `source`s; by default every one of the space's but the last. */
|
|
74
72
|
readonly sources?: ReadonlyArray<Format>;
|
|
75
73
|
/** The `img`'s own format; by default the space's last. */
|
|
76
74
|
readonly fallback?: Format;
|
|
77
75
|
readonly quality?: number;
|
|
78
76
|
}) => Hosted;
|
|
79
|
-
|
|
80
|
-
//# sourceMappingURL=provider-CB0nqu0m.d.mts.map
|
|
77
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","names":["Widths","Variant"],"sources":["../src/provider.ts"],"mappings":";;;;;;iBAOiB;WACN;WACA,UAAU;;;;;;;iBAQJ,YAAY,cAAc,aAAa;WAC7C,QAAQA,SAAO;;WAEf,SAAS,cAAc;;WAEvB,UAAU;;WAEV,MAAM,OAAO,OAAO,SAAS,YAAY,OAAO;;;iBAI1C;WACN;WACA,QAAQ;WACR;;;;;;;qBAQE,YAAS,OACb,cAAc,OAAK;WACN,SAAS,cAAc;WAAkB,UAAU;MACtE;;;;;;;qBA2BU,SAAM;;WAGN;WACA,SAASA,SAAO;;WAEhB;MAEV;;iBA4Bc,eAAe,SAAS;WAC9B,OAAOC,UAAQ;;;;;;;;;;;qBAYb,SAAM;;WAGN;;WAEA,QAAQA,UAAQ;;WAEhB,UAAU,cAAc;;WAExB,WAAW;WACX;MAEV"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
import * as Variant$1 from "./variant.js";
|
|
3
|
+
import * as Widths$1 from "./widths.js";
|
|
4
|
+
// src/provider.ts
|
|
5
|
+
/**
|
|
6
|
+
* The provider of one image whose variants a build already wrote: a table of
|
|
7
|
+
* files, no URL scheme. Its ladder is the widths it has, and it answers none
|
|
8
|
+
* for a variant it lacks. Refuses no files, and two files for one variant.
|
|
9
|
+
*/
|
|
10
|
+
const fromFiles = (files, formats) => {
|
|
11
|
+
if (files.length === 0) throw new Error("Provider.fromFiles: no files");
|
|
12
|
+
const byVariant = /* @__PURE__ */ new Map();
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
const variant = `${file.width}:${file.format}`;
|
|
15
|
+
if (byVariant.has(variant)) throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`);
|
|
16
|
+
byVariant.set(variant, file.url);
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
widths: Widths$1.make([...new Set(files.map((file) => file.width))]),
|
|
20
|
+
sources: formats.sources,
|
|
21
|
+
fallback: formats.fallback,
|
|
22
|
+
url: (_asset, { width, encoding }) => Option.fromNullishOr(byVariant.get(`${width}:${encoding}`))
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
|
|
26
|
+
/**
|
|
27
|
+
* Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that
|
|
28
|
+
* has it on. No Worker of ours runs: the zone fetches the original by its
|
|
29
|
+
* `key` (a path on the zone, or an absolute URL it may fetch), scales it down
|
|
30
|
+
* without enlarging, and picks the format from `Accept`.
|
|
31
|
+
*/
|
|
32
|
+
const cdnCgi = (options = {}) => {
|
|
33
|
+
const { zone, widths = Widths$1.standard, quality } = options;
|
|
34
|
+
if (zone !== void 0 && !HOSTNAME.test(zone)) throw new Error(`Provider.cdnCgi: "${zone}" is not a host name`);
|
|
35
|
+
if (quality !== void 0 && !Schema.is(Variant$1.Quality)(quality)) throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`);
|
|
36
|
+
const base = zone === void 0 ? "" : `https://${zone}`;
|
|
37
|
+
const qualityOption = quality === void 0 ? "" : `,quality=${quality}`;
|
|
38
|
+
return {
|
|
39
|
+
widths,
|
|
40
|
+
sources: [],
|
|
41
|
+
fallback: "auto",
|
|
42
|
+
url: (asset, { width, encoding }) => {
|
|
43
|
+
const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`;
|
|
44
|
+
return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
const cdnCgiSource = (key) => {
|
|
49
|
+
if (!/^https?:\/\//.test(key)) return key.replace(/^\/+/, "");
|
|
50
|
+
return key.includes("?") ? encodeURIComponent(key) : key;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under
|
|
54
|
+
* `baseUrl`. An original is named by its content hash, so it takes a
|
|
55
|
+
* `HashedAsset`, and has no URL for `auto`: this server names the format in
|
|
56
|
+
* the URL, never reads `Accept`, so every cache can key on the URL alone.
|
|
57
|
+
* Its formats and quality must be in `space`, or it is refused here rather
|
|
58
|
+
* than answered with a 400 on every image. Give the same value to the server
|
|
59
|
+
* (`serveFetch`'s `images.provider`), which reads its space from it.
|
|
60
|
+
*/
|
|
61
|
+
const hosted = (options = {}) => {
|
|
62
|
+
const { baseUrl: askedBaseUrl = "", space = Variant$1.standard } = options;
|
|
63
|
+
const fallback = options.fallback ?? space.formats[space.formats.length - 1];
|
|
64
|
+
const sources = options.sources ?? space.formats.slice(0, -1);
|
|
65
|
+
const parsed = Option.liftThrowable((value) => new URL(value))(askedBaseUrl);
|
|
66
|
+
const origin = Option.filter(parsed, (url) => (url.protocol === "http:" || url.protocol === "https:") && askedBaseUrl === url.origin);
|
|
67
|
+
if (askedBaseUrl !== "" && Option.isNone(origin)) throw new Error(`Provider.hosted: "${askedBaseUrl}" is not an origin`);
|
|
68
|
+
const baseUrl = Option.match(origin, {
|
|
69
|
+
onNone: () => "",
|
|
70
|
+
onSome: (url) => url.origin
|
|
71
|
+
});
|
|
72
|
+
for (const format of [...sources, fallback]) if (!space.formats.includes(format)) throw new Error(`Provider.hosted: the server's space does not make ${format}`);
|
|
73
|
+
const quality = Option.fromNullishOr(options.quality);
|
|
74
|
+
if (Option.isSome(quality) && !space.qualities.includes(quality.value)) throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`);
|
|
75
|
+
const encodeVariant = Schema.encodeOption(space.schema);
|
|
76
|
+
return {
|
|
77
|
+
space,
|
|
78
|
+
widths: space.widths,
|
|
79
|
+
sources,
|
|
80
|
+
fallback,
|
|
81
|
+
url: (asset, { width, encoding }) => {
|
|
82
|
+
if (encoding === "auto") return Option.none();
|
|
83
|
+
return Option.map(encodeVariant({
|
|
84
|
+
width,
|
|
85
|
+
format: encoding,
|
|
86
|
+
quality
|
|
87
|
+
}), (variant) => baseUrl + Variant$1.PATH.replace(":hash", asset.hash.value).replace(":variant", variant));
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
export { cdnCgi, fromFiles, hosted };
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","names":["Widths","Variant"],"sources":["../src/provider.ts"],"sourcesContent":["import { Option, Schema } from 'effect'\nimport type { HashedAsset, ImageAsset } from './asset.js'\nimport type { Encoding, Format } from './format.js'\nimport * as Variant from './variant.js'\nimport * as Widths from './widths.js'\n\n/** One variant asked of a provider: a ladder width, in an encoding. */\nexport interface Request {\n readonly width: number\n readonly encoding: Encoding\n}\n\n/**\n * Writes the URL of a variant. A provider performs no I/O: it knows a host's\n * URL scheme, the widths it makes, and the encodings worth offering. `Asset`\n * is the facts it needs: `HashedAsset` for one that names originals by hash.\n */\nexport interface Provider<in Asset extends ImageAsset = ImageAsset> {\n readonly widths: Widths.Widths\n /** Formats offered as `source`s before the `img`, most preferred first. */\n readonly sources: ReadonlyArray<Format>\n /** What the `img` itself asks for; `auto` lets the host choose. */\n readonly fallback: Encoding\n /** The variant's URL, or none when this provider has no such variant. */\n readonly url: (asset: Asset, request: Request) => Option.Option<string>\n}\n\n/** A file a build emitted: one width of one original, in one format. */\nexport interface File {\n readonly width: number\n readonly format: Format\n readonly url: string\n}\n\n/**\n * The provider of one image whose variants a build already wrote: a table of\n * files, no URL scheme. Its ladder is the widths it has, and it answers none\n * for a variant it lacks. Refuses no files, and two files for one variant.\n */\nexport const fromFiles = (\n files: ReadonlyArray<File>,\n formats: { readonly sources: ReadonlyArray<Format>; readonly fallback: Format },\n): Provider => {\n if (files.length === 0) throw new Error('Provider.fromFiles: no files')\n const byVariant = new Map<string, string>()\n for (const file of files) {\n const variant = `${file.width}:${file.format}`\n if (byVariant.has(variant)) {\n throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`)\n }\n byVariant.set(variant, file.url)\n }\n return {\n widths: Widths.make([...new Set(files.map(file => file.width))]),\n sources: formats.sources,\n fallback: formats.fallback,\n url: (_asset, { width, encoding }) =>\n Option.fromNullishOr(byVariant.get(`${width}:${encoding}`)),\n }\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n/**\n * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that\n * has it on. No Worker of ours runs: the zone fetches the original by its\n * `key` (a path on the zone, or an absolute URL it may fetch), scales it down\n * without enlarging, and picks the format from `Accept`.\n */\nexport const cdnCgi = (\n options: {\n /** The zone's host; omitted, URLs are relative to the page's. */\n readonly zone?: string\n readonly widths?: Widths.Widths\n /** 1 to 100. Cloudflare's default when omitted. */\n readonly quality?: number\n } = {},\n): Provider => {\n const { zone, widths = Widths.standard, quality } = options\n if (zone !== undefined && !HOSTNAME.test(zone)) {\n throw new Error(`Provider.cdnCgi: \"${zone}\" is not a host name`)\n }\n if (quality !== undefined && !Schema.is(Variant.Quality)(quality)) {\n throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`)\n }\n const base = zone === undefined ? '' : `https://${zone}`\n const qualityOption = quality === undefined ? '' : `,quality=${quality}`\n return {\n widths,\n sources: [],\n fallback: 'auto',\n url: (asset, { width, encoding }) => {\n const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`\n return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`)\n },\n }\n}\n\nconst cdnCgiSource = (key: string): string => {\n if (!/^https?:\\/\\//.test(key)) return key.replace(/^\\/+/, '')\n // A query in an absolute source would be read as the image URL's own.\n return key.includes('?') ? encodeURIComponent(key) : key\n}\n\n/** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */\nexport interface Hosted extends Provider<HashedAsset> {\n readonly space: Variant.Space\n}\n\n/**\n * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under\n * `baseUrl`. An original is named by its content hash, so it takes a\n * `HashedAsset`, and has no URL for `auto`: this server names the format in\n * the URL, never reads `Accept`, so every cache can key on the URL alone.\n * Its formats and quality must be in `space`, or it is refused here rather\n * than answered with a 400 on every image. Give the same value to the server\n * (`serveFetch`'s `images.provider`), which reads its space from it.\n */\nexport const hosted = (\n options: {\n /** The server's origin, such as `https://img.example.com`; omitted, the page's. */\n readonly baseUrl?: string\n /** The server's space; the same value its handler decodes with. */\n readonly space?: Variant.Space\n /** Formats offered as `source`s; by default every one of the space's but the last. */\n readonly sources?: ReadonlyArray<Format>\n /** The `img`'s own format; by default the space's last. */\n readonly fallback?: Format\n readonly quality?: number\n } = {},\n): Hosted => {\n const { baseUrl: askedBaseUrl = '', space = Variant.standard } = options\n const fallback = options.fallback ?? space.formats[space.formats.length - 1]!\n const sources = options.sources ?? space.formats.slice(0, -1)\n const parsed = Option.liftThrowable((value: string) => new URL(value))(askedBaseUrl)\n const origin = Option.filter(\n parsed,\n url => (url.protocol === 'http:' || url.protocol === 'https:') && askedBaseUrl === url.origin,\n )\n if (askedBaseUrl !== '' && Option.isNone(origin)) {\n throw new Error(`Provider.hosted: \"${askedBaseUrl}\" is not an origin`)\n }\n const baseUrl = Option.match(origin, { onNone: () => '', onSome: url => url.origin })\n for (const format of [...sources, fallback]) {\n if (!space.formats.includes(format)) {\n throw new Error(`Provider.hosted: the server's space does not make ${format}`)\n }\n }\n const quality = Option.fromNullishOr(options.quality)\n if (Option.isSome(quality) && !space.qualities.includes(quality.value)) {\n throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`)\n }\n const encodeVariant = Schema.encodeOption(space.schema)\n return {\n space,\n widths: space.widths,\n sources,\n fallback,\n url: (asset, { width, encoding }) => {\n if (encoding === 'auto') return Option.none()\n return Option.map(\n encodeVariant({ width, format: encoding, quality }),\n variant =>\n baseUrl + Variant.PATH.replace(':hash', asset.hash.value).replace(':variant', variant),\n )\n },\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Context, Duration, Effect, Layer, Schema } from "effect";
|
|
2
|
+
import { RateLimiter } from "effect/persistence";
|
|
3
|
+
declare const RateLimited_base: Schema.Class<RateLimited, Schema.TaggedStruct<"RateLimited", {
|
|
4
|
+
readonly retryAfterSeconds: Schema.Number;
|
|
5
|
+
}>, import("effect/Cause").YieldableError>;
|
|
6
|
+
/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */
|
|
7
|
+
export declare class RateLimited extends RateLimited_base {}
|
|
8
|
+
declare const Admission_base: Context.ServiceClass<Admission, "foldkit-media/Admission", {
|
|
9
|
+
readonly admit: (client: string) => Effect.Effect<void, RateLimited>;
|
|
10
|
+
}>;
|
|
11
|
+
/**
|
|
12
|
+
* Whether a client may have a variant made now. Asked only on a miss, after
|
|
13
|
+
* the store and before the original is read: a variant already made costs a
|
|
14
|
+
* read, and only making one costs work. Optional: without it, every miss is
|
|
15
|
+
* admitted.
|
|
16
|
+
*/
|
|
17
|
+
export declare class Admission extends Admission_base {}
|
|
18
|
+
/**
|
|
19
|
+
* Admission through Effect's `RateLimiter`, `limit` misses a client per
|
|
20
|
+
* `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one
|
|
21
|
+
* process, Redis for several). A store that fails admits the request, reported
|
|
22
|
+
* as `AdmissionFailed`: a limiter that is down should not take the images
|
|
23
|
+
* down with it.
|
|
24
|
+
*/
|
|
25
|
+
export declare const admissionRateLimiter: (options: {
|
|
26
|
+
readonly limit: number;
|
|
27
|
+
readonly window: Duration.Input;
|
|
28
|
+
readonly algorithm?: 'fixed-window' | 'token-bucket';
|
|
29
|
+
}) => Layer.Layer<Admission, never, RateLimiter.RateLimiter>;
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=admission.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admission.d.ts","names":[],"sources":["../../src/server/admission.ts"],"mappings":";;;;;;qBAMa,oBAAoB;;WAcb,QAAC,mBAAmB,OAAO,aAAa;;;;;;;;qBAF/C,kBAAkB;;;;;;;;qBAYlB,uBAAoB;WACtB;WACA,QAAQ,SAAS;WACjB;MACP,MAAM,MAAM,kBAAkB,YAAY"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Context, Duration, Effect, Layer, Match, Schema } from "effect";
|
|
2
|
+
import { RateLimiter } from "effect/persistence";
|
|
3
|
+
import { Diagnostics } from "foldkit-surface";
|
|
4
|
+
import { admissionFailed } from "./diagnostics.js";
|
|
5
|
+
// src/server/admission.ts
|
|
6
|
+
/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */
|
|
7
|
+
var RateLimited = class extends Schema.TaggedError()("RateLimited", { retryAfterSeconds: Schema.Number }, { httpApiStatus: 429 }) {};
|
|
8
|
+
/**
|
|
9
|
+
* Whether a client may have a variant made now. Asked only on a miss, after
|
|
10
|
+
* the store and before the original is read: a variant already made costs a
|
|
11
|
+
* read, and only making one costs work. Optional: without it, every miss is
|
|
12
|
+
* admitted.
|
|
13
|
+
*/
|
|
14
|
+
var Admission = class extends Context.Service()("foldkit-media/Admission") {};
|
|
15
|
+
/**
|
|
16
|
+
* Admission through Effect's `RateLimiter`, `limit` misses a client per
|
|
17
|
+
* `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one
|
|
18
|
+
* process, Redis for several). A store that fails admits the request, reported
|
|
19
|
+
* as `AdmissionFailed`: a limiter that is down should not take the images
|
|
20
|
+
* down with it.
|
|
21
|
+
*/
|
|
22
|
+
const admissionRateLimiter = (options) => Layer.effect(Admission, Effect.gen(function* () {
|
|
23
|
+
const limiter = yield* RateLimiter.RateLimiter;
|
|
24
|
+
return { admit: (client) => limiter.consume({
|
|
25
|
+
key: `foldkit-media:${client}`,
|
|
26
|
+
limit: options.limit,
|
|
27
|
+
window: options.window,
|
|
28
|
+
algorithm: options.algorithm ?? "token-bucket",
|
|
29
|
+
onExceeded: "fail"
|
|
30
|
+
}).pipe(Effect.asVoid, Effect.catch((error) => Match.valueTags(error.reason, {
|
|
31
|
+
RateLimitExceeded: ({ retryAfter }) => Effect.fail(new RateLimited({ retryAfterSeconds: Math.max(1, Math.ceil(Duration.toSeconds(retryAfter))) })),
|
|
32
|
+
RateLimitStoreError: () => Diagnostics.report(admissionFailed({
|
|
33
|
+
limiter: "RateLimiter",
|
|
34
|
+
client,
|
|
35
|
+
cause: error
|
|
36
|
+
}))
|
|
37
|
+
}))) };
|
|
38
|
+
}));
|
|
39
|
+
export { Admission, RateLimited, admissionRateLimiter };
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=admission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admission.js","names":[],"sources":["../../src/server/admission.ts"],"sourcesContent":["import { Context, Duration, Effect, Layer, Match, Schema } from 'effect'\nimport { RateLimiter } from 'effect/persistence'\nimport { Diagnostics } from 'foldkit-surface'\nimport { admissionFailed } from './diagnostics.js'\n\n/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */\nexport class RateLimited extends Schema.TaggedError<RateLimited>()(\n 'RateLimited',\n { retryAfterSeconds: Schema.Number },\n { httpApiStatus: 429 },\n) {}\n\n/**\n * Whether a client may have a variant made now. Asked only on a miss, after\n * the store and before the original is read: a variant already made costs a\n * read, and only making one costs work. Optional: without it, every miss is\n * admitted.\n */\nexport class Admission extends Context.Service<\n Admission,\n { readonly admit: (client: string) => Effect.Effect<void, RateLimited> }\n>()('foldkit-media/Admission') {}\n\n/**\n * Admission through Effect's `RateLimiter`, `limit` misses a client per\n * `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one\n * process, Redis for several). A store that fails admits the request, reported\n * as `AdmissionFailed`: a limiter that is down should not take the images\n * down with it.\n */\nexport const admissionRateLimiter = (options: {\n readonly limit: number\n readonly window: Duration.Input\n readonly algorithm?: 'fixed-window' | 'token-bucket'\n}): Layer.Layer<Admission, never, RateLimiter.RateLimiter> =>\n Layer.effect(\n Admission,\n Effect.gen(function* () {\n const limiter = yield* RateLimiter.RateLimiter\n return {\n admit: (client: string) =>\n limiter\n .consume({\n key: `foldkit-media:${client}`,\n limit: options.limit,\n window: options.window,\n algorithm: options.algorithm ?? 'token-bucket',\n onExceeded: 'fail',\n })\n .pipe(\n Effect.asVoid,\n Effect.catch(error =>\n Match.valueTags(error.reason, {\n RateLimitExceeded: ({ retryAfter }) =>\n Effect.fail(\n new RateLimited({\n retryAfterSeconds: Math.max(1, Math.ceil(Duration.toSeconds(retryAfter))),\n }),\n ),\n RateLimitStoreError: () =>\n Diagnostics.report(\n admissionFailed({ limiter: 'RateLimiter', client, cause: error }),\n ),\n }),\n ),\n ),\n }\n }),\n )\n"],"mappings":";;;;;;AAMA,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAChE,eACA,EAAE,mBAAmB,OAAO,OAAO,GACnC,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;;;;;;AAQH,IAAa,YAAb,cAA+B,QAAQ,QAGrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;;;;;;;;AAShC,MAAa,wBAAwB,YAKnC,MAAM,OACJ,WACA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,OAAO,YAAY;CACnC,OAAO,EACL,QAAQ,WACN,QACG,QAAQ;EACP,KAAK,iBAAiB;EACtB,OAAO,QAAQ;EACf,QAAQ,QAAQ;EAChB,WAAW,QAAQ,aAAa;EAChC,YAAY;CACd,CAAC,CAAC,CACD,KACC,OAAO,QACP,OAAO,OAAM,UACX,MAAM,UAAU,MAAM,QAAQ;EAC5B,oBAAoB,EAAE,iBACpB,OAAO,KACL,IAAI,YAAY,EACd,mBAAmB,KAAK,IAAI,GAAG,KAAK,KAAK,SAAS,UAAU,UAAU,CAAC,CAAC,EAC1E,CAAC,CACH;EACF,2BACE,YAAY,OACV,gBAAgB;GAAE,SAAS;GAAe;GAAQ,OAAO;EAAM,CAAC,CAClE;CACJ,CAAC,CACH,CACF,EACN;AACF,CAAC,CACH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
|
|
3
|
+
/**
|
|
4
|
+
* The media server's HTTP API: one route, a variant of an original named by
|
|
5
|
+
* its content hash. The route takes its params as text, and the handler
|
|
6
|
+
* decodes them with the space's Schema, the one `Provider.hosted` encodes
|
|
7
|
+
* with, so a variant outside the space is refused before any work, and that
|
|
8
|
+
* refusal, like every answer, carries the headers `headersFor` decides.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MediaApi: HttpApi.HttpApi<"foldkit-media", HttpApiGroup.HttpApiGroup<"images", HttpApiEndpoint.HttpApiEndpoint<"variant", "GET", "/_image/:hash/:variant", Schema.toCodecStringTree<Schema.Struct<{
|
|
11
|
+
hash: Schema.String;
|
|
12
|
+
variant: Schema.String;
|
|
13
|
+
}>>, never, never, never, HttpApiSchema.StreamUint8Array, never, never, never>, false>>;
|
|
14
|
+
//# sourceMappingURL=api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.d.ts","names":[],"sources":["../../src/server/api.ts"],"mappings":";;;;;;;;;qBAWa,UAAQ,QAAA,yBAAA,aAAA,uBAAA,gBAAA,4DAAA,OAAA,kBAAA,OAAA;;;0BAOpB,cAAA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import * as Variant$1 from "../variant.js";
|
|
3
|
+
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
|
|
4
|
+
// src/server/api.ts
|
|
5
|
+
/**
|
|
6
|
+
* The media server's HTTP API: one route, a variant of an original named by
|
|
7
|
+
* its content hash. The route takes its params as text, and the handler
|
|
8
|
+
* decodes them with the space's Schema, the one `Provider.hosted` encodes
|
|
9
|
+
* with, so a variant outside the space is refused before any work, and that
|
|
10
|
+
* refusal, like every answer, carries the headers `headersFor` decides.
|
|
11
|
+
*/
|
|
12
|
+
const MediaApi = HttpApi.make("foldkit-media").add(HttpApiGroup.make("images").add(HttpApiEndpoint.get("variant", Variant$1.PATH, {
|
|
13
|
+
params: {
|
|
14
|
+
hash: Schema.String,
|
|
15
|
+
variant: Schema.String
|
|
16
|
+
},
|
|
17
|
+
success: HttpApiSchema.StreamUint8Array()
|
|
18
|
+
})));
|
|
19
|
+
export { MediaApi };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=api.js.map
|