foldkit-media 0.1.0 → 0.2.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 +95 -58
- package/client.d.ts +2 -2
- package/dist/{asset-BNQ_j5tO.d.mts → asset-Dlkss5qp.d.mts} +32 -3
- package/dist/asset-Dlkss5qp.d.mts.map +1 -0
- package/dist/browser/index.d.mts +1 -1
- package/dist/browser/index.mjs +1 -1
- package/dist/cloudflare/index.d.mts +7 -6
- package/dist/cloudflare/index.d.mts.map +1 -1
- package/dist/cloudflare/index.mjs +11 -5
- package/dist/cloudflare/index.mjs.map +1 -1
- package/dist/{describe-DdYvLhMY.d.mts → describe-CivKHl4x.d.mts} +2 -2
- package/dist/{describe-DdYvLhMY.d.mts.map → describe-CivKHl4x.d.mts.map} +1 -1
- package/dist/{describe-Cqr63Gxa.mjs → describe-h9F5stgR.mjs} +5 -2
- package/dist/describe-h9F5stgR.mjs.map +1 -0
- package/dist/index.d.mts +10 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -1
- package/dist/{provider-DztvQjOr.d.mts → provider-g0Vlvlrb.d.mts} +19 -13
- package/dist/provider-g0Vlvlrb.d.mts.map +1 -0
- package/dist/server/index.d.mts +33 -15
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +172 -2
- package/dist/server/index.mjs.map +1 -1
- package/dist/{services-Ck-7dhIP.d.mts → services-8_h0ubLB.d.mts} +2 -2
- package/dist/{services-Ck-7dhIP.d.mts.map → services-8_h0ubLB.d.mts.map} +1 -1
- package/dist/sharp/index.d.mts +2 -2
- package/dist/sharp/index.mjs +1 -1
- package/dist/{upload-C5YM5jZR.mjs → stores-BtmSl8X3.mjs} +61 -203
- package/dist/stores-BtmSl8X3.mjs.map +1 -0
- package/dist/unpic/index.d.mts +1 -1
- package/dist/{upload-C4_inwfv.d.mts → upload-kp0_oK76.d.mts} +10 -10
- package/dist/{upload-C4_inwfv.d.mts.map → upload-kp0_oK76.d.mts.map} +1 -1
- package/dist/vite/index.mjs +3 -3
- package/dist/vite/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
- package/dist/describe-Cqr63Gxa.mjs.map +0 -1
- package/dist/provider-DztvQjOr.d.mts.map +0 -1
- package/dist/upload-C5YM5jZR.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -91,7 +91,9 @@ Option.map(picture, ({ img }) => img.srcset)
|
|
|
91
91
|
- **`Provider.hosted({ baseUrl?, space?, sources?, fallback?, quality? })`** —
|
|
92
92
|
this package's own server, for originals no CDN can fetch. A variant's URL is
|
|
93
93
|
`/_image/<sha-256>/w640.avif`: the original is named by its content hash, so
|
|
94
|
-
|
|
94
|
+
it is a `Provider<HashedAsset>`, and facts without `hash` are a type error
|
|
95
|
+
where the picture is derived. Decode stored facts with the `HashedAsset`
|
|
96
|
+
Schema (an upload answers one), or narrow with `isHashed`. The format is in the URL, so every
|
|
95
97
|
cache can key on it.
|
|
96
98
|
|
|
97
99
|
- **`detect(url, { widths?, sources?, fallback?, quality? })`** from
|
|
@@ -136,7 +138,7 @@ import hero from './hero.jpg?image'
|
|
|
136
138
|
import { Layout } from 'foldkit-media'
|
|
137
139
|
import { Image } from 'foldkit-mixins-ui'
|
|
138
140
|
|
|
139
|
-
Image.view({ ...hero, layout: Layout.Constrained({ width: 800 }), alt:
|
|
141
|
+
Image.view({ ...hero, layout: Layout.Constrained({ width: 800 }), alt: 'The finals' }, h)
|
|
140
142
|
```
|
|
141
143
|
|
|
142
144
|
The import is `{ asset, provider }`. The build measures the file once
|
|
@@ -244,13 +246,18 @@ A server makes only what its `Variant.space({ widths?, formats?, qualities?, rev
|
|
|
244
246
|
allows: the width ladder, a set of formats (AVIF and WebP by default) and a set
|
|
245
247
|
of qualities (none by default: no URL names one, and the encoder uses its own).
|
|
246
248
|
A request outside it is refused before any work, so an original has at most
|
|
247
|
-
`space.size` variants, whoever asks: 16 for `Variant.standard`.
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
249
|
+
`space.size` variants, whoever asks: 16 for `Variant.standard`. The server
|
|
250
|
+
reads its space from the provider the pages use, so the two cannot differ:
|
|
251
|
+
define `const media = Provider.hosted({ space })` once and give the same value
|
|
252
|
+
to `serveFetch`'s `images.provider` (or `layer({ provider })`). The provider
|
|
253
|
+
refuses, when defined, a format or quality its space does not make.
|
|
254
|
+
|
|
255
|
+
A variant's URL names the variant (the original's hash, a width, a format, a
|
|
256
|
+
quality), and what it answers is kept for a year under it. Nothing checks that
|
|
257
|
+
two makings of one variant give the same bytes, and an upgraded encoder may
|
|
258
|
+
not: the server cannot tell. So a change to what a variant is (the encoder's
|
|
259
|
+
settings, how it resizes) is a new `revision` of the space, which the
|
|
260
|
+
application bumps, never new bytes behind an old URL. `Variant.space({ revision: 1 })`
|
|
254
261
|
writes `w640.r1.avif`; revision 0, the default, writes no revision, so every
|
|
255
262
|
URL written before revisions keeps its spelling. A server of revision 2 still
|
|
256
263
|
answers what earlier ones wrote: an earlier revision's variant while its store
|
|
@@ -270,6 +277,10 @@ a 400; one well formed but outside this space (a width off the ladder) is a
|
|
|
270
277
|
and not at all by a browser, since another release, the next one in a
|
|
271
278
|
rollout, or the same one configured otherwise, may answer it.
|
|
272
279
|
|
|
280
|
+
The route checks no permission: anyone holding a variant's URL can read it. A content
|
|
281
|
+
hash cannot be guessed, but every page that shows the image hands it out, so
|
|
282
|
+
an original that must stay private does not belong on this server.
|
|
283
|
+
|
|
273
284
|
It needs three services, each a Layer you choose per host:
|
|
274
285
|
|
|
275
286
|
| Service | Job | Kind |
|
|
@@ -289,7 +300,7 @@ cannot be built, is the framework's own `500`, with none of them.
|
|
|
289
300
|
|
|
290
301
|
| Answer | Status | `Cache-Control` |
|
|
291
302
|
| --- | --- | --- |
|
|
292
|
-
| A variant (`ETag: "<hash>/<spelling>"`) | 200 | `public, max-age=31536000, immutable`: the path names the
|
|
303
|
+
| A variant (`ETag: "<hash>/<spelling>"`) | 200 | `public, max-age=31536000, immutable`: the path names the variant, and a new way of making it is a new revision |
|
|
293
304
|
| A request already holding it (`If-None-Match`) | 304 | the same; the store is not read |
|
|
294
305
|
| A URL outside this release's grammar | 400 | `no-store`, and `CDN-Cache-Control: public, max-age=60`: a later release may read it (a new format) |
|
|
295
306
|
| A well-formed URL outside this space | 404 | the same: a later release may offer it |
|
|
@@ -306,11 +317,15 @@ cross-origin` and `Timing-Allow-Origin: *`, and a variant says where it came
|
|
|
306
317
|
from in `Server-Timing` (`edge`, `store` or `made`). Nothing sends `Vary`: the
|
|
307
318
|
format is in the URL.
|
|
308
319
|
|
|
309
|
-
- `serveFetch({
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
320
|
+
- `serveFetch({ images?, uploads?, otherwise? })` is a Worker's fetch handler.
|
|
321
|
+
It owns `/_image/` and `/_media/`: `images` (`{ provider?, maxBytes?, layer }`)
|
|
322
|
+
serves the variants, `uploads` (below) the upload route, each with its
|
|
323
|
+
services built from the request's bindings once per environment. Anything
|
|
324
|
+
else under those two prefixes, a route it was not given or a preflight, is a
|
|
325
|
+
404, and every other path goes to `otherwise` (a 404 without one), so the
|
|
326
|
+
application's own routes need not know the media paths.
|
|
327
|
+
- `layer({ provider?, maxBytes?, coalesce? })` is the route as an Effect
|
|
328
|
+
`HttpRouter` layer, for a Node server beside other routes.
|
|
314
329
|
- `variantsNone` keeps nothing, for a host with a cache of its own in front.
|
|
315
330
|
|
|
316
331
|
### Stores
|
|
@@ -402,41 +417,41 @@ through `POST /_media/upload`: the bytes are the body, with an `image/*`
|
|
|
402
417
|
`Content-Type`. The route reads at most `maxBytes` (20 MB by default) as the
|
|
403
418
|
body streams, reads its facts through the `Inspector`, keeps the bytes under
|
|
404
419
|
their SHA-256 in `Uploads` (where `Originals` reads them), and answers the
|
|
405
|
-
facts as
|
|
420
|
+
facts as a `HashedAsset`, keyed by that hash, with a `201`. The variant server
|
|
406
421
|
serves it at once. Only the facts go on to the application's data (a CMS's
|
|
407
|
-
asset row); the bytes never travel through RPC.
|
|
422
|
+
asset row); the bytes never travel through RPC. The answer is the server's
|
|
423
|
+
reading of the bytes, but once it has passed through a client it is the
|
|
424
|
+
client's word: a client can change a width or name another original's hash.
|
|
425
|
+
Decoding with `HashedAsset` checks the facts' shape, not that they are true,
|
|
426
|
+
so store facts your server read, not ones a client sends back.
|
|
408
427
|
|
|
409
428
|
Who may upload is the application's to say, and the route has no default:
|
|
410
|
-
`UploadPolicy` is asked before a byte is read.
|
|
429
|
+
`UploadPolicy` is asked before a byte is read. `uploadPolicyBearer(secret)` is
|
|
430
|
+
the one for a deployment's secret: it admits `Authorization: Bearer <secret>`,
|
|
431
|
+
compared by digest so the time taken says nothing of the secret, and admits
|
|
432
|
+
nobody while the secret is unset or empty. Who may upload by session is a
|
|
433
|
+
policy of your own (`Layer.succeed(UploadPolicy, { admit })`, a `foldkit-guard`
|
|
434
|
+
check).
|
|
411
435
|
|
|
412
436
|
```ts
|
|
413
|
-
import {
|
|
414
|
-
import {
|
|
415
|
-
UploadForbidden,
|
|
416
|
-
UploadPolicy,
|
|
417
|
-
uploadLayer,
|
|
418
|
-
uploadsKeyValueStore,
|
|
419
|
-
} from 'foldkit-media/server'
|
|
437
|
+
import { Layer } from 'effect'
|
|
438
|
+
import { uploadLayer, uploadPolicyBearer, uploadsKeyValueStore } from 'foldkit-media/server'
|
|
420
439
|
import { inspectorSharp } from 'foldkit-media/sharp'
|
|
421
440
|
|
|
422
|
-
// The application's own secret or session check; compare a secret in constant time.
|
|
423
|
-
declare const token: string
|
|
424
|
-
|
|
425
|
-
const editors = Layer.succeed(UploadPolicy, {
|
|
426
|
-
admit: request =>
|
|
427
|
-
request.headers['authorization'] === `Bearer ${token}`
|
|
428
|
-
? Effect.void
|
|
429
|
-
: Effect.fail(new UploadForbidden({})),
|
|
430
|
-
})
|
|
431
|
-
|
|
432
441
|
const uploads = uploadLayer({ maxBytes: 10 * 1024 * 1024 }).pipe(
|
|
433
|
-
Layer.provide(
|
|
442
|
+
Layer.provide(
|
|
443
|
+
Layer.mergeAll(
|
|
444
|
+
uploadsKeyValueStore(),
|
|
445
|
+
inspectorSharp(),
|
|
446
|
+
uploadPolicyBearer(process.env['UPLOAD_TOKEN']),
|
|
447
|
+
),
|
|
448
|
+
),
|
|
434
449
|
)
|
|
435
450
|
```
|
|
436
451
|
|
|
437
452
|
`uploadsKeyValueStore()` keeps them where `originalsKeyValueStore()` reads,
|
|
438
453
|
over the same `KeyValueStore`; on Cloudflare, `uploadsR2(bucket)` beside
|
|
439
|
-
`originalsR2(bucket)`, and `
|
|
454
|
+
`originalsR2(bucket)`, and `serveFetch`'s `uploads` hosts the route in a
|
|
440
455
|
Worker. A refusal answers its kind and nothing more, and no browser keeps it:
|
|
441
456
|
`403` from the policy, `415` for a body that is not `image/*` or not an image
|
|
442
457
|
the inspector reads, `413` past `maxBytes` or the inspector's pixel limit, and
|
|
@@ -462,12 +477,14 @@ them as files at their own paths, for `foldkit-ssr`'s `staticSite` `emit`:
|
|
|
462
477
|
|
|
463
478
|
```ts
|
|
464
479
|
const media = serveFetch<object>({
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
Layer.
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
480
|
+
images: {
|
|
481
|
+
layer: () =>
|
|
482
|
+
Layer.mergeAll(transformerSharp(), originalsKeyValueStore(), variantsKeyValueStore()).pipe(
|
|
483
|
+
Layer.provide(KeyValueStore.layerFileSystem('.media')),
|
|
484
|
+
// The disk itself: Node's file system and paths.
|
|
485
|
+
Layer.provide(NodeServices.layer),
|
|
486
|
+
),
|
|
487
|
+
},
|
|
471
488
|
})
|
|
472
489
|
const env = {}
|
|
473
490
|
|
|
@@ -494,17 +511,33 @@ export const site = {
|
|
|
494
511
|
|
|
495
512
|
### On Cloudflare
|
|
496
513
|
|
|
497
|
-
`foldkit-media/cloudflare` gives the
|
|
514
|
+
`foldkit-media/cloudflare` gives the services from a Worker's bindings, and
|
|
515
|
+
`serveFetch` is the Worker:
|
|
498
516
|
|
|
499
517
|
```ts
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
})
|
|
518
|
+
export default {
|
|
519
|
+
fetch: serveFetch<WorkerEnv>({
|
|
520
|
+
images: {
|
|
521
|
+
layer: env =>
|
|
522
|
+
Layer.mergeAll(
|
|
523
|
+
originalsR2(env.MEDIA),
|
|
524
|
+
transformerImages(env.IMAGES),
|
|
525
|
+
variantsR2(env.MEDIA, { cache: true }),
|
|
526
|
+
admissionRateLimit(env.LIMITER),
|
|
527
|
+
),
|
|
528
|
+
},
|
|
529
|
+
uploads: {
|
|
530
|
+
layer: env =>
|
|
531
|
+
Layer.mergeAll(
|
|
532
|
+
uploadsR2(env.MEDIA),
|
|
533
|
+
inspectorImages(env.IMAGES),
|
|
534
|
+
uploadPolicyBearer(env.UPLOAD_TOKEN),
|
|
535
|
+
),
|
|
536
|
+
},
|
|
537
|
+
// The application's own routes.
|
|
538
|
+
otherwise: async () => new Response('Not found', { status: 404 }),
|
|
539
|
+
}),
|
|
540
|
+
}
|
|
508
541
|
```
|
|
509
542
|
|
|
510
543
|
- `transformerImages(images)` is the Images binding: it scales down, never up,
|
|
@@ -514,15 +547,19 @@ const answerImages = serveFetch<WorkerEnv>({
|
|
|
514
547
|
store adapters above or the application's own (`clear` and `size` list the
|
|
515
548
|
bucket).
|
|
516
549
|
- `variantsR2(bucket, { prefix?, cache? })` is `variantsKeyValueStore` over
|
|
517
|
-
it, so a variant made last month is not made, and billed, again
|
|
518
|
-
|
|
550
|
+
it, so a variant made last month is not made, and billed, again. Two misses
|
|
551
|
+
for one variant at the same moment both make it, since a Worker request
|
|
552
|
+
cannot wait on another's; with
|
|
553
|
+
`cache`, the Cache API is read first and filled from R2: `true` for the
|
|
554
|
+
Worker's `caches.default`, or a cache of your own (`await caches.open(…)`).
|
|
555
|
+
`true` outside a Worker throws where the layer is made.
|
|
519
556
|
- `originalsR2(bucket)` streams an original rather than reading it into
|
|
520
557
|
memory, unlike the general adapter.
|
|
521
558
|
|
|
522
559
|
Cloudflare bills each new width of each original once a month (format and
|
|
523
560
|
quality do not count), so the ladder is the cost: eight widths are at most
|
|
524
|
-
eight transformations an original. `examples/cloudflare`
|
|
525
|
-
|
|
561
|
+
eight transformations an original. `examples/cloudflare` is such a Worker,
|
|
562
|
+
with Remote and Sync as its `otherwise`.
|
|
526
563
|
|
|
527
564
|
## Icons
|
|
528
565
|
|
|
@@ -557,8 +594,8 @@ A view draws an icon with `Icon.draw(icon, h)`: inline SVG through the view's
|
|
|
557
594
|
builder (Foldkit's `h`, or anything of its shape, `SvgBuilder`), every
|
|
558
595
|
attribute in the server's markup, `1em` square unless `size` is given, and
|
|
559
596
|
`aria-hidden`, since the control it sits in carries the name.
|
|
560
|
-
`foldkit-mixins-ui`'s `Icon.view
|
|
561
|
-
it when given a `label`. A style masks with `Icon.maskUrl(icon)`, a CSS `url()`.
|
|
597
|
+
`foldkit-mixins-ui`'s `Icon.view({ icon, label? })` draws it into its glyph,
|
|
598
|
+
sized by the recipe, and names it when given a `label`. A style masks with `Icon.maskUrl(icon)`, a CSS `url()`.
|
|
562
599
|
|
|
563
600
|
Every icon is parsed against a presentational allowlist, because it is drawn
|
|
564
601
|
inline. The parse refuses, naming the icon, an element or attribute outside
|
package/client.d.ts
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* `images` plugin: add `"foldkit-media/client"` to the tsconfig's `types`.
|
|
4
4
|
*/
|
|
5
5
|
declare module '*?image' {
|
|
6
|
-
import type {
|
|
6
|
+
import type { HashedAsset, Provider } from 'foldkit-media'
|
|
7
7
|
|
|
8
|
-
const image: { readonly asset:
|
|
8
|
+
const image: { readonly asset: HashedAsset; readonly provider: Provider.Provider }
|
|
9
9
|
export default image
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
2
|
//#region src/asset.d.ts
|
|
3
3
|
/** What stands in an image's place until it loads. */
|
|
4
4
|
declare const Placeholder: Schema.TaggedUnion<{
|
|
@@ -46,6 +46,35 @@ declare const ImageAsset: Schema.Struct<{
|
|
|
46
46
|
}>>;
|
|
47
47
|
}>;
|
|
48
48
|
type ImageAsset = typeof ImageAsset.Type;
|
|
49
|
+
/**
|
|
50
|
+
* Facts that name the original by its content hash: what a build or an upload
|
|
51
|
+
* answers, and what `Provider.hosted` needs to write a URL.
|
|
52
|
+
*/
|
|
53
|
+
type HashedAsset = ImageAsset & {
|
|
54
|
+
readonly hash: Option.Some<string>;
|
|
55
|
+
};
|
|
56
|
+
declare const isHashed: (asset: ImageAsset) => asset is HashedAsset;
|
|
57
|
+
/** `ImageAsset`, refusing facts with no content hash. */
|
|
58
|
+
declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
|
|
59
|
+
readonly key: Schema.String;
|
|
60
|
+
readonly width: Schema.Int;
|
|
61
|
+
readonly height: Schema.Int;
|
|
62
|
+
readonly alpha: Schema.Boolean;
|
|
63
|
+
readonly hash: Schema.OptionFromNullOr<Schema.String>;
|
|
64
|
+
readonly placeholder: Schema.OptionFromNullOr<Schema.TaggedUnion<{
|
|
65
|
+
readonly Color: Schema.TaggedStruct<"Color", {
|
|
66
|
+
readonly value: Schema.String;
|
|
67
|
+
}>;
|
|
68
|
+
readonly LowRes: Schema.TaggedStruct<"LowRes", {}>;
|
|
69
|
+
readonly ThumbHash: Schema.TaggedStruct<"ThumbHash", {
|
|
70
|
+
readonly hash: Schema.String;
|
|
71
|
+
}>;
|
|
72
|
+
}>>;
|
|
73
|
+
readonly focus: Schema.OptionFromOptionalNullOr<Schema.Struct<{
|
|
74
|
+
readonly x: Schema.Finite;
|
|
75
|
+
readonly y: Schema.Finite;
|
|
76
|
+
}>>;
|
|
77
|
+
}>>;
|
|
49
78
|
//#endregion
|
|
50
|
-
export {
|
|
51
|
-
//# sourceMappingURL=asset-
|
|
79
|
+
export { isHashed as a, Placeholder as i, HashedAsset as n, ImageAsset as r, Focus as t };
|
|
80
|
+
//# sourceMappingURL=asset-Dlkss5qp.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"asset-Dlkss5qp.d.mts","names":[],"sources":["../src/asset.ts"],"mappings":";;;cAuCa,aAAW,OAAA;;;;;;;;;KAYZ,qBAAqB,YAAY;;cAOhC,OAAK,OAAA;;;;KACN,eAAe,MAAM;;;;;;;;;cAUpB,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;KASX,oBAAoB,WAAW;;;;;KAM/B,cAAc;WAAwB,MAAM,OAAO;;cAElD,WAAQ,OAAW,eAAa,SAAS;;cAGzC,aAAW,OAAA,OAAA,aAAA,OAAA"}
|
package/dist/browser/index.d.mts
CHANGED
package/dist/browser/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Inspector } from "../describe-
|
|
1
|
+
import { t as Inspector } from "../describe-h9F5stgR.mjs";
|
|
2
2
|
import { t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
|
|
3
3
|
import { i as TransformFailed, n as OriginalTooLarge } from "../errors-qETj7Pgi.mjs";
|
|
4
4
|
import { Effect, Layer, Option } from "effect";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as Inspector } from "../describe-
|
|
2
|
-
import { a as Uploads, p as Admission } from "../upload-
|
|
3
|
-
import { a as Transformer, i as Originals, o as Variants } from "../services-
|
|
1
|
+
import { n as Inspector } from "../describe-CivKHl4x.mjs";
|
|
2
|
+
import { a as Uploads, p as Admission } from "../upload-kp0_oK76.mjs";
|
|
3
|
+
import { a as Transformer, i as Originals, o as Variants } from "../services-8_h0ubLB.mjs";
|
|
4
4
|
import { Layer } from "effect";
|
|
5
5
|
import { KeyValueStore } from "effect/persistence";
|
|
6
6
|
import { Cache as Cache$1, ImagesBinding, R2Bucket, RateLimit } from "@cloudflare/workers-types";
|
|
@@ -23,12 +23,13 @@ export declare const transformerImages: (images: ImagesBinding) => Layer.Layer<T
|
|
|
23
23
|
export declare const keyValueStoreR2: (bucket: R2Bucket) => Layer.Layer<KeyValueStore.KeyValueStore>;
|
|
24
24
|
/**
|
|
25
25
|
* Variants kept in R2 under `prefix`, so one made last month is not made, and
|
|
26
|
-
* billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache
|
|
27
|
-
*
|
|
26
|
+
* billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,
|
|
27
|
+
* the Cache API stands in front of it: `true` for the Worker's
|
|
28
|
+
* `caches.default`, or a cache of your own (`await caches.open(…)`).
|
|
28
29
|
*/
|
|
29
30
|
export declare const variantsR2: (bucket: R2Bucket, options?: {
|
|
30
31
|
readonly prefix?: string;
|
|
31
|
-
readonly cache?: Cache$1;
|
|
32
|
+
readonly cache?: Cache$1 | true;
|
|
32
33
|
}) => Layer.Layer<Variants>;
|
|
33
34
|
/**
|
|
34
35
|
* Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["Cache"],"sources":["../../src/cloudflare/index.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["Cache"],"sources":["../../src/cloudflare/index.ts"],"mappings":";;;;;;;;qBAuBa,cAAW,QAAY,aAAW,MAAM,MAAM;;qBAiB9C,YAAS,QAAY,aAAW,MAAM,MAAM;;;;;;qBAgB5C,oBAAiB,QAAY,kBAAgB,MAAM,MAAM;;;;;;qBAsCzD,kBAAe,QAAY,aAAW,MAAM,MAAM,cAAc;;;;;;;qBA2HhE,aAAU,QACb,UAAQ;WACI;WAA0B,QAAQA;MACrD,MAAM,MAAM;;;;;;;qBAiBF,qBAAkB,SACpB,WAAS;WACE;MACnB,MAAM,MAAM;;;;;;;;;;qBA0BF,kBAAe,QAAY,kBAAgB,MAAM,MAAM"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as Inspector } from "../describe-
|
|
1
|
+
import { t as Inspector } from "../describe-h9F5stgR.mjs";
|
|
2
2
|
import { i as TransformFailed, r as QuotaExhausted, t as OriginalNotFound } from "../errors-qETj7Pgi.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { h as RateLimited, m as Admission, s as Uploads, t as makeVariants } from "../stores-BtmSl8X3.mjs";
|
|
4
4
|
import { n as Transformer, r as Variants, t as Originals } from "../services-BeakQl7F.mjs";
|
|
5
5
|
import { Effect, Layer, Option } from "effect";
|
|
6
6
|
import { KeyValueStore } from "effect/persistence";
|
|
@@ -114,16 +114,22 @@ const withEdge = (behind, edge) => {
|
|
|
114
114
|
put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded)))
|
|
115
115
|
};
|
|
116
116
|
};
|
|
117
|
+
const cacheOf = (cache) => {
|
|
118
|
+
if (cache !== true) return cache;
|
|
119
|
+
if (typeof caches === "undefined") throw new Error("variantsR2: `cache: true` reads the Worker global `caches.default`, which this runtime lacks");
|
|
120
|
+
return caches.default;
|
|
121
|
+
};
|
|
117
122
|
/**
|
|
118
123
|
* Variants kept in R2 under `prefix`, so one made last month is not made, and
|
|
119
|
-
* billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache
|
|
120
|
-
*
|
|
124
|
+
* billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,
|
|
125
|
+
* the Cache API stands in front of it: `true` for the Worker's
|
|
126
|
+
* `caches.default`, or a cache of your own (`await caches.open(…)`).
|
|
121
127
|
*/
|
|
122
128
|
const variantsR2 = (bucket, options = {}) => {
|
|
123
129
|
const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? "variants/"));
|
|
124
130
|
return Layer.succeed(Variants, Option.match(Option.fromNullishOr(options.cache), {
|
|
125
131
|
onNone: () => kept,
|
|
126
|
-
onSome: (
|
|
132
|
+
onSome: (cache) => withEdge(kept, cacheOf(cache))
|
|
127
133
|
}));
|
|
128
134
|
};
|
|
129
135
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["/**\n * The media server's services on Cloudflare: originals in R2, the Images\n * binding as the transformer, and variants kept in R2 behind the Cache API.\n * Each takes the binding it needs, so build them in `serveFetch`'s `layer`\n * from the request's environment.\n */\nimport type { Cache, ImagesBinding, R2Bucket, RateLimit } from '@cloudflare/workers-types'\nimport { Effect, Layer, Option } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Admission, RateLimited } from '../server/admission.js'\nimport { Inspector } from '../describe.js'\nimport { OriginalNotFound, QuotaExhausted, TransformFailed } from '../server/errors.js'\nimport { Originals, Transformer, Variants, type Encoded, type Kept } from '../server/services.js'\nimport { Uploads } from '../server/upload.js'\nimport { makeVariants } from '../server/stores.js'\n\n/** Originals in an R2 bucket, each under its content hash. */\nexport const originalsR2 = (bucket: R2Bucket): Layer.Layer<Originals> =>\n Layer.succeed(Originals, {\n get: hash =>\n Effect.promise(() => bucket.get(hash)).pipe(\n Effect.flatMap(object =>\n object === null\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n // The two runtimes' stream types differ only in their declarations.\n body: object.body as unknown as ReadableStream<Uint8Array>,\n size: object.size,\n }),\n ),\n ),\n })\n\n/** Uploads into an R2 bucket, each under its content hash: what `originalsR2` reads. */\nexport const uploadsR2 = (bucket: R2Bucket): Layer.Layer<Uploads> =>\n Layer.succeed(Uploads, {\n put: (hash, bytes) => Effect.promise(() => bucket.put(hash, bytes)).pipe(Effect.asVoid),\n })\n\n// Cloudflare's code for a spent transformation allowance.\nconst QUOTA_EXHAUSTED = 9422\n\nconst isImagesError = (cause: unknown): cause is { readonly code: number } =>\n typeof cause === 'object' && cause !== null && typeof Reflect.get(cause, 'code') === 'number'\n\n/**\n * The Images binding as the transformer. It scales down, never up, and names\n * the format, so the variant is what its URL says. A spent allowance is\n * `QuotaExhausted`; any other refusal is `TransformFailed`, its reason logged.\n */\nexport const transformerImages = (images: ImagesBinding): Layer.Layer<Transformer> =>\n Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.tryPromise({\n try: async () => {\n const result = await images\n .input(original.body as unknown as Parameters<ImagesBinding['input']>[0])\n .transform({ width: variant.width, fit: 'scale-down' })\n .output({\n format: `image/${variant.format}`,\n ...Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n })\n const response = result.response()\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: result.contentType(),\n }\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch((cause): Effect.Effect<never, QuotaExhausted | TransformFailed> =>\n isImagesError(cause) && cause.code === QUOTA_EXHAUSTED\n ? Effect.fail(new QuotaExhausted({}))\n : Effect.logWarning('Media.transform failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n\n/**\n * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by\n * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the\n * application's own. `clear` and `size` list the whole bucket.\n */\nexport const keyValueStoreR2 = (bucket: R2Bucket): Layer.Layer<KeyValueStore.KeyValueStore> =>\n Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket))\n\nconst r2Store = (bucket: R2Bucket): KeyValueStore.KeyValueStore => {\n const attempt = <A>(method: string, key: string | undefined, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: cause =>\n new KeyValueStore.KeyValueStoreError({\n message: `R2 ${method} failed`,\n method,\n ...(key === undefined ? {} : { key }),\n cause,\n }),\n })\n // Every key in the bucket, a page of listing at a time.\n const keys = async () => {\n const found: Array<string> = []\n let cursor: string | undefined\n do {\n const page = await bucket.list(cursor === undefined ? {} : { cursor })\n found.push(...page.objects.map(object => object.key))\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor !== undefined)\n return found\n }\n return KeyValueStore.make({\n get: key => attempt('get', key, async () => (await bucket.get(key))?.text()),\n getUint8Array: key =>\n attempt('getUint8Array', key, async () => {\n const object = await bucket.get(key)\n return object === null ? undefined : new Uint8Array(await object.arrayBuffer())\n }),\n set: (key, value) => attempt('set', key, async () => void (await bucket.put(key, value))),\n remove: key => attempt('remove', key, () => bucket.delete(key)),\n clear: attempt('clear', undefined, async () => {\n const all = await keys()\n // R2 deletes at most 1,000 keys a call.\n for (let at = 0; at < all.length; at += 1000) await bucket.delete(all.slice(at, at + 1000))\n }),\n size: attempt('size', undefined, async () => (await keys()).length),\n })\n}\n\n// The Cache API keys by request; this origin is never fetched.\nconst edgeKey = (key: string) => `https://foldkit-media.invalid/${key}`\n\n/**\n * Variants with the edge's Cache API in front: read there first, and filled\n * from what is kept behind it, so a popular variant is served from the edge.\n */\nconst withEdge = (behind: Variants['Service'], edge: Cache): Variants['Service'] => {\n const fill = (key: string, encoded: Encoded) =>\n Effect.tryPromise({\n try: () =>\n edge.put(\n edgeKey(key),\n // The page's Response and workers-types' differ only in their declarations.\n new Response(encoded.bytes, {\n headers: {\n 'content-type': encoded.contentType,\n 'cache-control': 'public, max-age=31536000, immutable',\n },\n }) as never,\n ),\n catch: cause => cause,\n }).pipe(Effect.catch(cause => Effect.logWarning('Media: the edge cache failed a write', cause)))\n const behindEdge = (key: string) =>\n behind.get(key).pipe(\n Effect.tap(found =>\n Option.match(found, {\n onNone: () => Effect.void,\n onSome: kept => fill(key, kept.encoded),\n }),\n ),\n )\n return {\n get: key =>\n Effect.tryPromise({\n try: async () => {\n const hit = await edge.match(edgeKey(key))\n return hit === undefined\n ? Option.none<Kept>()\n : Option.some({\n encoded: {\n bytes: new Uint8Array(await hit.arrayBuffer()),\n contentType: hit.headers.get('content-type') ?? 'application/octet-stream',\n },\n from: 'edge' as const,\n })\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Effect.logWarning('Media: the edge cache failed a read', cause).pipe(\n Effect.as(Option.none<Kept>()),\n ),\n ),\n Effect.flatMap(found => (Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),\n ),\n put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded))),\n }\n}\n\n/**\n * Variants kept in R2 under `prefix`, so one made last month is not made, and\n * billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`\n * (`caches.default`), the Cache API stands in front of it.\n */\nexport const variantsR2 = (\n bucket: R2Bucket,\n options: { readonly prefix?: string; readonly cache?: Cache } = {},\n): Layer.Layer<Variants> => {\n const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? 'variants/'))\n return Layer.succeed(\n Variants,\n Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => kept,\n onSome: edge => withEdge(kept, edge),\n }),\n )\n}\n\n/**\n * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose\n * limit and period are its configuration. It answers yes or no, not when, so\n * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60\n * by default). A binding that fails admits the request, logged.\n */\nexport const admissionRateLimit = (\n binding: RateLimit,\n options: { readonly retryAfterSeconds?: number } = {},\n): Layer.Layer<Admission> =>\n Layer.succeed(Admission, {\n admit: client =>\n Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(\n Effect.catch(error =>\n Effect.logWarning('Media: the rate limit binding failed; admitting', error).pipe(\n Effect.as({ success: true }),\n ),\n ),\n Effect.flatMap(({ success }) =>\n success\n ? Effect.void\n : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })),\n ),\n ),\n })\n\n/**\n * The `Inspector` through the Images binding: an original's size from `info`,\n * which costs no transformation. It makes no thumbnail, since raw pixels are\n * not offered offline and could not be tested, so an original described here\n * has no ThumbHash; and as `info` does not say whether pixels are\n * transparent, every format but JPEG is taken to be, which costs a\n * placeholder, never shows a wrong one. An SVG, which has no size in pixels,\n * is refused.\n */\nexport const inspectorImages = (images: ImagesBinding): Layer.Layer<Inspector> =>\n Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.tryPromise({\n try: () =>\n images.info(\n new Blob([bytes]).stream() as unknown as Parameters<ImagesBinding['info']>[0],\n ),\n catch: cause => cause,\n }).pipe(\n Effect.flatMap(info =>\n // An SVG's answer has no width: it has no size in pixels.\n 'width' in info\n ? Effect.succeed({\n width: info.width,\n height: info.height,\n alpha: info.format !== 'image/jpeg',\n thumbnail: Option.none(),\n })\n : Effect.fail(info),\n ),\n Effect.catch(cause =>\n Effect.logWarning('Media.inspect failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n"],"mappings":";;;;;;;;AAiBA,MAAa,eAAe,WAC1B,MAAM,QAAQ,WAAW,EACvB,MAAK,SACH,OAAO,cAAc,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,KACrC,OAAO,SAAQ,WACb,WAAW,OACP,OAAO,KAAK,IAAI,iBAAiB,EAAE,KAAK,CAAC,CAAC,IAC1C,OAAO,QAAQ;CAEb,MAAM,OAAO;CACb,MAAM,OAAO;AACf,CAAC,CACP,CACF,EACJ,CAAC;;AAGH,MAAa,aAAa,WACxB,MAAM,QAAQ,SAAS,EACrB,MAAM,MAAM,UAAU,OAAO,cAAc,OAAO,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,EACxF,CAAC;AAGH,MAAM,kBAAkB;AAExB,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM;;;;;;AAOvF,MAAa,qBAAqB,WAChC,MAAM,QAAQ,aAAa,EACzB,YAAY,UAAU,YACpB,OAAO,WAAW;CAChB,KAAK,YAAY;EACf,MAAM,SAAS,MAAM,OAClB,MAAM,SAAS,IAAwD,CAAC,CACxE,UAAU;GAAE,OAAO,QA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CAAC,CAC7B,CACF,GACA,OAAO,SAAS,EAAE,cAChB,UACI,OAAO,OACP,OAAO,KAAK,IAAI,YAAY,EAAE,mBAAmB,QAAQ,qBAAqB,GAAG,CAAC,CAAC,CACzF,CACF,EACJ,CAAC;;;;;;;;;;AAWH,MAAa,mBAAmB,WAC9B,MAAM,QAAQ,WAAW,EACvB,UAAS,UACP,OAAO,WAAW;CAChB,WACE,OAAO,KACL,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAC3B;CACF,QAAO,UAAS;AAClB,CAAC,CAAC,CAAC,KACD,OAAO,SAAQ,SAEb,WAAW,OACP,OAAO,QAAQ;CACb,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,OAAO,KAAK,WAAW;CACvB,WAAW,OAAO,KAAK;AACzB,CAAC,IACD,OAAO,KAAK,IAAI,CACtB,GACA,OAAO,OAAM,UACX,OAAO,WAAW,wBAAwB,KAAK,CAAC,CAAC,KAC/C,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD,CACF,CACF,EACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["/**\n * The media server's services on Cloudflare: originals in R2, the Images\n * binding as the transformer, and variants kept in R2 behind the Cache API.\n * Each takes the binding it needs, so build them in `serveFetch`'s `layer`\n * from the request's environment.\n */\nimport type {\n Cache,\n CacheStorage,\n ImagesBinding,\n R2Bucket,\n RateLimit,\n} from '@cloudflare/workers-types'\nimport { Effect, Layer, Option } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Admission, RateLimited } from '../server/admission.js'\nimport { Inspector } from '../describe.js'\nimport { OriginalNotFound, QuotaExhausted, TransformFailed } from '../server/errors.js'\nimport { Originals, Transformer, Variants, type Encoded, type Kept } from '../server/services.js'\nimport { Uploads } from '../server/upload.js'\nimport { makeVariants } from '../server/stores.js'\n\n/** Originals in an R2 bucket, each under its content hash. */\nexport const originalsR2 = (bucket: R2Bucket): Layer.Layer<Originals> =>\n Layer.succeed(Originals, {\n get: hash =>\n Effect.promise(() => bucket.get(hash)).pipe(\n Effect.flatMap(object =>\n object === null\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n // The two runtimes' stream types differ only in their declarations.\n body: object.body as unknown as ReadableStream<Uint8Array>,\n size: object.size,\n }),\n ),\n ),\n })\n\n/** Uploads into an R2 bucket, each under its content hash: what `originalsR2` reads. */\nexport const uploadsR2 = (bucket: R2Bucket): Layer.Layer<Uploads> =>\n Layer.succeed(Uploads, {\n put: (hash, bytes) => Effect.promise(() => bucket.put(hash, bytes)).pipe(Effect.asVoid),\n })\n\n// Cloudflare's code for a spent transformation allowance.\nconst QUOTA_EXHAUSTED = 9422\n\nconst isImagesError = (cause: unknown): cause is { readonly code: number } =>\n typeof cause === 'object' && cause !== null && typeof Reflect.get(cause, 'code') === 'number'\n\n/**\n * The Images binding as the transformer. It scales down, never up, and names\n * the format, so the variant is what its URL says. A spent allowance is\n * `QuotaExhausted`; any other refusal is `TransformFailed`, its reason logged.\n */\nexport const transformerImages = (images: ImagesBinding): Layer.Layer<Transformer> =>\n Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.tryPromise({\n try: async () => {\n const result = await images\n .input(original.body as unknown as Parameters<ImagesBinding['input']>[0])\n .transform({ width: variant.width, fit: 'scale-down' })\n .output({\n format: `image/${variant.format}`,\n ...Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n })\n const response = result.response()\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: result.contentType(),\n }\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch((cause): Effect.Effect<never, QuotaExhausted | TransformFailed> =>\n isImagesError(cause) && cause.code === QUOTA_EXHAUSTED\n ? Effect.fail(new QuotaExhausted({}))\n : Effect.logWarning('Media.transform failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n\n/**\n * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by\n * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the\n * application's own. `clear` and `size` list the whole bucket.\n */\nexport const keyValueStoreR2 = (bucket: R2Bucket): Layer.Layer<KeyValueStore.KeyValueStore> =>\n Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket))\n\nconst r2Store = (bucket: R2Bucket): KeyValueStore.KeyValueStore => {\n const attempt = <A>(method: string, key: string | undefined, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: cause =>\n new KeyValueStore.KeyValueStoreError({\n message: `R2 ${method} failed`,\n method,\n ...(key === undefined ? {} : { key }),\n cause,\n }),\n })\n // Every key in the bucket, a page of listing at a time.\n const keys = async () => {\n const found: Array<string> = []\n let cursor: string | undefined\n do {\n const page = await bucket.list(cursor === undefined ? {} : { cursor })\n found.push(...page.objects.map(object => object.key))\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor !== undefined)\n return found\n }\n return KeyValueStore.make({\n get: key => attempt('get', key, async () => (await bucket.get(key))?.text()),\n getUint8Array: key =>\n attempt('getUint8Array', key, async () => {\n const object = await bucket.get(key)\n return object === null ? undefined : new Uint8Array(await object.arrayBuffer())\n }),\n set: (key, value) => attempt('set', key, async () => void (await bucket.put(key, value))),\n remove: key => attempt('remove', key, () => bucket.delete(key)),\n clear: attempt('clear', undefined, async () => {\n const all = await keys()\n // R2 deletes at most 1,000 keys a call.\n for (let at = 0; at < all.length; at += 1000) await bucket.delete(all.slice(at, at + 1000))\n }),\n size: attempt('size', undefined, async () => (await keys()).length),\n })\n}\n\n// The Cache API keys by request; this origin is never fetched.\nconst edgeKey = (key: string) => `https://foldkit-media.invalid/${key}`\n\n/**\n * Variants with the edge's Cache API in front: read there first, and filled\n * from what is kept behind it, so a popular variant is served from the edge.\n */\nconst withEdge = (behind: Variants['Service'], edge: Cache): Variants['Service'] => {\n const fill = (key: string, encoded: Encoded) =>\n Effect.tryPromise({\n try: () =>\n edge.put(\n edgeKey(key),\n // The page's Response and workers-types' differ only in their declarations.\n new Response(encoded.bytes, {\n headers: {\n 'content-type': encoded.contentType,\n 'cache-control': 'public, max-age=31536000, immutable',\n },\n }) as never,\n ),\n catch: cause => cause,\n }).pipe(Effect.catch(cause => Effect.logWarning('Media: the edge cache failed a write', cause)))\n const behindEdge = (key: string) =>\n behind.get(key).pipe(\n Effect.tap(found =>\n Option.match(found, {\n onNone: () => Effect.void,\n onSome: kept => fill(key, kept.encoded),\n }),\n ),\n )\n return {\n get: key =>\n Effect.tryPromise({\n try: async () => {\n const hit = await edge.match(edgeKey(key))\n return hit === undefined\n ? Option.none<Kept>()\n : Option.some({\n encoded: {\n bytes: new Uint8Array(await hit.arrayBuffer()),\n contentType: hit.headers.get('content-type') ?? 'application/octet-stream',\n },\n from: 'edge' as const,\n })\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Effect.logWarning('Media: the edge cache failed a read', cause).pipe(\n Effect.as(Option.none<Kept>()),\n ),\n ),\n Effect.flatMap(found => (Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),\n ),\n put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded))),\n }\n}\n\n// A Worker's global, which the DOM's `CacheStorage` declares without `default`.\ndeclare const caches: CacheStorage | undefined\n\nconst cacheOf = (cache: Cache | true): Cache => {\n if (cache !== true) return cache\n if (typeof caches === 'undefined') {\n throw new Error(\n 'variantsR2: `cache: true` reads the Worker global `caches.default`, which this runtime lacks',\n )\n }\n return caches.default\n}\n\n/**\n * Variants kept in R2 under `prefix`, so one made last month is not made, and\n * billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,\n * the Cache API stands in front of it: `true` for the Worker's\n * `caches.default`, or a cache of your own (`await caches.open(…)`).\n */\nexport const variantsR2 = (\n bucket: R2Bucket,\n options: { readonly prefix?: string; readonly cache?: Cache | true } = {},\n): Layer.Layer<Variants> => {\n const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? 'variants/'))\n return Layer.succeed(\n Variants,\n Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => kept,\n onSome: cache => withEdge(kept, cacheOf(cache)),\n }),\n )\n}\n\n/**\n * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose\n * limit and period are its configuration. It answers yes or no, not when, so\n * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60\n * by default). A binding that fails admits the request, logged.\n */\nexport const admissionRateLimit = (\n binding: RateLimit,\n options: { readonly retryAfterSeconds?: number } = {},\n): Layer.Layer<Admission> =>\n Layer.succeed(Admission, {\n admit: client =>\n Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(\n Effect.catch(error =>\n Effect.logWarning('Media: the rate limit binding failed; admitting', error).pipe(\n Effect.as({ success: true }),\n ),\n ),\n Effect.flatMap(({ success }) =>\n success\n ? Effect.void\n : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })),\n ),\n ),\n })\n\n/**\n * The `Inspector` through the Images binding: an original's size from `info`,\n * which costs no transformation. It makes no thumbnail, since raw pixels are\n * not offered offline and could not be tested, so an original described here\n * has no ThumbHash; and as `info` does not say whether pixels are\n * transparent, every format but JPEG is taken to be, which costs a\n * placeholder, never shows a wrong one. An SVG, which has no size in pixels,\n * is refused.\n */\nexport const inspectorImages = (images: ImagesBinding): Layer.Layer<Inspector> =>\n Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.tryPromise({\n try: () =>\n images.info(\n new Blob([bytes]).stream() as unknown as Parameters<ImagesBinding['info']>[0],\n ),\n catch: cause => cause,\n }).pipe(\n Effect.flatMap(info =>\n // An SVG's answer has no width: it has no size in pixels.\n 'width' in info\n ? Effect.succeed({\n width: info.width,\n height: info.height,\n alpha: info.format !== 'image/jpeg',\n thumbnail: Option.none(),\n })\n : Effect.fail(info),\n ),\n Effect.catch(cause =>\n Effect.logWarning('Media.in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AAO,KACL,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAC3B;CACF,QAAO,UAAS;AAClB,CAAC,CAAC,CAAC,KACD,OAAO,SAAQ,SAEb,WAAW,OACP,OAAO,QAAQ;CACb,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,OAAO,KAAK,WAAW;CACvB,WAAW,OAAO,KAAK;AACzB,CAAC,IACD,OAAO,KAAK,IAAI,CACtB,GACA,OAAO,OAAM,UACX,OAAO,WAAW,wBAAwB,KAAK,CAAC,CAAC,KAC/C,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD,CACF,CACF,EACJ,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as ImageAsset } from "./asset-Dlkss5qp.mjs";
|
|
2
2
|
import { Context, Effect, Option, Schema } from "effect";
|
|
3
3
|
//#region src/server/errors.d.ts
|
|
4
4
|
declare const OriginalNotFound_base: Schema.Class<OriginalNotFound, Schema.TaggedStruct<"OriginalNotFound", {
|
|
@@ -53,4 +53,4 @@ declare class Inspector extends Inspector_base {}
|
|
|
53
53
|
declare const describe: (key: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector>;
|
|
54
54
|
//#endregion
|
|
55
55
|
export { OriginalNotFound as a, TransformFailed as c, describe as i, Inspector as n, OriginalTooLarge as o, Thumbnail as r, QuotaExhausted as s, Inspected as t };
|
|
56
|
-
//# sourceMappingURL=describe-
|
|
56
|
+
//# sourceMappingURL=describe-CivKHl4x.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-
|
|
1
|
+
{"version":3,"file":"describe-CivKHl4x.d.mts","names":[],"sources":["../src/server/errors.ts","../src/describe.ts"],"mappings":";;;;;;;cAGa,yBAAyB;;;;;;;cAOzB,yBAAyB;;;;;;cAUzB,wBAAwB;;;cAOxB,uBAAuB;;;;UCrBnB;WACN;WACA;WACA,MAAM;;;UAIA;WACN;WACA;;WAEA;;WAEA,WAAW,OAAO,OAAO;;;WAOd,UAChB,OAAO,WAAW,iBACf,OAAO,OAAO,WAAW,kBAAkB;;;cALvC,kBAAkB;;;;;;;cAoBlB,WAAQ,aACR,OACJ,WAAW,iBACjB,OAAO,OAAO,YAAY,kBAAkB,kBAAkB"}
|
|
@@ -140,6 +140,9 @@ const ImageAsset = Schema.Struct({
|
|
|
140
140
|
placeholder: Schema.OptionFromNullOr(Placeholder),
|
|
141
141
|
focus: Schema.OptionFromOptionalNullOr(Focus)
|
|
142
142
|
});
|
|
143
|
+
const isHashed = (asset) => Option.isSome(asset.hash);
|
|
144
|
+
/** `ImageAsset`, refusing facts with no content hash. */
|
|
145
|
+
const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed));
|
|
143
146
|
//#endregion
|
|
144
147
|
//#region src/describe.ts
|
|
145
148
|
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
@@ -166,6 +169,6 @@ const describe = (key, bytes) => Effect.gen(function* () {
|
|
|
166
169
|
};
|
|
167
170
|
});
|
|
168
171
|
//#endregion
|
|
169
|
-
export {
|
|
172
|
+
export { ImageAsset as a, ContentHash as c, Spelling as d, respell as f, variant_exports as h, HashedAsset as i, PATH as l, standard as m, describe as n, Placeholder as o, revisionOf as p, Focus as r, isHashed as s, Inspector as t, Quality as u };
|
|
170
173
|
|
|
171
|
-
//# sourceMappingURL=describe-
|
|
174
|
+
//# sourceMappingURL=describe-h9F5stgR.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describe-h9F5stgR.mjs","names":["Widths.standard"],"sources":["../src/variant.ts","../src/asset.ts","../src/describe.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","import { Option, Schema } from 'effect'\nimport { ContentHash } from './variant.js'\n\n// A placeholder's color lands in a style the page writes, so it is a color\n// and nothing else: no `;`, no `url(`, no second declaration.\nconst CSS_COLOR =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\([0-9a-z%.,\\s/+-]*\\))$/i\n\nconst coefficientCount = (x: number, y: number): number => {\n let count = 0\n for (let cy = 0; cy < y; cy++)\n for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++\n return count\n}\n\n// A ThumbHash's header decides exactly how many coefficient bytes follow it.\n// Checking that layout here keeps malformed stored data out of the renderer.\nconst isThumbHash = (encoded: string): boolean => {\n try {\n const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))\n if (bytes.length < 5) return false\n const hasAlpha = (bytes[2]! & 0x80) !== 0\n const landscape = (bytes[4]! & 0x80) !== 0\n const shorter = bytes[3]! & 7\n if (shorter === 0) return false\n const long = hasAlpha ? 5 : 7\n const lx = landscape ? long : shorter\n const ly = landscape ? shorter : long\n const coefficients =\n coefficientCount(lx, ly) +\n coefficientCount(3, 3) * 2 +\n (hasAlpha ? coefficientCount(5, 5) : 0)\n return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2)\n } catch {\n return false\n }\n}\n\n/** What stands in an image's place until it loads. */\nexport const Placeholder = Schema.TaggedUnion({\n /** A flat color, such as one taken from a logo. */\n Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },\n /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */\n ThumbHash: {\n hash: Schema.String.check(\n Schema.makeFilter(encoded => isThumbHash(encoded) || 'not a valid ThumbHash'),\n ),\n },\n /** The provider's smallest width of the image itself, scaled up. */\n LowRes: {},\n})\nexport type Placeholder = typeof Placeholder.Type\n\nconst Pixels = Schema.Int.check(Schema.isGreaterThan(0))\n\nconst Share = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }))\n\n/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */\nexport const Focus = Schema.Struct({ x: Share, y: Share })\nexport type Focus = typeof Focus.Type\n\n/**\n * The facts of one original image, derived from it once and stored beside it.\n * `key` is where the original lives, as its provider reads it. `hash` is the\n * original's content hash, absent for an image never read; `alpha` says\n * whether it has transparent pixels. `focus`, the one fact an editor sets\n * rather than one derived, is where a crop keeps the subject; a stored asset\n * without it reads as none.\n */\nexport const ImageAsset = Schema.Struct({\n key: Schema.String.check(Schema.isNonEmpty()),\n width: Pixels,\n height: Pixels,\n alpha: Schema.Boolean,\n hash: Schema.OptionFromNullOr(ContentHash),\n placeholder: Schema.OptionFromNullOr(Placeholder),\n focus: Schema.OptionFromOptionalNullOr(Focus),\n})\nexport type ImageAsset = typeof ImageAsset.Type\n\n/**\n * Facts that name the original by its content hash: what a build or an upload\n * answers, and what `Provider.hosted` needs to write a URL.\n */\nexport type HashedAsset = ImageAsset & { readonly hash: Option.Some<string> }\n\nexport const isHashed = (asset: ImageAsset): asset is HashedAsset => Option.isSome(asset.hash)\n\n/** `ImageAsset`, refusing facts with no content hash. */\nexport const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed))\n","import { Context, Effect, Option } from 'effect'\nimport { rgbaToThumbHash } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { OriginalTooLarge, TransformFailed } from './server/errors.js'\n\n/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */\nexport interface Thumbnail {\n readonly width: number\n readonly height: number\n readonly rgba: Uint8Array\n}\n\n/** What an inspector reads of an original. */\nexport interface Inspected {\n readonly width: number\n readonly height: number\n /** Whether it may have transparent pixels; an inspector that cannot tell says yes. */\n readonly alpha: boolean\n /** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */\n readonly thumbnail: Option.Option<Thumbnail>\n}\n\n/** Reads an original's facts: its size, its alpha, and a thumbnail. */\nexport class Inspector extends Context.Service<\n Inspector,\n {\n readonly inspect: (\n bytes: Uint8Array<ArrayBuffer>,\n ) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>\n }\n>()('foldkit-media/Inspector') {}\n\nconst hex = (buffer: ArrayBuffer) =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n\nconst base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))\n\n/**\n * An original's facts, as an `ImageAsset` under `key`: its size and alpha\n * from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the\n * inspector made a thumbnail. Where an original enters (an upload, a build, a\n * page's content naming a URL), so its facts are derived once and stored.\n */\nexport const describe = (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n): Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector> =>\n Effect.gen(function* () {\n const inspected = yield* Inspector.use(inspector => inspector.inspect(bytes))\n const digest = yield* Effect.promise(() => crypto.subtle.digest('SHA-256', bytes))\n return {\n key,\n width: inspected.width,\n height: inspected.height,\n alpha: inspected.alpha,\n hash: Option.some(hex(digest)),\n placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) =>\n Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) }),\n ),\n focus: Option.none(),\n }\n })\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,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AAO,WAAW,KAAK,CAAC;CACjF,OAAO;EACL;EACA,OAAO,UAAU;EACjB,QAAQ,UAAU;EAClB,OAAO,UAAU;EACjB,MAAM,OAAO,KAAK,IAAI,MAAM,CAAC;EAC7B,aAAa,OAAO,IAAI,UAAU,YAAY,EAAE,OAAO,QAAQ,WAC7D,YAAY,MAAM,UAAU,KAAK,EAAE,MAAM,OAAO,gBAAgB,OAAO,QAAQ,IAAI,CAAC,EAAE,CAAC,CACzF;EACA,OAAO,OAAO,KAAK;CACrB;AACF,CAAC"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import { i as describe, n as Inspector, r as Thumbnail, t as Inspected } from "./describe-
|
|
1
|
+
import { a as isHashed, i as Placeholder, n as HashedAsset, r as ImageAsset, t as Focus } from "./asset-Dlkss5qp.mjs";
|
|
2
|
+
import { i as describe, n as Inspector, r as Thumbnail, t as Inspected } from "./describe-CivKHl4x.mjs";
|
|
3
3
|
import { a as mimeType, i as Format, n as widths_d_exports, r as Encoding, t as Widths } from "./widths-Cg7-x89y.mjs";
|
|
4
4
|
import { r as variant_d_exports } from "./variant-BOg1M0Wj.mjs";
|
|
5
5
|
import { a as SvgTag, i as SvgNode, n as Stroke, o as icon_d_exports, r as SvgBuilder, t as IconData } from "./icon-ClqtprHT.mjs";
|
|
6
|
-
import { n as
|
|
6
|
+
import { n as Provider, r as provider_d_exports } from "./provider-g0Vlvlrb.mjs";
|
|
7
7
|
import { Option, Schema } from "effect";
|
|
8
8
|
declare namespace layout_d_exports {
|
|
9
9
|
export { Candidate, Constrained, Fixed, FullWidth, Layout, LayoutSchema as Schema, box, candidates, ratio, sizes$1 as sizes };
|
|
@@ -107,9 +107,10 @@ interface Picture {
|
|
|
107
107
|
*/
|
|
108
108
|
readonly placeholder: Option.Option<string>;
|
|
109
109
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
readonly
|
|
110
|
+
/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */
|
|
111
|
+
interface Input<Asset extends ImageAsset = ImageAsset> {
|
|
112
|
+
readonly asset: Asset;
|
|
113
|
+
readonly provider: Provider<NoInfer<Asset>>;
|
|
113
114
|
readonly layout: Layout;
|
|
114
115
|
/** The page's largest image: fetched first, not lazily. */
|
|
115
116
|
readonly priority?: boolean;
|
|
@@ -128,7 +129,7 @@ interface Input {
|
|
|
128
129
|
* this image). Candidates the provider lacks are left out, never written as a
|
|
129
130
|
* broken URL.
|
|
130
131
|
*/
|
|
131
|
-
declare const derive: (input: Input) => Option.Option<Picture>;
|
|
132
|
+
declare const derive: <Asset extends ImageAsset>(input: Input<Asset>) => Option.Option<Picture>;
|
|
132
133
|
/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */
|
|
133
134
|
interface Preloaded {
|
|
134
135
|
/** A `source`'s media type, so a browser that cannot show it skips the preload. */
|
|
@@ -153,7 +154,7 @@ declare const preload: ({ sources, img }: Picture) => string;
|
|
|
153
154
|
* AVIF, as an absolute URL against `origin`. None when the provider has no
|
|
154
155
|
* such variant.
|
|
155
156
|
*/
|
|
156
|
-
declare const ogImage: (asset:
|
|
157
|
+
declare const ogImage: <Asset extends ImageAsset>(asset: Asset, provider: Provider<NoInfer<Asset>>, origin: string) => Option.Option<string>;
|
|
157
158
|
//#endregion
|
|
158
|
-
export { type Encoding, Focus, Format, icon_d_exports as Icon, type IconData, ImageAsset, type Inspected, Inspector, layout_d_exports as Layout, picture_d_exports as Picture, Placeholder, provider_d_exports as Provider, type Stroke, type SvgBuilder, type SvgNode, type SvgTag, type Thumbnail, variant_d_exports as Variant, widths_d_exports as Widths, describe, mimeType };
|
|
159
|
+
export { type Encoding, Focus, Format, HashedAsset, icon_d_exports as Icon, type IconData, ImageAsset, type Inspected, Inspector, layout_d_exports as Layout, picture_d_exports as Picture, Placeholder, provider_d_exports as Provider, type Stroke, type SvgBuilder, type SvgNode, type SvgTag, type Thumbnail, variant_d_exports as Variant, widths_d_exports as Widths, describe, isHashed, mimeType };
|
|
159
160
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["sizes","Layout.Layout"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts"],"mappings":";;;;;;;;;;;cAOM,cAAY,OAAA;;;;;;;;;KASN,gBAAgB,aAAa;cAE5B,QAAK;;;aAAL,OAAA;;;;cACA,cAAW;;;aAAX,OAAA;;;;cACA,iBAAgB;;;;;;UAOZ;WACN;WACA;;;;;;;;cASE,aAAU,QACb,QAAM,QACN,QAAM,sBAEb,cAAc;;cAkBJA,UAAK,QAAY;;cAQjB,QAAK,OAAW,KAAK;;;;;;cAQrB,MAAG,QACN,QAAM,OACP,KAAK;WACA;WAAwB;;;;;;;;KC3C1B;;;;;UC3BK;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU,OAAO;WACjB,eAAe,OAAO;;;;;;UAOhB;;WAEN,SAAS,cAAc;WACvB,KAAK;;WAEL;;WAEA,OAAO,OAAO;;;;;WAKd,aAAa,OAAO
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["sizes","Layout.Layout"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts"],"mappings":";;;;;;;;;;;cAOM,cAAY,OAAA;;;;;;;;;KASN,gBAAgB,aAAa;cAE5B,QAAK;;;aAAL,OAAA;;;;cACA,cAAW;;;aAAX,OAAA;;;;cACA,iBAAgB;;;;;;UAOZ;WACN;WACA;;;;;;;;cASE,aAAU,QACb,QAAM,QACN,QAAM,sBAEb,cAAc;;cAkBJA,UAAK,QAAY;;cAQjB,QAAK,OAAW,KAAK;;;;;;cAQrB,MAAG,QACN,QAAM,OACP,KAAK;WACA;WAAwB;;;;;;;;KC3C1B;;;;;UC3BK;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU,OAAO;WACjB,eAAe,OAAO;;;;;;UAOhB;;WAEN,SAAS,cAAc;WACvB,KAAK;;WAEL;;WAEA,OAAO,OAAO;;;;;WAKd,aAAa,OAAO;;;UAId,MAAM,cAAc,aAAa;WACvC,OAAO;WACP,UAAU,SAAS,QAAQ;WAC3B,QAAQC;;WAER;;WAEA;;;;;;WAMA,cAAc;;;;;;;;cASZ,SAAU,cAAc,YAAU,OAAS,MAAM,WAAS,OAAO,OAAO;;UA0DpE;;WAEN,MAAM,OAAO;WACb;WACA;;;cAIE,gBAAW,MAAA,QAAA,SAA6B;;;;;;;;;cAoBxC,YAAO,SAAA,OAAsB;;;;;;;cAkB7B,UAAW,cAAc,YAAU,OACvC,OAAK,UACF,SAAS,QAAQ,SAAO,mBAEjC,OAAO"}
|