foldkit-media 0.1.0 → 0.3.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 +167 -66
- package/client.d.ts +2 -2
- package/dist/{asset-BNQ_j5tO.d.mts → asset-BLo8VWmd.d.mts} +32 -5
- package/dist/asset-BLo8VWmd.d.mts.map +1 -0
- package/dist/browser/index.d.mts +86 -4
- package/dist/browser/index.d.mts.map +1 -1
- package/dist/browser/index.mjs +88 -7
- package/dist/browser/index.mjs.map +1 -1
- package/dist/cloudflare/index.d.mts +13 -9
- package/dist/cloudflare/index.d.mts.map +1 -1
- package/dist/cloudflare/index.mjs +28 -12
- package/dist/cloudflare/index.mjs.map +1 -1
- package/dist/{describe-DdYvLhMY.d.mts → describe-BOgc0xbR.d.mts} +2 -6
- package/dist/describe-BOgc0xbR.d.mts.map +1 -0
- package/dist/{describe-Cqr63Gxa.mjs → describe-C6sWA_8p.mjs} +10 -10
- package/dist/describe-C6sWA_8p.mjs.map +1 -0
- package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
- package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
- package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
- package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
- package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
- package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
- package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
- package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
- package/dist/icons/index.d.mts +1 -3
- package/dist/icons/index.d.mts.map +1 -1
- package/dist/icons/index.mjs +2 -3
- package/dist/index.d.mts +13 -15
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +19 -21
- package/dist/index.mjs.map +1 -1
- package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
- package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
- package/dist/{provider-DztvQjOr.d.mts → provider-CB0nqu0m.d.mts} +21 -16
- package/dist/provider-CB0nqu0m.d.mts.map +1 -0
- package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/dist/server/index.d.mts +34 -27
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +174 -8
- package/dist/server/index.mjs.map +1 -1
- package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
- package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
- package/dist/{services-Ck-7dhIP.d.mts → services-BZoK2VOY.d.mts} +3 -5
- package/dist/services-BZoK2VOY.d.mts.map +1 -0
- package/dist/sharp/index.d.mts +2 -4
- package/dist/sharp/index.d.mts.map +1 -1
- package/dist/sharp/index.mjs +5 -6
- package/dist/{upload-C5YM5jZR.mjs → stores-CxraN3kt.mjs} +128 -228
- package/dist/stores-CxraN3kt.mjs.map +1 -0
- package/dist/unpic/index.d.mts +2 -4
- package/dist/unpic/index.d.mts.map +1 -1
- package/dist/unpic/index.mjs +2 -3
- package/dist/{upload-C4_inwfv.d.mts → upload-lVLMRJoC.d.mts} +53 -24
- package/dist/upload-lVLMRJoC.d.mts.map +1 -0
- package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
- package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
- package/dist/vite/index.d.mts +1 -5
- package/dist/vite/index.d.mts.map +1 -1
- package/dist/vite/index.mjs +7 -9
- package/dist/vite/index.mjs.map +1 -1
- package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
- package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
- package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
- package/dist/widths-upkgLdek.d.mts.map +1 -0
- package/package.json +6 -6
- package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
- package/dist/describe-Cqr63Gxa.mjs.map +0 -1
- package/dist/describe-DdYvLhMY.d.mts.map +0 -1
- package/dist/provider-DztvQjOr.d.mts.map +0 -1
- package/dist/services-Ck-7dhIP.d.mts.map +0 -1
- package/dist/upload-C4_inwfv.d.mts.map +0 -1
- package/dist/upload-C5YM5jZR.mjs.map +0 -1
- package/dist/widths-Cg7-x89y.d.mts.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
|
|
@@ -401,52 +416,116 @@ An original that no CDN or build holds, such as an editor's upload, enters
|
|
|
401
416
|
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
|
-
their SHA-256 in `Uploads` (where `Originals` reads them)
|
|
405
|
-
facts as
|
|
406
|
-
|
|
407
|
-
asset row); the bytes never travel through RPC.
|
|
419
|
+
their SHA-256 in `Uploads` (where `Originals` reads them) with the facts
|
|
420
|
+
beside them, and answers the facts as a `HashedAsset`, keyed by that hash,
|
|
421
|
+
with a `201`. The variant server serves it at once.
|
|
408
422
|
|
|
409
|
-
Who may upload is the application's to say, and the route has no
|
|
410
|
-
`UploadPolicy` is asked before a byte is read
|
|
423
|
+
**Who may upload** is the application's to say, and the route has no
|
|
424
|
+
default. `UploadPolicy.admit(request, route)` is asked before a byte is read,
|
|
425
|
+
with the route it is for (`'Upload'`, or `'DescribeUrl'` for the facts route
|
|
426
|
+
below). It refuses with `UploadForbidden` (`403`), or with
|
|
427
|
+
`UploadUnauthenticated` (`401`) when it cannot tell who is asking, so a client
|
|
428
|
+
whose session ended knows to sign in again.
|
|
411
429
|
|
|
412
430
|
```ts
|
|
413
|
-
import {
|
|
431
|
+
import { Layer } from 'effect'
|
|
432
|
+
import { GuardMedia } from 'foldkit-guard/media'
|
|
414
433
|
import {
|
|
415
|
-
UploadForbidden,
|
|
416
|
-
UploadPolicy,
|
|
417
434
|
uploadLayer,
|
|
435
|
+
uploadPolicyAny,
|
|
436
|
+
uploadPolicyBearer,
|
|
418
437
|
uploadsKeyValueStore,
|
|
419
438
|
} 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
|
+
uploadPolicyAny(
|
|
447
|
+
uploadPolicyBearer(process.env['UPLOAD_TOKEN']),
|
|
448
|
+
GuardMedia.uploadPolicy(Policy, { resolve, Upload: [G.isEditor] }),
|
|
449
|
+
),
|
|
450
|
+
),
|
|
451
|
+
),
|
|
434
452
|
)
|
|
435
453
|
```
|
|
436
454
|
|
|
437
|
-
`
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
`
|
|
442
|
-
the
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
route
|
|
455
|
+
- `uploadPolicyBearer(secret)` is for a deployment's secret, a script's: it
|
|
456
|
+
admits `Authorization: Bearer <secret>`, compared by digest so the time
|
|
457
|
+
taken says nothing of the secret, and admits nobody while the secret is
|
|
458
|
+
unset or empty.
|
|
459
|
+
- `GuardMedia.uploadPolicy` from `foldkit-guard/media` decides each route by
|
|
460
|
+
the principal guards of your guard set (`G`, `Policy`), for who `resolve`
|
|
461
|
+
says is asking: the resolver your Remote server is given, such as
|
|
462
|
+
`AuthServer.resolver` from `foldkit-auth/server`. It reads the request's
|
|
463
|
+
headers alone. A route given no guards admits nobody; here an editor may
|
|
464
|
+
upload and nobody may have a URL described.
|
|
465
|
+
- `uploadPolicyAny(a, b, …)` tries policies in turn, the first to admit
|
|
466
|
+
winning; when every one refuses, the last refusal is the answer.
|
|
467
|
+
- A policy of your own is `Layer.succeed(UploadPolicy, { admit })`.
|
|
468
|
+
|
|
469
|
+
**Registering an upload.** The bytes never travel through RPC; only facts go
|
|
470
|
+
on to the application's data (a CMS's asset row). But the facts the route
|
|
471
|
+
answered are the client's word once they pass through it: a client can change
|
|
472
|
+
a width, or name another original's hash, and decoding with `HashedAsset`
|
|
473
|
+
checks their shape, not that they are true. So the mutation that registers
|
|
474
|
+
an upload takes the hash, and reads the facts the server kept:
|
|
475
|
+
`StoredFacts.get(hash)` answers them, or none for a hash nobody uploaded (or
|
|
476
|
+
one kept before facts were), over the same store as `Uploads`
|
|
477
|
+
(`storedFactsKeyValueStore()`, `storedFactsR2(bucket)`). What only an editor
|
|
478
|
+
knows, such as a focal point, comes with the hash.
|
|
479
|
+
|
|
480
|
+
`uploadsKeyValueStore()` keeps uploads where `originalsKeyValueStore()`
|
|
481
|
+
reads, over the same `KeyValueStore`; on Cloudflare, `uploadsR2(bucket)`
|
|
482
|
+
beside `originalsR2(bucket)`, and `serveFetch`'s `uploads` hosts the route in
|
|
483
|
+
a Worker. A refusal answers its kind and nothing more, and no browser keeps
|
|
484
|
+
it: `403` or `401` from the policy, `415` for a body that is not `image/*` or
|
|
485
|
+
not an image the inspector reads, `413` past `maxBytes` or the inspector's
|
|
486
|
+
pixel limit, and `400` for a body that broke off. Because the body must be
|
|
487
|
+
`image/*`, which is not a type a browser sends to another origin without a
|
|
488
|
+
preflight, and the route answers no preflight, a cookie alone cannot upload
|
|
489
|
+
from another site.
|
|
490
|
+
|
|
491
|
+
From a browser, `upload(file, { url?, headers? })` (`foldkit-media/browser`)
|
|
492
|
+
sends one file to the route and is a `Stream`: `Progressed { loaded, total }`
|
|
493
|
+
as the bytes go, then one `Uploaded { asset }` with the route's facts, and it
|
|
494
|
+
ends. A refusal fails it with `UploadFailed { reason, status }`, whose
|
|
495
|
+
`reason` names the route's answer (`Forbidden`, `Unauthenticated`,
|
|
496
|
+
`TooLarge`, `Unsupported`, `Malformed`), `Network` when nothing answered,
|
|
497
|
+
or `Unexpected` for an answer that is not the route's. It is an
|
|
498
|
+
`XMLHttpRequest`, since `fetch` reports no upload progress, and interrupting
|
|
499
|
+
the stream aborts it: a Command or Subscription that runs it cancels by
|
|
500
|
+
ending.
|
|
501
|
+
|
|
502
|
+
```ts
|
|
503
|
+
import { Effect, Match, Stream } from 'effect'
|
|
504
|
+
import { upload } from 'foldkit-media/browser'
|
|
505
|
+
|
|
506
|
+
const send = (file: File) =>
|
|
507
|
+
upload(file).pipe(
|
|
508
|
+
Stream.runForEach(event =>
|
|
509
|
+
Effect.sync(() =>
|
|
510
|
+
Match.valueTags(event, {
|
|
511
|
+
Progressed: ({ loaded, total }) => console.log(`${loaded} of ${total} bytes`),
|
|
512
|
+
Uploaded: ({ asset }) => console.log('kept as', asset.key),
|
|
513
|
+
}),
|
|
514
|
+
),
|
|
515
|
+
),
|
|
516
|
+
)
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
A browser authenticates as the page does: a same-origin request carries the
|
|
520
|
+
session cookie, which the application's own `UploadPolicy` reads (as
|
|
521
|
+
`GuardMedia.uploadPolicy` does). `uploadPolicyBearer`'s secret is a deployment's,
|
|
522
|
+
for a script; a page that sends it in `headers` gives it to every visitor. No
|
|
523
|
+
timeout is set: a stalled server shows the send on its way until it is
|
|
524
|
+
interrupted.
|
|
446
525
|
|
|
447
526
|
An image a page names only by URL gets its facts from the same route set:
|
|
448
527
|
`GET /_media/facts?url=` reads it with `factsOf`, behind the same
|
|
449
|
-
`UploadPolicy`, and answers them keyed by the URL (`200`). Only `https` on a
|
|
528
|
+
`UploadPolicy`, asked for `'DescribeUrl'`, and answers them keyed by the URL (`200`). Only `https` on a
|
|
450
529
|
host in `uploadLayer({ facts: { allow } })` is read, and `allow` is empty
|
|
451
530
|
unless given, so a server names every host it fetches. An editor asks it when
|
|
452
531
|
a URL is set, and stores the facts beside the URL. Neither route limits how
|
|
@@ -462,12 +541,14 @@ them as files at their own paths, for `foldkit-ssr`'s `staticSite` `emit`:
|
|
|
462
541
|
|
|
463
542
|
```ts
|
|
464
543
|
const media = serveFetch<object>({
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
Layer.
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
544
|
+
images: {
|
|
545
|
+
layer: () =>
|
|
546
|
+
Layer.mergeAll(transformerSharp(), originalsKeyValueStore(), variantsKeyValueStore()).pipe(
|
|
547
|
+
Layer.provide(KeyValueStore.layerFileSystem('.media')),
|
|
548
|
+
// The disk itself: Node's file system and paths.
|
|
549
|
+
Layer.provide(NodeServices.layer),
|
|
550
|
+
),
|
|
551
|
+
},
|
|
471
552
|
})
|
|
472
553
|
const env = {}
|
|
473
554
|
|
|
@@ -494,17 +575,33 @@ export const site = {
|
|
|
494
575
|
|
|
495
576
|
### On Cloudflare
|
|
496
577
|
|
|
497
|
-
`foldkit-media/cloudflare` gives the
|
|
578
|
+
`foldkit-media/cloudflare` gives the services from a Worker's bindings, and
|
|
579
|
+
`serveFetch` is the Worker:
|
|
498
580
|
|
|
499
581
|
```ts
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
})
|
|
582
|
+
export default {
|
|
583
|
+
fetch: serveFetch<WorkerEnv>({
|
|
584
|
+
images: {
|
|
585
|
+
layer: env =>
|
|
586
|
+
Layer.mergeAll(
|
|
587
|
+
originalsR2(env.MEDIA),
|
|
588
|
+
transformerImages(env.IMAGES),
|
|
589
|
+
variantsR2(env.MEDIA, { cache: true }),
|
|
590
|
+
admissionRateLimit(env.LIMITER),
|
|
591
|
+
),
|
|
592
|
+
},
|
|
593
|
+
uploads: {
|
|
594
|
+
layer: env =>
|
|
595
|
+
Layer.mergeAll(
|
|
596
|
+
uploadsR2(env.MEDIA),
|
|
597
|
+
inspectorImages(env.IMAGES),
|
|
598
|
+
uploadPolicyBearer(env.UPLOAD_TOKEN),
|
|
599
|
+
),
|
|
600
|
+
},
|
|
601
|
+
// The application's own routes.
|
|
602
|
+
otherwise: async () => new Response('Not found', { status: 404 }),
|
|
603
|
+
}),
|
|
604
|
+
}
|
|
508
605
|
```
|
|
509
606
|
|
|
510
607
|
- `transformerImages(images)` is the Images binding: it scales down, never up,
|
|
@@ -514,15 +611,19 @@ const answerImages = serveFetch<WorkerEnv>({
|
|
|
514
611
|
store adapters above or the application's own (`clear` and `size` list the
|
|
515
612
|
bucket).
|
|
516
613
|
- `variantsR2(bucket, { prefix?, cache? })` is `variantsKeyValueStore` over
|
|
517
|
-
it, so a variant made last month is not made, and billed, again
|
|
518
|
-
|
|
614
|
+
it, so a variant made last month is not made, and billed, again. Two misses
|
|
615
|
+
for one variant at the same moment both make it, since a Worker request
|
|
616
|
+
cannot wait on another's; with
|
|
617
|
+
`cache`, the Cache API is read first and filled from R2: `true` for the
|
|
618
|
+
Worker's `caches.default`, or a cache of your own (`await caches.open(…)`).
|
|
619
|
+
`true` outside a Worker throws where the layer is made.
|
|
519
620
|
- `originalsR2(bucket)` streams an original rather than reading it into
|
|
520
621
|
memory, unlike the general adapter.
|
|
521
622
|
|
|
522
623
|
Cloudflare bills each new width of each original once a month (format and
|
|
523
624
|
quality do not count), so the ladder is the cost: eight widths are at most
|
|
524
|
-
eight transformations an original. `examples/cloudflare`
|
|
525
|
-
|
|
625
|
+
eight transformations an original. `examples/cloudflare` is such a Worker,
|
|
626
|
+
with Remote and Sync as its `otherwise`.
|
|
526
627
|
|
|
527
628
|
## Icons
|
|
528
629
|
|
|
@@ -557,8 +658,8 @@ A view draws an icon with `Icon.draw(icon, h)`: inline SVG through the view's
|
|
|
557
658
|
builder (Foldkit's `h`, or anything of its shape, `SvgBuilder`), every
|
|
558
659
|
attribute in the server's markup, `1em` square unless `size` is given, and
|
|
559
660
|
`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()`.
|
|
661
|
+
`foldkit-mixins-ui`'s `Icon.view({ icon, label? })` draws it into its glyph,
|
|
662
|
+
sized by the recipe, and names it when given a `label`. A style masks with `Icon.maskUrl(icon)`, a CSS `url()`.
|
|
562
663
|
|
|
563
664
|
Every icon is parsed against a presentational allowlist, because it is drawn
|
|
564
665
|
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,5 +1,4 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
2
|
-
//#region src/asset.d.ts
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
3
2
|
/** What stands in an image's place until it loads. */
|
|
4
3
|
declare const Placeholder: Schema.TaggedUnion<{
|
|
5
4
|
readonly Color: Schema.TaggedStruct<"Color", {
|
|
@@ -46,6 +45,34 @@ declare const ImageAsset: Schema.Struct<{
|
|
|
46
45
|
}>>;
|
|
47
46
|
}>;
|
|
48
47
|
type ImageAsset = typeof ImageAsset.Type;
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
/**
|
|
49
|
+
* Facts that name the original by its content hash: what a build or an upload
|
|
50
|
+
* answers, and what `Provider.hosted` needs to write a URL.
|
|
51
|
+
*/
|
|
52
|
+
type HashedAsset = ImageAsset & {
|
|
53
|
+
readonly hash: Option.Some<string>;
|
|
54
|
+
};
|
|
55
|
+
declare const isHashed: (asset: ImageAsset) => asset is HashedAsset;
|
|
56
|
+
/** `ImageAsset`, refusing facts with no content hash. */
|
|
57
|
+
declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
|
|
58
|
+
readonly key: Schema.String;
|
|
59
|
+
readonly width: Schema.Int;
|
|
60
|
+
readonly height: Schema.Int;
|
|
61
|
+
readonly alpha: Schema.Boolean;
|
|
62
|
+
readonly hash: Schema.OptionFromNullOr<Schema.String>;
|
|
63
|
+
readonly placeholder: Schema.OptionFromNullOr<Schema.TaggedUnion<{
|
|
64
|
+
readonly Color: Schema.TaggedStruct<"Color", {
|
|
65
|
+
readonly value: Schema.String;
|
|
66
|
+
}>;
|
|
67
|
+
readonly LowRes: Schema.TaggedStruct<"LowRes", {}>;
|
|
68
|
+
readonly ThumbHash: Schema.TaggedStruct<"ThumbHash", {
|
|
69
|
+
readonly hash: Schema.String;
|
|
70
|
+
}>;
|
|
71
|
+
}>>;
|
|
72
|
+
readonly focus: Schema.OptionFromOptionalNullOr<Schema.Struct<{
|
|
73
|
+
readonly x: Schema.Finite;
|
|
74
|
+
readonly y: Schema.Finite;
|
|
75
|
+
}>>;
|
|
76
|
+
}>>;
|
|
77
|
+
export { isHashed as a, Placeholder as i, HashedAsset as n, ImageAsset as r, Focus as t };
|
|
78
|
+
//# sourceMappingURL=asset-BLo8VWmd.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"asset-BLo8VWmd.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
|
@@ -1,6 +1,88 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { n as HashedAsset } from "../asset-BLo8VWmd.mjs";
|
|
2
|
+
import { n as Inspector } from "../describe-BOgc0xbR.mjs";
|
|
3
|
+
import { Cause, Layer, Schema, Stream } from "effect";
|
|
4
|
+
/** Why an upload did not end in facts: the route's refusal, or no answer at all. */
|
|
5
|
+
export declare const UploadRefusal: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "Network", "Unexpected"]>;
|
|
6
|
+
export type UploadRefusal = typeof UploadRefusal.Type;
|
|
7
|
+
declare const UploadFailed_base: Schema.Class<UploadFailed, Schema.TaggedStruct<"UploadFailed", {
|
|
8
|
+
readonly reason: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "Network", "Unexpected"]>;
|
|
9
|
+
/** The HTTP status, `0` when there was no answer. */
|
|
10
|
+
readonly status: Schema.Number;
|
|
11
|
+
}>, Cause.YieldableError>;
|
|
12
|
+
export declare class UploadFailed extends UploadFailed_base {}
|
|
13
|
+
/** How far the bytes have gone: `loaded` of `total`. */
|
|
14
|
+
export declare const Progressed: Schema.TaggedStruct<"Progressed", {
|
|
15
|
+
readonly loaded: Schema.Number;
|
|
16
|
+
readonly total: Schema.Number;
|
|
17
|
+
}>;
|
|
18
|
+
/** The route kept the image, and these are its facts. */
|
|
19
|
+
export declare const Uploaded: Schema.TaggedStruct<"Uploaded", {
|
|
20
|
+
readonly asset: Schema.refine<HashedAsset, Schema.Struct<{
|
|
21
|
+
readonly key: Schema.String;
|
|
22
|
+
readonly width: Schema.Int;
|
|
23
|
+
readonly height: Schema.Int;
|
|
24
|
+
readonly alpha: Schema.Boolean;
|
|
25
|
+
readonly hash: Schema.OptionFromNullOr<Schema.String>;
|
|
26
|
+
readonly placeholder: Schema.OptionFromNullOr<Schema.TaggedUnion<{
|
|
27
|
+
readonly Color: Schema.TaggedStruct<"Color", {
|
|
28
|
+
readonly value: Schema.String;
|
|
29
|
+
}>;
|
|
30
|
+
readonly LowRes: Schema.TaggedStruct<"LowRes", {}>;
|
|
31
|
+
readonly ThumbHash: Schema.TaggedStruct<"ThumbHash", {
|
|
32
|
+
readonly hash: Schema.String;
|
|
33
|
+
}>;
|
|
34
|
+
}>>;
|
|
35
|
+
readonly focus: Schema.OptionFromOptionalNullOr<Schema.Struct<{
|
|
36
|
+
readonly x: Schema.Finite;
|
|
37
|
+
readonly y: Schema.Finite;
|
|
38
|
+
}>>;
|
|
39
|
+
}>>;
|
|
40
|
+
}>;
|
|
41
|
+
export declare const UploadEvent: Schema.Union<readonly [Schema.TaggedStruct<"Progressed", {
|
|
42
|
+
readonly loaded: Schema.Number;
|
|
43
|
+
readonly total: Schema.Number;
|
|
44
|
+
}>, Schema.TaggedStruct<"Uploaded", {
|
|
45
|
+
readonly asset: Schema.refine<HashedAsset, Schema.Struct<{
|
|
46
|
+
readonly key: Schema.String;
|
|
47
|
+
readonly width: Schema.Int;
|
|
48
|
+
readonly height: Schema.Int;
|
|
49
|
+
readonly alpha: Schema.Boolean;
|
|
50
|
+
readonly hash: Schema.OptionFromNullOr<Schema.String>;
|
|
51
|
+
readonly placeholder: Schema.OptionFromNullOr<Schema.TaggedUnion<{
|
|
52
|
+
readonly Color: Schema.TaggedStruct<"Color", {
|
|
53
|
+
readonly value: Schema.String;
|
|
54
|
+
}>;
|
|
55
|
+
readonly LowRes: Schema.TaggedStruct<"LowRes", {}>;
|
|
56
|
+
readonly ThumbHash: Schema.TaggedStruct<"ThumbHash", {
|
|
57
|
+
readonly hash: Schema.String;
|
|
58
|
+
}>;
|
|
59
|
+
}>>;
|
|
60
|
+
readonly focus: Schema.OptionFromOptionalNullOr<Schema.Struct<{
|
|
61
|
+
readonly x: Schema.Finite;
|
|
62
|
+
readonly y: Schema.Finite;
|
|
63
|
+
}>>;
|
|
64
|
+
}>>;
|
|
65
|
+
}>]>;
|
|
66
|
+
export type UploadEvent = typeof UploadEvent.Type;
|
|
67
|
+
interface UploadOptions {
|
|
68
|
+
/** Where the route is. Default `/_media/upload`. */
|
|
69
|
+
readonly url?: string | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Sent with the bytes. A page's own session cookie goes with a same-origin
|
|
72
|
+
* request already: never put a deployment's secret (`uploadPolicyBearer`'s) here,
|
|
73
|
+
* where every visitor can read it.
|
|
74
|
+
*/
|
|
75
|
+
readonly headers?: Readonly<Record<string, string>> | undefined;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Sends `file` to the upload route as its body, which the browser types by the
|
|
79
|
+
* file's own `type`:
|
|
80
|
+
* `Progressed` as the bytes go, then one `Uploaded` with the facts, and the
|
|
81
|
+
* stream ends. A refusal fails it with `UploadFailed`, naming why; a file the
|
|
82
|
+
* route does not take as an image is `Unsupported`. Interrupting it aborts the
|
|
83
|
+
* request.
|
|
84
|
+
*/
|
|
85
|
+
export declare const upload: (file: Blob, options?: UploadOptions) => Stream.Stream<UploadEvent, UploadFailed>;
|
|
4
86
|
/**
|
|
5
87
|
* The `Inspector` in a browser or a web worker: the size from the decoded
|
|
6
88
|
* picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
|
|
@@ -11,5 +93,5 @@ import { Layer } from "effect";
|
|
|
11
93
|
export declare const inspectorBrowser: (options?: {
|
|
12
94
|
readonly maxPixels?: number;
|
|
13
95
|
}) => Layer.Layer<Inspector>;
|
|
14
|
-
|
|
96
|
+
export type { UploadOptions };
|
|
15
97
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/browser/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/browser/upload.ts","../../src/browser/index.ts"],"mappings":";;;;qBAUa,eAAa,OAAA;YAWd,uBAAuB,cAAc;;;;;;qBAEpC,qBAAqB;;qBAOrB,YAAU,OAAA;;;;;qBAKV,UAAQ,OAAA;;;;;;;;;;;;;;;;;;;;;;qBACR,aAAW,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YACZ,qBAAqB,YAAY;UAqB5B;;WAEN;;;;;;WAMA,UAAU,SAAS;;;;;;;;;;qBAWjB,SAAM,MACX,MAAI,UACD,kBACR,OAAO,OAAO,aAAa;;;;;;;;qBCpDjB,mBAAgB;WACP;MACnB,MAAM,MAAM"}
|
package/dist/browser/index.mjs
CHANGED
|
@@ -1,8 +1,90 @@
|
|
|
1
|
-
import { t as Inspector } from "../describe-
|
|
2
|
-
import { t as nonNegativeInteger } from "../limits-
|
|
3
|
-
import { i as TransformFailed, n as OriginalTooLarge } from "../errors-
|
|
4
|
-
import { Effect, Layer, Option } from "effect";
|
|
5
|
-
|
|
1
|
+
import { i as HashedAsset, t as Inspector } from "../describe-C6sWA_8p.mjs";
|
|
2
|
+
import { t as nonNegativeInteger } from "../limits-B4hHpyfE.mjs";
|
|
3
|
+
import { i as TransformFailed, n as OriginalTooLarge } from "../errors-BhEgXJ4m.mjs";
|
|
4
|
+
import { Cause, Effect, Layer, Option, Queue, Schema, Stream } from "effect";
|
|
5
|
+
// src/browser/upload.ts
|
|
6
|
+
/**
|
|
7
|
+
* An image sent to the upload route from a browser: the bytes go once, with
|
|
8
|
+
* their progress reported as they go, and the route's facts come back as the
|
|
9
|
+
* `HashedAsset` to store. `fetch` reports no upload progress, so this is an
|
|
10
|
+
* `XMLHttpRequest`, and interrupting the stream aborts it.
|
|
11
|
+
*/
|
|
12
|
+
/** Why an upload did not end in facts: the route's refusal, or no answer at all. */
|
|
13
|
+
const UploadRefusal = Schema.Literals([
|
|
14
|
+
"Forbidden",
|
|
15
|
+
"Unauthenticated",
|
|
16
|
+
"TooLarge",
|
|
17
|
+
"Unsupported",
|
|
18
|
+
"Malformed",
|
|
19
|
+
"Network",
|
|
20
|
+
"Unexpected"
|
|
21
|
+
]);
|
|
22
|
+
var UploadFailed = class extends Schema.TaggedError()("UploadFailed", {
|
|
23
|
+
reason: UploadRefusal,
|
|
24
|
+
/** The HTTP status, `0` when there was no answer. */
|
|
25
|
+
status: Schema.Number
|
|
26
|
+
}) {};
|
|
27
|
+
/** How far the bytes have gone: `loaded` of `total`. */
|
|
28
|
+
const Progressed = Schema.TaggedStruct("Progressed", {
|
|
29
|
+
loaded: Schema.Number,
|
|
30
|
+
total: Schema.Number
|
|
31
|
+
});
|
|
32
|
+
/** The route kept the image, and these are its facts. */
|
|
33
|
+
const Uploaded = Schema.TaggedStruct("Uploaded", { asset: HashedAsset });
|
|
34
|
+
const UploadEvent = Schema.Union([Progressed, Uploaded]);
|
|
35
|
+
const refusals = {
|
|
36
|
+
400: "Malformed",
|
|
37
|
+
401: "Unauthenticated",
|
|
38
|
+
403: "Forbidden",
|
|
39
|
+
413: "TooLarge",
|
|
40
|
+
415: "Unsupported"
|
|
41
|
+
};
|
|
42
|
+
const decodeFacts = Schema.decodeUnknownOption(HashedAsset);
|
|
43
|
+
/** The facts in a 201's body, or none for a body that is not them. */
|
|
44
|
+
const factsOf = (body) => {
|
|
45
|
+
try {
|
|
46
|
+
return decodeFacts(JSON.parse(body));
|
|
47
|
+
} catch {
|
|
48
|
+
return Option.none();
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Sends `file` to the upload route as its body, which the browser types by the
|
|
53
|
+
* file's own `type`:
|
|
54
|
+
* `Progressed` as the bytes go, then one `Uploaded` with the facts, and the
|
|
55
|
+
* stream ends. A refusal fails it with `UploadFailed`, naming why; a file the
|
|
56
|
+
* route does not take as an image is `Unsupported`. Interrupting it aborts the
|
|
57
|
+
* request.
|
|
58
|
+
*/
|
|
59
|
+
const upload = (file, options = {}) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
|
|
60
|
+
const request = new XMLHttpRequest();
|
|
61
|
+
const fail = (reason) => Queue.failCauseUnsafe(queue, Cause.fail(new UploadFailed({
|
|
62
|
+
reason,
|
|
63
|
+
status: request.status
|
|
64
|
+
})));
|
|
65
|
+
request.upload.onprogress = (event) => {
|
|
66
|
+
Queue.offerUnsafe(queue, Progressed.make({
|
|
67
|
+
loaded: event.loaded,
|
|
68
|
+
total: event.lengthComputable ? event.total : file.size
|
|
69
|
+
}));
|
|
70
|
+
};
|
|
71
|
+
request.onload = () => {
|
|
72
|
+
if (request.status !== 201) return fail(refusals[request.status] ?? "Unexpected");
|
|
73
|
+
Option.match(factsOf(request.responseText), {
|
|
74
|
+
onNone: () => fail("Unexpected"),
|
|
75
|
+
onSome: (asset) => {
|
|
76
|
+
Queue.offerUnsafe(queue, Uploaded.make({ asset }));
|
|
77
|
+
Queue.endUnsafe(queue);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
request.onerror = () => fail("Network");
|
|
82
|
+
request.open("POST", options.url ?? "/_media/upload");
|
|
83
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) request.setRequestHeader(name, value);
|
|
84
|
+
request.send(file);
|
|
85
|
+
return request;
|
|
86
|
+
}), (request) => Effect.sync(() => request.abort())));
|
|
87
|
+
// src/browser/index.ts
|
|
6
88
|
/**
|
|
7
89
|
* An image's facts read in the browser, where it is chosen: `describe(key,
|
|
8
90
|
* bytes)` over `inspectorBrowser()` gives its `ImageAsset`, size, hash and
|
|
@@ -63,7 +145,6 @@ const inspectorBrowser = (options = {}) => {
|
|
|
63
145
|
};
|
|
64
146
|
}), (bitmap) => Effect.sync(() => bitmap.close())) });
|
|
65
147
|
};
|
|
66
|
-
|
|
67
|
-
export { inspectorBrowser };
|
|
148
|
+
export { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, inspectorBrowser, upload };
|
|
68
149
|
|
|
69
150
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/browser/index.ts"],"sourcesContent":["/**\n * An image's facts read in the browser, where it is chosen: `describe(key,\n * bytes)` over `inspectorBrowser()` gives its `ImageAsset`, size, hash and\n * ThumbHash included, before it is uploaded or stored, with no server to ask.\n * The browser's own decoder reads it, so what it cannot show is refused here.\n */\nimport { Effect, Layer, Option } from 'effect'\nimport { Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { OriginalTooLarge, TransformFailed } from '../server/errors.js'\n\n// A ThumbHash is made from at most 100 pixels a side.\nconst THUMBNAIL_SIDE = 100\n\n// Bound each canvas readback while still checking every decoded pixel.\nconst ALPHA_TILE_SIDE = 512\n\n// About 50 megapixels, as the Node inspector. The browser decodes the file before its size is\n// known, so this bounds the canvas work after the decode, not the decode itself.\nconst DEFAULT_MAX_PIXELS = 50_000_000\n\n/**\n * The `Inspector` in a browser or a web worker: the size from the decoded\n * picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any\n * decoded pixel is not opaque. A file the browser cannot decode is\n * `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels\n * released at once.\n */\nexport const inspectorBrowser = (\n options: { readonly maxPixels?: number } = {},\n): Layer.Layer<Inspector> => {\n const maxPixels = nonNegativeInteger('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS)\n return Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.acquireUseRelease(\n Effect.tryPromise({\n try: () => createImageBitmap(new Blob([bytes])),\n catch: () => new TransformFailed({}),\n }),\n bitmap =>\n Effect.gen(function* () {\n const { width, height } = bitmap\n if (width * height > maxPixels) {\n return yield* new OriginalTooLarge({\n size: width * height,\n limit: maxPixels,\n unit: 'pixels',\n })\n }\n const alphaCanvas = new OffscreenCanvas(\n Math.min(width, ALPHA_TILE_SIDE),\n Math.min(height, ALPHA_TILE_SIDE),\n )\n const alphaContext = alphaCanvas.getContext('2d')\n if (alphaContext === null) return yield* new TransformFailed({})\n let alpha = false\n for (let top = 0; top < height && !alpha; top += ALPHA_TILE_SIDE) {\n for (let left = 0; left < width && !alpha; left += ALPHA_TILE_SIDE) {\n const tileWidth = Math.min(ALPHA_TILE_SIDE, width - left)\n const tileHeight = Math.min(ALPHA_TILE_SIDE, height - top)\n alphaCanvas.width = tileWidth\n alphaCanvas.height = tileHeight\n alphaContext.drawImage(\n bitmap,\n left,\n top,\n tileWidth,\n tileHeight,\n 0,\n 0,\n tileWidth,\n tileHeight,\n )\n const pixels = alphaContext.getImageData(0, 0, tileWidth, tileHeight).data\n for (let at = 3; at < pixels.length && !alpha; at += 4) alpha = pixels[at]! < 255\n }\n }\n const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(width, height))\n const side = (length: number) => Math.max(1, Math.round(length * scale))\n const canvas = new OffscreenCanvas(side(width), side(height))\n const context = canvas.getContext('2d')\n if (context === null) return yield* new TransformFailed({})\n context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n const rgba = new Uint8Array(\n context.getImageData(0, 0, canvas.width, canvas.height).data.buffer,\n )\n return {\n width,\n height,\n alpha,\n thumbnail: Option.some({ width: canvas.width, height: canvas.height, rgba }),\n }\n }),\n bitmap => Effect.sync(() => bitmap.close()),\n ),\n })\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,iBAAiB;AAGvB,MAAM,kBAAkB;AAIxB,MAAM,qBAAqB;;;;;;;;AAS3B,MAAa,oBACX,UAA2C,CAAC,MACjB;CAC3B,MAAM,YAAY,mBAAmB,aAAa,QAAQ,aAAa,kBAAkB;CACzF,OAAO,MAAM,QAAQ,WAAW,EAC9B,UAAS,UACP,OAAO,kBACL,OAAO,WAAW;EAChB,WAAW,kBAAkB,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;EAC9C,aAAa,IAAI,gBAAgB,CAAC,CAAC;CACrC,CAAC,IACD,WACE,OAAO,IAAI,aAAa;EACtB,MAAM,EAAE,OAAO,WAAW;EAC1B,IAAI,QAAQ,SAAS,WACnB,OAAO,OAAO,IAAI,iBAAiB;GACjC,MAAM,QAAQ;GACd,OAAO;GACP,MAAM;EACR,CAAC;EAEH,MAAM,cAAc,IAAI,gBACtB,KAAK,IAAI,OAAO,eAAe,GAC/B,KAAK,IAAI,QAAQ,eAAe,CAClC;EACA,MAAM,eAAe,YAAY,WAAW,IAAI;EAChD,IAAI,iBAAiB,MAAM,OAAO,OAAO,IAAI,gBAAgB,CAAC,CAAC;EAC/D,IAAI,QAA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","../../src/browser/index.ts"],"sourcesContent":["/**\n * An image sent to the upload route from a browser: the bytes go once, with\n * their progress reported as they go, and the route's facts come back as the\n * `HashedAsset` to store. `fetch` reports no upload progress, so this is an\n * `XMLHttpRequest`, and interrupting the stream aborts it.\n */\nimport { Cause, Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { HashedAsset } from '../asset.js'\n\n/** Why an upload did not end in facts: the route's refusal, or no answer at all. */\nexport const UploadRefusal = Schema.Literals([\n 'Forbidden',\n 'Unauthenticated',\n 'TooLarge',\n 'Unsupported',\n 'Malformed',\n /** No answer: the network failed, or the request was refused before reaching the route. */\n 'Network',\n /** An answer that is neither the route's facts nor one of its refusals. */\n 'Unexpected',\n])\nexport type UploadRefusal = typeof UploadRefusal.Type\n\nexport class UploadFailed extends Schema.TaggedError<UploadFailed>()('UploadFailed', {\n reason: UploadRefusal,\n /** The HTTP status, `0` when there was no answer. */\n status: Schema.Number,\n}) {}\n\n/** How far the bytes have gone: `loaded` of `total`. */\nexport const Progressed = Schema.TaggedStruct('Progressed', {\n loaded: Schema.Number,\n total: Schema.Number,\n})\n/** The route kept the image, and these are its facts. */\nexport const Uploaded = Schema.TaggedStruct('Uploaded', { asset: HashedAsset })\nexport const UploadEvent = Schema.Union([Progressed, Uploaded])\nexport type UploadEvent = typeof UploadEvent.Type\n\nconst refusals: Readonly<Record<number, UploadRefusal>> = {\n 400: 'Malformed',\n 401: 'Unauthenticated',\n 403: 'Forbidden',\n 413: 'TooLarge',\n 415: 'Unsupported',\n}\n\nconst decodeFacts = Schema.decodeUnknownOption(HashedAsset)\n\n/** The facts in a 201's body, or none for a body that is not them. */\nconst factsOf = (body: string): Option.Option<HashedAsset> => {\n try {\n return decodeFacts(JSON.parse(body))\n } catch {\n return Option.none()\n }\n}\n\nexport interface UploadOptions {\n /** Where the route is. Default `/_media/upload`. */\n readonly url?: string | undefined\n /**\n * Sent with the bytes. A page's own session cookie goes with a same-origin\n * request already: never put a deployment's secret (`uploadPolicyBearer`'s) here,\n * where every visitor can read it.\n */\n readonly headers?: Readonly<Record<string, string>> | undefined\n}\n\n/**\n * Sends `file` to the upload route as its body, which the browser types by the\n * file's own `type`:\n * `Progressed` as the bytes go, then one `Uploaded` with the facts, and the\n * stream ends. A refusal fails it with `UploadFailed`, naming why; a file the\n * route does not take as an image is `Unsupported`. Interrupting it aborts the\n * request.\n */\nexport const upload = (\n file: Blob,\n options: UploadOptions = {},\n): Stream.Stream<UploadEvent, UploadFailed> =>\n Stream.callback<UploadEvent, UploadFailed>(queue =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const request = new XMLHttpRequest()\n const fail = (reason: UploadRefusal) =>\n Queue.failCauseUnsafe(\n queue,\n Cause.fail(new UploadFailed({ reason, status: request.status })),\n )\n request.upload.onprogress = event => {\n Queue.offerUnsafe(\n queue,\n Progressed.make({\n loaded: event.loaded,\n total: event.lengthComputable ? event.total : file.size,\n }),\n )\n }\n request.onload = () => {\n if (request.status !== 201) return fail(refusals[request.status] ?? 'Unexpected')\n Option.match(factsOf(request.responseText), {\n onNone: () => fail('Unexpected'),\n onSome: asset => {\n Queue.offerUnsafe(queue, Uploaded.make({ asset }))\n Queue.endUnsafe(queue)\n },\n })\n }\n request.onerror = () => fail('Network')\n request.open('POST', options.url ?? '/_media/upload')\n for (const [name, value] of Object.entries(options.headers ?? {}))\n request.setRequestHeader(name, value)\n request.send(file)\n return request\n }),\n // Done or not, the request goes with the stream: abort is a no-op on one that finished.\n request => Effect.sync(() => request.abort()),\n ),\n )\n","/**\n * An image's facts read in the browser, where it is chosen: `describe(key,\n * bytes)` over `inspectorBrowser()` gives its `ImageAsset`, size, hash and\n * ThumbHash included, before it is uploaded or stored, with no server to ask.\n * The browser's own decoder reads it, so what it cannot show is refused here.\n */\nimport { Effect, Layer, Option } from 'effect'\nimport { Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { OriginalTooLarge, TransformFailed } from '../server/errors.js'\n\n// A ThumbHash is made from at most 100 pixels a side.\nconst THUMBNAIL_SIDE = 100\n\n// Bound each canvas readback while still checking every decoded pixel.\nconst ALPHA_TILE_SIDE = 512\n\n// About 50 megapixels, as the Node inspector. The browser decodes the file before its size is\n// known, so this bounds the canvas work after the decode, not the decode itself.\nconst DEFAULT_MAX_PIXELS = 50_000_000\n\n/**\n * The `Inspector` in a browser or a web worker: the size from the decoded\n * picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any\n * decoded pixel is not opaque. A file the browser cannot decode is\n * `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels\n * released at once.\n */\nexport const inspectorBrowser = (\n options: { readonly maxPixels?: number } = {},\n): Layer.Layer<Inspector> => {\n const maxPixels = nonNegativeInteger('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS)\n return Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.acquireUseRelease(\n Effect.tryPromise({\n try: () => createImageBitmap(new Blob([bytes])),\n catch: () => new TransformFailed({}),\n }),\n bitmap =>\n Effect.gen(function* () {\n const { width, height } = bitmap\n if (width * height > maxPixels) {\n return yield* new OriginalTooLarge({\n size: width * height,\n limit: maxPixels,\n unit: 'pixels',\n })\n }\n const alphaCanvas = new OffscreenCanvas(\n Math.min(width, ALPHA_TILE_SIDE),\n Math.min(height, ALPHA_TILE_SIDE),\n )\n const alphaContext = alphaCanvas.getContext('2d')\n if (alphaContext === null) return yield* new TransformFailed({})\n let alpha = false\n for (let top = 0; top < height && !alpha; top += ALPHA_TILE_SIDE) {\n for (let left = 0; left < width && !alpha; left += ALPHA_TILE_SIDE) {\n const tileWidth = Math.min(ALPHA_TILE_SIDE, width - left)\n const tileHeight = Math.min(ALPHA_TILE_SIDE, height - top)\n alphaCanvas.width = tileWidth\n alphaCanvas.height = tileHeight\n alphaContext.drawImage(\n bitmap,\n left,\n top,\n tileWidth,\n tileHeight,\n 0,\n 0,\n tileWidth,\n tileHeight,\n )\n const pixels = alphaContext.getImageData(0, 0, tileWidth, tileHeight).data\n for (let at = 3; at < pixels.length && !alpha; at += 4) alpha = pixels[at]! < 255\n }\n }\n const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(width, height))\n const side = (length: number) => Math.max(1, Math.round(length * scale))\n const canvas = new OffscreenCanvas(side(width), side(height))\n const context = canvas.getContext('2d')\n if (context === null) return yield* new TransformFailed({})\n context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n const rgba = new Uint8Array(\n context.getImageData(0, 0, canvas.width, canvas.height).data.buffer,\n )\n return {\n width,\n height,\n alpha,\n thumbnail: Option.some({ width: canvas.width, height: canvas.height, rgba }),\n }\n }),\n bitmap => Effect.sync(() => bitmap.close()),\n ),\n })\n}\n\nexport {\n Progressed,\n UploadEvent,\n UploadFailed,\n UploadRefusal,\n Uploaded,\n upload,\n type UploadOptions,\n} from './upload.js'\n"],"mappings":";;;;;;;;;;;;AAUA,MAAa,gBAAgB,OAAO,SAAS;CAC3C;CACA;CACA;CACA;CACA;CAEA;CAEA;AACF,CAAC;AAGD,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACnF,QAAQ;;CAER,QAAQ,OAAO;AACjB,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,aAAa,OAAO,aAAa,cAAc;CAC1D,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CAAC;;AAED,MAAa,WAAW,OAAO,aAAa,YAAY,EAAE,OAAO,YAAY,CAAC;AAC9E,MAAa,cAAc,OAAO,MAAM,CAAC,YAAY,QAAQ,CAAC;AAG9D,MAAM,WAAoD;CACxD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;AAEA,MAAM,cAAc,OAAO,oBAAoB,WAAW;;AAG1D,MAAM,WAAW,SAA6C;CAC5D,IAAI;EACF,OAAO,YAAY,KAAK,MAAM,IAAI,CAAC;CACrC,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;;;;;;;;;AAqBA,MAAa,UACX,MACA,UAAyB,CAAC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