foldkit-media 0.6.0 → 0.8.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 +200 -7
- package/dist/browser/index.d.ts +2 -2
- package/dist/browser/index.js +2 -2
- package/dist/browser/index.js.map +1 -1
- package/dist/browser/upload.d.ts +33 -2
- package/dist/browser/upload.d.ts.map +1 -1
- package/dist/browser/upload.js +59 -25
- package/dist/browser/upload.js.map +1 -1
- package/dist/file.d.ts +16 -0
- package/dist/file.d.ts.map +1 -0
- package/dist/file.js +18 -0
- package/dist/file.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/server/diagnostics.d.ts +9 -1
- package/dist/server/diagnostics.d.ts.map +1 -1
- package/dist/server/diagnostics.js +7 -1
- package/dist/server/diagnostics.js.map +1 -1
- package/dist/server/fetch.d.ts +9 -2
- package/dist/server/fetch.d.ts.map +1 -1
- package/dist/server/fetch.js +7 -5
- package/dist/server/fetch.js.map +1 -1
- package/dist/server/fileRules.d.ts +34 -0
- package/dist/server/fileRules.d.ts.map +1 -0
- package/dist/server/fileRules.js +78 -0
- package/dist/server/fileRules.js.map +1 -0
- package/dist/server/fileStore.d.ts +68 -0
- package/dist/server/fileStore.d.ts.map +1 -0
- package/dist/server/fileStore.js +95 -0
- package/dist/server/fileStore.js.map +1 -0
- package/dist/server/files.d.ts +88 -0
- package/dist/server/files.d.ts.map +1 -0
- package/dist/server/files.js +195 -0
- package/dist/server/files.js.map +1 -0
- package/dist/server/index.d.ts +5 -2
- package/dist/server/index.js +3 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -21,6 +21,9 @@ a resizing server, its Cloudflare and Node layers, uploads, and Vite plugins.
|
|
|
21
21
|
view only reads them.
|
|
22
22
|
- **Variants** belong to whoever makes them, a CDN or a resizing server, and
|
|
23
23
|
are a cache: they can be made again from the original.
|
|
24
|
+
- **An uploaded file** (any file, not an image to resize) belongs to the
|
|
25
|
+
`FileStore`, with the facts the route recorded; which row holds it, and who
|
|
26
|
+
may read it, is the application's ([Files](#files)).
|
|
24
27
|
- **Which variant a page shows** is the browser's choice, from `srcset` and
|
|
25
28
|
`sizes`. Nothing in your Model decides it.
|
|
26
29
|
- **An icon's drawing** belongs to its set (Lucide, an application's SVG
|
|
@@ -125,7 +128,7 @@ reads it and writes its variants beside the bundle. Add the plugin, and the
|
|
|
125
128
|
type of a `?image` import (`"types": ["foldkit-media/client"]` in the
|
|
126
129
|
`tsconfig`):
|
|
127
130
|
|
|
128
|
-
```ts
|
|
131
|
+
```ts standalone
|
|
129
132
|
// vite.config.ts
|
|
130
133
|
import { images } from 'foldkit-media/vite'
|
|
131
134
|
import { defineConfig } from 'vite'
|
|
@@ -133,6 +136,11 @@ import { defineConfig } from 'vite'
|
|
|
133
136
|
export default defineConfig({ plugins: [images({ sources: ['avif'], fallback: 'webp' })] })
|
|
134
137
|
```
|
|
135
138
|
|
|
139
|
+
<!-- docs-check standalone
|
|
140
|
+
import type { HtmlBuilder } from 'foldkit/html'
|
|
141
|
+
declare const h: HtmlBuilder<never>
|
|
142
|
+
import 'foldkit-media/client'
|
|
143
|
+
-->
|
|
136
144
|
```ts
|
|
137
145
|
import hero from './hero.jpg?image'
|
|
138
146
|
import { Layout } from 'foldkit-media'
|
|
@@ -165,6 +173,11 @@ no head tags, so `Picture.preload(picture)` returns the `<link rel="preload">`
|
|
|
165
173
|
for your SSR `head` function to include, from the same `Picture.derive` the view
|
|
166
174
|
draws with `priority: true`:
|
|
167
175
|
|
|
176
|
+
<!-- docs-check standalone
|
|
177
|
+
import { Option } from 'effect'
|
|
178
|
+
import { Picture } from 'foldkit-media'
|
|
179
|
+
declare const picture: Option.Option<Picture.Picture>
|
|
180
|
+
-->
|
|
168
181
|
```ts
|
|
169
182
|
const preloadTag = Option.map(picture, Picture.preload)
|
|
170
183
|
```
|
|
@@ -429,6 +442,22 @@ below). It refuses with `UploadForbidden` (`403`), or with
|
|
|
429
442
|
`UploadUnauthenticated` (`401`) when it cannot tell who is asking, so a client
|
|
430
443
|
whose session ended knows to sign in again.
|
|
431
444
|
|
|
445
|
+
<!-- docs-check standalone
|
|
446
|
+
import { Effect, Option, Schema } from 'effect'
|
|
447
|
+
import { Guards } from 'foldkit-guard'
|
|
448
|
+
const User = Schema.Struct({ id: Schema.String, role: Schema.Literals(['admin', 'editor']) })
|
|
449
|
+
type User = typeof User.Type
|
|
450
|
+
const G = Guards.declare(
|
|
451
|
+
'Media',
|
|
452
|
+
User,
|
|
453
|
+
guard => ({ isEditor: guard.principal() }),
|
|
454
|
+
{ key: user => user.id, unguarded: 'deny' },
|
|
455
|
+
)
|
|
456
|
+
const Policy = G.implement({
|
|
457
|
+
isEditor: principal => Option.exists(principal, user => user.role === 'editor'),
|
|
458
|
+
})
|
|
459
|
+
declare const resolve: (request: Request) => Effect.Effect<Option.Option<User>>
|
|
460
|
+
-->
|
|
432
461
|
```ts
|
|
433
462
|
import { Layer } from 'effect'
|
|
434
463
|
import { GuardMedia } from 'foldkit-guard/media'
|
|
@@ -535,6 +564,157 @@ often it is asked: each admitted call reads up to `maxBytes` and decodes it,
|
|
|
535
564
|
so the `UploadPolicy` is where an application limits who calls, and how often. What cannot be read (a host
|
|
536
565
|
not allowed, a missing file, no image) is a `422`, saying only that.
|
|
537
566
|
|
|
567
|
+
### Files
|
|
568
|
+
|
|
569
|
+
Images are not the only uploads: a form may take a PDF, a spreadsheet, any
|
|
570
|
+
file. `POST /_media/files` keeps any file, and `GET /_media/files/:key` serves
|
|
571
|
+
it back as a download. They are a route set of their own (`fileLayer`), apart
|
|
572
|
+
from the image routes, and a server that mounts only the image routes serves
|
|
573
|
+
no file. Files are kept in a `FileStore` under 32-hex keys, and the variant
|
|
574
|
+
server reads only a 64-hex content hash, so no request to it names a file.
|
|
575
|
+
|
|
576
|
+
**Who owns what.** The route owns the bytes and the facts it recorded about
|
|
577
|
+
them: a key it minted, and the name, type and size the uploader declared. The
|
|
578
|
+
application owns which row holds a file and who may read it. A form only ever
|
|
579
|
+
holds a `FileAsset` (`{ key, name, type, size }`, from `foldkit-media`), which
|
|
580
|
+
is the client's word once it has passed through the client.
|
|
581
|
+
|
|
582
|
+
```text
|
|
583
|
+
browser: uploadFile(file) -> POST /_media/files -> key minted, bytes + record kept -> FileAsset
|
|
584
|
+
form submits the FileAsset -> your mutation: authorize, then keepOrClaim -> the server's FileAsset on the row
|
|
585
|
+
GET /_media/files/:key -> FileReadPolicy (who asks, may they read this key) -> the bytes, as an attachment
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
A key is 128 random bits, so it cannot be guessed, and each upload's bytes
|
|
589
|
+
are kept on their own, even when equal to another's: sharing them would make
|
|
590
|
+
a second upload of the same bytes answer faster, telling the uploader that
|
|
591
|
+
someone already holds them.
|
|
592
|
+
|
|
593
|
+
```ts
|
|
594
|
+
import { Effect, Layer, Option } from 'effect'
|
|
595
|
+
import { SecureRandom } from 'effect/crypto'
|
|
596
|
+
import { KeyValueStore } from 'effect/persistence'
|
|
597
|
+
import type { FileAsset } from 'foldkit-media'
|
|
598
|
+
import {
|
|
599
|
+
FileUploadPolicy,
|
|
600
|
+
UploadForbidden,
|
|
601
|
+
fileLayer,
|
|
602
|
+
fileReadPolicy,
|
|
603
|
+
filesKeyValueStore,
|
|
604
|
+
keepOrClaim,
|
|
605
|
+
} from 'foldkit-media/server'
|
|
606
|
+
|
|
607
|
+
// Your own: who a request is, and which rows hold which file.
|
|
608
|
+
declare const userOf: (headers: Headers) => Option.Option<string>
|
|
609
|
+
declare const rowHolding: (key: string) => Effect.Effect<Option.Option<{ readonly owner: string }>>
|
|
610
|
+
|
|
611
|
+
const files = fileLayer({ accept: ['application/pdf', 'image/*'] }).pipe(
|
|
612
|
+
Layer.provide(
|
|
613
|
+
Layer.mergeAll(
|
|
614
|
+
filesKeyValueStore(),
|
|
615
|
+
Layer.succeed(FileUploadPolicy, {
|
|
616
|
+
admit: request =>
|
|
617
|
+
Option.match(userOf(new Headers(request.headers)), {
|
|
618
|
+
onNone: () => Effect.fail(new UploadForbidden({})),
|
|
619
|
+
onSome: Effect.succeed,
|
|
620
|
+
}),
|
|
621
|
+
}),
|
|
622
|
+
fileReadPolicy({
|
|
623
|
+
resolve: request => Effect.succeed(userOf(new Headers(request.headers))),
|
|
624
|
+
read: (user, key) =>
|
|
625
|
+
rowHolding(key).pipe(
|
|
626
|
+
Effect.map(row =>
|
|
627
|
+
Option.exists(row, ({ owner }) => Option.contains(user, owner)),
|
|
628
|
+
),
|
|
629
|
+
),
|
|
630
|
+
}),
|
|
631
|
+
),
|
|
632
|
+
),
|
|
633
|
+
Layer.provide(Layer.merge(KeyValueStore.layerMemory, SecureRandom.layerWebCrypto)),
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
// In the mutation that saves a row, once the write is authorized:
|
|
637
|
+
const attached = (held: Option.Option<FileAsset>, submitted: FileAsset, user: string) =>
|
|
638
|
+
keepOrClaim(held, submitted, user)
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
- **`FileUploadPolicy.admit(request)`** says who is uploading, before a byte
|
|
642
|
+
is read, and answers their id. Only that id may claim the file later, so it
|
|
643
|
+
must be stable and never given to another person. An empty id is refused
|
|
644
|
+
(`403`) and reported (`OwnerMissing`): one id for every visitor would let
|
|
645
|
+
anyone claim anyone's upload.
|
|
646
|
+
- **`fileReadPolicy({ resolve, read })`** asks in two steps, before the store
|
|
647
|
+
is read. `resolve` says who is asking from the request alone, never the key,
|
|
648
|
+
or fails `FileUnauthenticated` (`401`) when it cannot tell, so a client can
|
|
649
|
+
ask the reader to sign in again. `read` says whether they may read a key,
|
|
650
|
+
typically by finding the row that holds it. A no is a `404`, the same answer
|
|
651
|
+
as a key nobody uploaded, so a refusal never says whether a file exists.
|
|
652
|
+
- **`keepOrClaim(held, submitted, owner)`** is what a save stores. When the
|
|
653
|
+
submitted key is the file the row already holds, it keeps that file and
|
|
654
|
+
claims nothing, so a teammate re-saving a row is fine. Otherwise it claims
|
|
655
|
+
the key: `FileStore.claim` answers the facts the route recorded, once, to
|
|
656
|
+
the uploader, within `claimWithin` (a day by default, an option of
|
|
657
|
+
`filesKeyValueStore`), and fails `FileUnclaimed` for anything else (an
|
|
658
|
+
unknown key, an expired one, someone else's, one claimed already), each
|
|
659
|
+
alike. Call it after authorizing the write, so a refused write claims
|
|
660
|
+
nothing. A key moves to another row only by being uploaded again.
|
|
661
|
+
|
|
662
|
+
**A download cannot run here.** Every answer the download route writes,
|
|
663
|
+
refusals included, is `application/octet-stream` with `nosniff`, a
|
|
664
|
+
`Content-Security-Policy` of `sandbox; default-src 'none'`,
|
|
665
|
+
`Cross-Origin-Resource-Policy: same-origin` and `Cache-Control: private,
|
|
666
|
+
no-store`. A file comes as an attachment named by its record, never by the
|
|
667
|
+
request, both as RFC 6266's `filename*` and as an ASCII fallback. The
|
|
668
|
+
declared type is never served, so an HTML file uploaded as a PDF downloads
|
|
669
|
+
and runs nothing. None of the image routes' cross-origin headers are sent.
|
|
670
|
+
What the router answers before the route runs (another method, a path it
|
|
671
|
+
cannot decode) and a `500` carry no body, so nothing in them can run.
|
|
672
|
+
|
|
673
|
+
**What an upload must be.** The body is `application/octet-stream`, and the
|
|
674
|
+
file's name and type travel in `x-foldkit-file-name` (percent-encoded UTF-8)
|
|
675
|
+
and `x-foldkit-file-type`. A page on another site cannot send either without a
|
|
676
|
+
preflight, which the route never answers, so a cookie alone cannot upload from
|
|
677
|
+
elsewhere. An application that adds CORS middleware answering `OPTIONS` for
|
|
678
|
+
these paths undoes that. The name must be non-empty, at most 255 bytes, with
|
|
679
|
+
no control or format character (bidi overrides, zero-width characters), line
|
|
680
|
+
separator or slash. The type is parsed, its parameters dropped, and compared
|
|
681
|
+
with `accept` without regard to case: `text/html;x=image/png` is `text/html`.
|
|
682
|
+
`accept` is required, `'*'` for any type. The client writes the type, so
|
|
683
|
+
`accept` shapes the product and secures nothing; to check the content itself
|
|
684
|
+
(magic numbers, a scan), give `inspect: (bytes, declared) => Effect<void,
|
|
685
|
+
FileRefused>`, run before anything is kept.
|
|
686
|
+
|
|
687
|
+
| Answer | Why |
|
|
688
|
+
| --- | --- |
|
|
689
|
+
| `201` | Kept; the body is the `FileAsset`. |
|
|
690
|
+
| `400` | No name, or one that breaks a rule above; or a body that broke off. |
|
|
691
|
+
| `401` / `403` | The policy could not tell who is asking, or refused them. |
|
|
692
|
+
| `408` | The body came slower than `minBytesPerSecond` (32 KB/s by default) over 10 seconds. |
|
|
693
|
+
| `413` | Past `maxBytes` (20 MB by default), counted as the body streams. |
|
|
694
|
+
| `415` | Not `application/octet-stream`, a type outside `accept`, or refused by `inspect`. |
|
|
695
|
+
| `429` | `Admission`, when one is given, refused this uploader (`Retry-After` says when to try). |
|
|
696
|
+
| `503` | Every slot is taken (`maxConcurrent`, 2 by default), or this uploader already has one. It does not queue: try again soon. |
|
|
697
|
+
|
|
698
|
+
**Memory.** An upload holds about twice its size while it is read, so the
|
|
699
|
+
defaults hold at most `2 × 20 MB × 2 = 80 MB`, within a 128 MB Worker. Lower
|
|
700
|
+
`maxBytes` or `maxConcurrent` where an `inspect` copies the bytes. The slots
|
|
701
|
+
belong to the server (a Worker isolate), built once with the layer. A
|
|
702
|
+
download holds its file in memory too, and downloads take no slot, so a
|
|
703
|
+
Worker serving many large files to many readers at once should keep them
|
|
704
|
+
elsewhere (R2 behind a signed URL). One slot per uploader stops one account
|
|
705
|
+
taking every slot, not several: at the minimum rate a 20 MB body takes about
|
|
706
|
+
eleven minutes, so `maxConcurrent` accounts can hold every slot that long.
|
|
707
|
+
Where that matters, ask `Admission` to limit uploads per owner.
|
|
708
|
+
|
|
709
|
+
From a browser, `uploadFile(file, { url?, headers? })` (`foldkit-media/browser`)
|
|
710
|
+
sends the file as the route expects, and is a `Stream` like `upload`:
|
|
711
|
+
`Progressed` as the bytes go, then `FileUploaded { asset }`. Its
|
|
712
|
+
`UploadFailed` reasons add `TooSlow`, `RateLimited` and `Busy` to `upload`'s.
|
|
713
|
+
In a Worker, `serveFetch`'s `files` hosts the route set. Not done here:
|
|
714
|
+
resumable uploads, range requests, quotas beyond `Admission`, and removing the
|
|
715
|
+
bytes of files nobody claimed (`claimWithin` stops their use; reclaiming the
|
|
716
|
+
space is a sweep left to the application).
|
|
717
|
+
|
|
538
718
|
### Written out at build
|
|
539
719
|
|
|
540
720
|
A static site needs no server for its hosted images: `materialize` makes every
|
|
@@ -542,7 +722,20 @@ variant the built pages name, through the server's own handler, and returns
|
|
|
542
722
|
them as files at their own paths, for `foldkit-ssr`'s `staticSite` `emit`:
|
|
543
723
|
|
|
544
724
|
```ts
|
|
545
|
-
|
|
725
|
+
import { NodeServices } from '@effect/platform-node'
|
|
726
|
+
import { readFileSync } from 'node:fs'
|
|
727
|
+
import { Layer } from 'effect'
|
|
728
|
+
import { KeyValueStore } from 'effect/persistence'
|
|
729
|
+
import {
|
|
730
|
+
materialize,
|
|
731
|
+
originalsKeyValueStore,
|
|
732
|
+
serveFetch,
|
|
733
|
+
variantsKeyValueStore,
|
|
734
|
+
} from 'foldkit-media/server'
|
|
735
|
+
import { transformerSharp } from 'foldkit-media/sharp'
|
|
736
|
+
import type { BuiltPage } from 'foldkit-ssr/vite'
|
|
737
|
+
|
|
738
|
+
const staticMedia = serveFetch<object>({
|
|
546
739
|
images: {
|
|
547
740
|
layer: () =>
|
|
548
741
|
Layer.mergeAll(transformerSharp(), originalsKeyValueStore(), variantsKeyValueStore()).pipe(
|
|
@@ -556,10 +749,10 @@ const env = {}
|
|
|
556
749
|
|
|
557
750
|
export const site = {
|
|
558
751
|
// …
|
|
559
|
-
emit: pages =>
|
|
752
|
+
emit: (pages: ReadonlyArray<BuiltPage>) =>
|
|
560
753
|
materialize({
|
|
561
754
|
pages,
|
|
562
|
-
fetch: request =>
|
|
755
|
+
fetch: request => staticMedia(request, env),
|
|
563
756
|
headersFile: readFileSync('public/_headers', 'utf8'),
|
|
564
757
|
}),
|
|
565
758
|
}
|
|
@@ -580,7 +773,7 @@ export const site = {
|
|
|
580
773
|
`foldkit-media/cloudflare` gives the services from a Worker's bindings, and
|
|
581
774
|
`serveFetch` is the Worker:
|
|
582
775
|
|
|
583
|
-
```ts
|
|
776
|
+
```ts standalone
|
|
584
777
|
import type { ImagesBinding, R2Bucket, RateLimit } from '@cloudflare/workers-types'
|
|
585
778
|
import { Layer } from 'effect'
|
|
586
779
|
import {
|
|
@@ -692,7 +885,7 @@ An icon is data too: `IconData` holds its `viewBox`, what its root paints
|
|
|
692
885
|
(`fill`, `stroke`), and its drawing as nodes, never markup to set as HTML. An
|
|
693
886
|
application imports icons by name, and the build reads them:
|
|
694
887
|
|
|
695
|
-
```ts
|
|
888
|
+
```ts standalone
|
|
696
889
|
// vite.config.ts
|
|
697
890
|
import { icons } from 'foldkit-media/vite'
|
|
698
891
|
import { defineConfig } from 'vite'
|
|
@@ -702,7 +895,7 @@ export default defineConfig({
|
|
|
702
895
|
})
|
|
703
896
|
```
|
|
704
897
|
|
|
705
|
-
```ts
|
|
898
|
+
```ts sketch
|
|
706
899
|
import { arrowLeft } from 'virtual:foldkit-icons/lucide'
|
|
707
900
|
import { logo } from 'virtual:foldkit-icons/app'
|
|
708
901
|
```
|
package/dist/browser/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
2
|
import { Inspector } from "../describe.js";
|
|
3
|
-
import { Progressed, UploadEvent, UploadFailed, UploadOptions, UploadRefusal, Uploaded, upload } from "./upload.js";
|
|
3
|
+
import { FileUploadEvent, FileUploaded, Progressed, UploadEvent, UploadFailed, UploadOptions, UploadRefusal, Uploaded, upload, uploadFile } from "./upload.js";
|
|
4
4
|
/**
|
|
5
5
|
* The `Inspector` in a browser or a web worker: the size from the decoded
|
|
6
6
|
* picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
|
|
@@ -11,5 +11,5 @@ import { Progressed, UploadEvent, UploadFailed, UploadOptions, UploadRefusal, Up
|
|
|
11
11
|
export declare const inspectorBrowser: (options?: {
|
|
12
12
|
readonly maxPixels?: number;
|
|
13
13
|
}) => Layer.Layer<Inspector>;
|
|
14
|
-
export { Progressed, UploadEvent, UploadFailed, type UploadOptions, UploadRefusal, Uploaded, upload };
|
|
14
|
+
export { FileUploadEvent, FileUploaded, Progressed, UploadEvent, UploadFailed, type UploadOptions, UploadRefusal, Uploaded, upload, uploadFile };
|
|
15
15
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/browser/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { Effect, Layer, Option } from "effect";
|
|
|
2
2
|
import { Inspector } from "../describe.js";
|
|
3
3
|
import { nonNegativeInteger } from "../limits.js";
|
|
4
4
|
import { OriginalTooLarge, TransformFailed } from "../server/errors.js";
|
|
5
|
-
import { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, upload } from "./upload.js";
|
|
5
|
+
import { FileUploadEvent, FileUploaded, Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, upload, uploadFile } from "./upload.js";
|
|
6
6
|
// src/browser/index.ts
|
|
7
7
|
/**
|
|
8
8
|
* An image's facts read in the browser, where it is chosen: `describe(key,
|
|
@@ -64,6 +64,6 @@ const inspectorBrowser = (options = {}) => {
|
|
|
64
64
|
};
|
|
65
65
|
}), (bitmap) => Effect.sync(() => bitmap.close())) });
|
|
66
66
|
};
|
|
67
|
-
export { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, inspectorBrowser, upload };
|
|
67
|
+
export { FileUploadEvent, FileUploaded, Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, inspectorBrowser, upload, uploadFile };
|
|
68
68
|
|
|
69
69
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","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\nexport {\n Progressed,\n UploadEvent,\n UploadFailed,\n UploadRefusal,\n Uploaded,\n upload,\n type UploadOptions,\n} from './upload.js'\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;EAE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O,KAAK;IAAE,OAAO,OAAO;IAAO,QAAQ,OAAO;IAAQ;GAAK,CAAC;EAC7E;CACF,CAAC,IACH,WAAU,OAAO,WAAW,OAAO,MAAM,CAAC,CAC5C,EACJ,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","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\nexport {\n FileUploadEvent,\n FileUploaded,\n Progressed,\n UploadEvent,\n UploadFailed,\n UploadRefusal,\n Uploaded,\n upload,\n uploadFile,\n type UploadOptions,\n} from './upload.js'\n"],"mappings":";;;;;;;;;;;;AAYA,MAAM,iBAAiB;AAGvB,MAAM,kBAAkB;AAIxB,MAAM,qBAAqB;;;;;;;;AAS3B,MAAa,oBACX,UAA2C,CAAC,MACjB;CAC3B,MAAM,YAAY,mBAAmB,aAAa,QAAQ,aAAa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AAS,IAAI,gBAAgB,KAAK,KAAK,GAAG,KAAK,MAAM,CAAC;EAC5D,MAAM,UAAU,OAAO,WAAW,IAAI;EACtC,IAAI,YAAY,MAAM,OAAO,OAAO,IAAI,gBAAgB,CAAC,CAAC;EAC1D,QAAQ,UAAU,QAAQ,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;EAC3D,MAAM,OAAO,IAAI,WACf,QAAQ,aAAa,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM,CAAC,CAAC,KAAK,MAC/D;EACA,OAAO;GACL;GACA;GACA;GACA,WAAW,OAAO,KAAK;IAAE,OAAO,OAAO;IAAO,QAAQ,OAAO;IAAQ;GAAK,CAAC;EAC7E;CACF,CAAC,IACH,WAAU,OAAO,WAAW,OAAO,MAAM,CAAC,CAC5C,EACJ,CAAC;AACH"}
|
package/dist/browser/upload.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Cause, Schema, Stream } from "effect";
|
|
2
2
|
import { HashedAsset } from "../asset.js";
|
|
3
3
|
/** Why an upload did not end in facts: the route's refusal, or no answer at all. */
|
|
4
|
-
export declare const UploadRefusal: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "Network", "Unexpected"]>;
|
|
4
|
+
export declare const UploadRefusal: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "TooSlow", "Busy", "RateLimited", "Network", "Unexpected"]>;
|
|
5
5
|
export type UploadRefusal = typeof UploadRefusal.Type;
|
|
6
6
|
declare const UploadFailed_base: Schema.Class<UploadFailed, Schema.TaggedStruct<"UploadFailed", {
|
|
7
|
-
readonly reason: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "Network", "Unexpected"]>;
|
|
7
|
+
readonly reason: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "TooSlow", "Busy", "RateLimited", "Network", "Unexpected"]>;
|
|
8
8
|
/** The HTTP status, `0` when there was no answer. */
|
|
9
9
|
readonly status: Schema.Number;
|
|
10
10
|
}>, Cause.YieldableError>;
|
|
@@ -63,6 +63,27 @@ export declare const UploadEvent: Schema.Union<readonly [Schema.TaggedStruct<"Pr
|
|
|
63
63
|
}>>;
|
|
64
64
|
}>]>;
|
|
65
65
|
export type UploadEvent = typeof UploadEvent.Type;
|
|
66
|
+
/** The file route kept the file, and these are its facts. */
|
|
67
|
+
export declare const FileUploaded: Schema.TaggedStruct<"FileUploaded", {
|
|
68
|
+
readonly asset: Schema.Struct<{
|
|
69
|
+
readonly key: Schema.String;
|
|
70
|
+
readonly name: Schema.String;
|
|
71
|
+
readonly type: Schema.String;
|
|
72
|
+
readonly size: Schema.Number;
|
|
73
|
+
}>;
|
|
74
|
+
}>;
|
|
75
|
+
export declare const FileUploadEvent: Schema.Union<readonly [Schema.TaggedStruct<"Progressed", {
|
|
76
|
+
readonly loaded: Schema.Number;
|
|
77
|
+
readonly total: Schema.Number;
|
|
78
|
+
}>, Schema.TaggedStruct<"FileUploaded", {
|
|
79
|
+
readonly asset: Schema.Struct<{
|
|
80
|
+
readonly key: Schema.String;
|
|
81
|
+
readonly name: Schema.String;
|
|
82
|
+
readonly type: Schema.String;
|
|
83
|
+
readonly size: Schema.Number;
|
|
84
|
+
}>;
|
|
85
|
+
}>]>;
|
|
86
|
+
export type FileUploadEvent = typeof FileUploadEvent.Type;
|
|
66
87
|
export interface UploadOptions {
|
|
67
88
|
/** Where the route is. Default `/_media/upload`. */
|
|
68
89
|
readonly url?: string | undefined;
|
|
@@ -82,5 +103,15 @@ export interface UploadOptions {
|
|
|
82
103
|
* request.
|
|
83
104
|
*/
|
|
84
105
|
export declare const upload: (file: Blob, options?: UploadOptions) => Stream.Stream<UploadEvent, UploadFailed>;
|
|
106
|
+
/**
|
|
107
|
+
* Sends any `file` to the file route (`/_media/files` by default):
|
|
108
|
+
* `Progressed` as the bytes go, then one `FileUploaded` with the facts to
|
|
109
|
+
* claim on save. The body goes as `application/octet-stream`, which no page
|
|
110
|
+
* can send to another site without a preflight, and the file's name and type
|
|
111
|
+
* in headers of their own; a file the browser gives no type is declared
|
|
112
|
+
* `application/octet-stream`. A refusal fails it with `UploadFailed`, as does a
|
|
113
|
+
* file name that cannot be sent (`Malformed`, status `0`).
|
|
114
|
+
*/
|
|
115
|
+
export declare const uploadFile: (file: File, options?: UploadOptions) => Stream.Stream<FileUploadEvent, UploadFailed>;
|
|
85
116
|
export {};
|
|
86
117
|
//# sourceMappingURL=upload.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.d.ts","names":[],"sources":["../../src/browser/upload.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"upload.d.ts","names":[],"sources":["../../src/browser/upload.ts"],"mappings":";;;qBAYa,eAAa,OAAA;YAiBd,uBAAuB,cAAc;;;;;;qBAEpC,qBAAqB;;qBAOrB,YAAU,OAAA;;;;;qBAKV,UAAQ,OAAA;;;;;;;;;;;;;;;;;;;;;;qBACR,aAAW,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YACZ,qBAAqB,YAAY;;qBAEhC,cAAY,OAAA;;;;;;;;qBACZ,iBAAe,OAAA,gBAAA,OAAA;;;;;;;;;;;YAChB,yBAAyB,gBAAgB;iBA0BpC;;WAEN;;;;;;WAMA,UAAU,SAAS;;;;;;;;;;qBA2DjB,SAAM,MACX,MAAI,UACD,kBACR,OAAO,OAAO,aAAa;;;;;;;;;;qBAcjB,aAAU,MACf,MAAI,UACD,kBACR,OAAO,OAAO,iBAAiB"}
|
package/dist/browser/upload.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Cause, Effect, Option, Queue, Schema, Stream } from "effect";
|
|
2
2
|
import { HashedAsset } from "../asset.js";
|
|
3
|
+
import { FileAsset } from "../file.js";
|
|
3
4
|
// src/browser/upload.ts
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
-
* their progress reported as they go, and the route's facts come back
|
|
7
|
-
* `HashedAsset`
|
|
8
|
-
* `
|
|
6
|
+
* A file sent to an upload route from a browser: the bytes go once, with
|
|
7
|
+
* their progress reported as they go, and the route's facts come back: an
|
|
8
|
+
* image's `HashedAsset` (`upload`), or any file's `FileAsset` (`uploadFile`).
|
|
9
|
+
* `fetch` reports no upload progress, so this is an `XMLHttpRequest`, and
|
|
10
|
+
* interrupting the stream aborts it.
|
|
9
11
|
*/
|
|
10
12
|
/** Why an upload did not end in facts: the route's refusal, or no answer at all. */
|
|
11
13
|
const UploadRefusal = Schema.Literals([
|
|
@@ -14,6 +16,9 @@ const UploadRefusal = Schema.Literals([
|
|
|
14
16
|
"TooLarge",
|
|
15
17
|
"Unsupported",
|
|
16
18
|
"Malformed",
|
|
19
|
+
"TooSlow",
|
|
20
|
+
"Busy",
|
|
21
|
+
"RateLimited",
|
|
17
22
|
"Network",
|
|
18
23
|
"Unexpected"
|
|
19
24
|
]);
|
|
@@ -30,31 +35,30 @@ const Progressed = Schema.TaggedStruct("Progressed", {
|
|
|
30
35
|
/** The route kept the image, and these are its facts. */
|
|
31
36
|
const Uploaded = Schema.TaggedStruct("Uploaded", { asset: HashedAsset });
|
|
32
37
|
const UploadEvent = Schema.Union([Progressed, Uploaded]);
|
|
38
|
+
/** The file route kept the file, and these are its facts. */
|
|
39
|
+
const FileUploaded = Schema.TaggedStruct("FileUploaded", { asset: FileAsset });
|
|
40
|
+
const FileUploadEvent = Schema.Union([Progressed, FileUploaded]);
|
|
33
41
|
const refusals = {
|
|
34
42
|
400: "Malformed",
|
|
35
43
|
401: "Unauthenticated",
|
|
36
44
|
403: "Forbidden",
|
|
45
|
+
408: "TooSlow",
|
|
37
46
|
413: "TooLarge",
|
|
38
|
-
415: "Unsupported"
|
|
47
|
+
415: "Unsupported",
|
|
48
|
+
429: "RateLimited",
|
|
49
|
+
503: "Busy"
|
|
39
50
|
};
|
|
40
|
-
const decodeFacts = Schema.decodeUnknownOption(HashedAsset);
|
|
41
51
|
/** The facts in a 201's body, or none for a body that is not them. */
|
|
42
|
-
const factsOf = (body) => {
|
|
52
|
+
const factsOf = (schema) => (body) => {
|
|
43
53
|
try {
|
|
44
|
-
return
|
|
54
|
+
return Schema.decodeUnknownOption(schema)(JSON.parse(body));
|
|
45
55
|
} catch {
|
|
46
56
|
return Option.none();
|
|
47
57
|
}
|
|
48
58
|
};
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
* `Progressed` as the bytes go, then one `Uploaded` with the facts, and the
|
|
53
|
-
* stream ends. A refusal fails it with `UploadFailed`, naming why; a file the
|
|
54
|
-
* route does not take as an image is `Unsupported`. Interrupting it aborts the
|
|
55
|
-
* request.
|
|
56
|
-
*/
|
|
57
|
-
const upload = (file, options = {}) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
|
|
59
|
+
const imageFactsOf = factsOf(HashedAsset);
|
|
60
|
+
const fileFactsOf = factsOf(FileAsset);
|
|
61
|
+
const sent = (body, url, headers, read, done) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
|
|
58
62
|
const request = new XMLHttpRequest();
|
|
59
63
|
const fail = (reason) => Queue.failCauseUnsafe(queue, Cause.fail(new UploadFailed({
|
|
60
64
|
reason,
|
|
@@ -63,25 +67,55 @@ const upload = (file, options = {}) => Stream.callback((queue) => Effect.acquire
|
|
|
63
67
|
request.upload.onprogress = (event) => {
|
|
64
68
|
Queue.offerUnsafe(queue, Progressed.make({
|
|
65
69
|
loaded: event.loaded,
|
|
66
|
-
total: event.lengthComputable ? event.total :
|
|
70
|
+
total: event.lengthComputable ? event.total : body.size
|
|
67
71
|
}));
|
|
68
72
|
};
|
|
69
73
|
request.onload = () => {
|
|
70
74
|
if (request.status !== 201) return fail(refusals[request.status] ?? "Unexpected");
|
|
71
|
-
Option.match(
|
|
75
|
+
Option.match(read(request.responseText), {
|
|
72
76
|
onNone: () => fail("Unexpected"),
|
|
73
|
-
onSome: (
|
|
74
|
-
Queue.offerUnsafe(queue,
|
|
77
|
+
onSome: (facts) => {
|
|
78
|
+
Queue.offerUnsafe(queue, done(facts));
|
|
75
79
|
Queue.endUnsafe(queue);
|
|
76
80
|
}
|
|
77
81
|
});
|
|
78
82
|
};
|
|
79
83
|
request.onerror = () => fail("Network");
|
|
80
|
-
request.open("POST",
|
|
81
|
-
for (const [name, value] of Object.entries(
|
|
82
|
-
request.send(
|
|
84
|
+
request.open("POST", url);
|
|
85
|
+
for (const [name, value] of Object.entries(headers)) request.setRequestHeader(name, value);
|
|
86
|
+
request.send(body);
|
|
83
87
|
return request;
|
|
84
88
|
}), (request) => Effect.sync(() => request.abort())));
|
|
85
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Sends `file` to the upload route as its body, which the browser types by the
|
|
91
|
+
* file's own `type`:
|
|
92
|
+
* `Progressed` as the bytes go, then one `Uploaded` with the facts, and the
|
|
93
|
+
* stream ends. A refusal fails it with `UploadFailed`, naming why; a file the
|
|
94
|
+
* route does not take as an image is `Unsupported`. Interrupting it aborts the
|
|
95
|
+
* request.
|
|
96
|
+
*/
|
|
97
|
+
const upload = (file, options = {}) => sent(file, options.url ?? "/_media/upload", options.headers ?? {}, imageFactsOf, (asset) => Uploaded.make({ asset }));
|
|
98
|
+
/**
|
|
99
|
+
* Sends any `file` to the file route (`/_media/files` by default):
|
|
100
|
+
* `Progressed` as the bytes go, then one `FileUploaded` with the facts to
|
|
101
|
+
* claim on save. The body goes as `application/octet-stream`, which no page
|
|
102
|
+
* can send to another site without a preflight, and the file's name and type
|
|
103
|
+
* in headers of their own; a file the browser gives no type is declared
|
|
104
|
+
* `application/octet-stream`. A refusal fails it with `UploadFailed`, as does a
|
|
105
|
+
* file name that cannot be sent (`Malformed`, status `0`).
|
|
106
|
+
*/
|
|
107
|
+
const uploadFile = (file, options = {}) => Stream.suspend(() => {
|
|
108
|
+
const name = Option.liftThrowable(encodeURIComponent)(file.name);
|
|
109
|
+
return Option.isNone(name) ? Stream.fail(new UploadFailed({
|
|
110
|
+
reason: "Malformed",
|
|
111
|
+
status: 0
|
|
112
|
+
})) : sent(file, options.url ?? "/_media/files", {
|
|
113
|
+
...options.headers,
|
|
114
|
+
"content-type": "application/octet-stream",
|
|
115
|
+
"x-foldkit-file-name": name.value,
|
|
116
|
+
"x-foldkit-file-type": file.type === "" ? "application/octet-stream" : file.type
|
|
117
|
+
}, fileFactsOf, (asset) => FileUploaded.make({ asset }));
|
|
118
|
+
});
|
|
119
|
+
export { FileUploadEvent, FileUploaded, Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, upload, uploadFile };
|
|
86
120
|
|
|
87
121
|
//# sourceMappingURL=upload.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload.js","names":[],"sources":["../../src/browser/upload.ts"],"sourcesContent":["/**\n *
|
|
1
|
+
{"version":3,"file":"upload.js","names":[],"sources":["../../src/browser/upload.ts"],"sourcesContent":["/**\n * A file sent to an upload route from a browser: the bytes go once, with\n * their progress reported as they go, and the route's facts come back: an\n * image's `HashedAsset` (`upload`), or any file's `FileAsset` (`uploadFile`).\n * `fetch` reports no upload progress, so this is an `XMLHttpRequest`, and\n * interrupting the stream aborts it.\n */\nimport { Cause, Effect, Option, Queue, Schema, Stream } from 'effect'\nimport { HashedAsset } from '../asset.js'\nimport { FileAsset } from '../file.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 /** The file route: the body came too slowly. */\n 'TooSlow',\n /** The file route: every slot was taken, or this uploader already had one. Try again soon. */\n 'Busy',\n /** The file route: too many uploads lately. */\n 'RateLimited',\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/** The file route kept the file, and these are its facts. */\nexport const FileUploaded = Schema.TaggedStruct('FileUploaded', { asset: FileAsset })\nexport const FileUploadEvent = Schema.Union([Progressed, FileUploaded])\nexport type FileUploadEvent = typeof FileUploadEvent.Type\n\nconst refusals: Readonly<Record<number, UploadRefusal>> = {\n 400: 'Malformed',\n 401: 'Unauthenticated',\n 403: 'Forbidden',\n 408: 'TooSlow',\n 413: 'TooLarge',\n 415: 'Unsupported',\n 429: 'RateLimited',\n 503: 'Busy',\n}\n\n/** The facts in a 201's body, or none for a body that is not them. */\nconst factsOf =\n <A>(schema: Schema.Codec<A, unknown>) =>\n (body: string): Option.Option<A> => {\n try {\n return Schema.decodeUnknownOption(schema)(JSON.parse(body))\n } catch {\n return Option.none()\n }\n }\nconst imageFactsOf = factsOf(HashedAsset)\nconst fileFactsOf = factsOf(FileAsset)\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// The one sender: `body` goes with `headers`, its progress reported, and a 201 whose body\n// `read` takes ends the stream with `done` of it.\nconst sent = <A, Event>(\n body: Blob,\n url: string,\n headers: Readonly<Record<string, string>>,\n read: (body: string) => Option.Option<A>,\n done: (facts: A) => Event,\n): Stream.Stream<typeof Progressed.Type | Event, UploadFailed> =>\n Stream.callback<typeof Progressed.Type | Event, 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 : body.size,\n }),\n )\n }\n request.onload = () => {\n if (request.status !== 201) return fail(refusals[request.status] ?? 'Unexpected')\n Option.match(read(request.responseText), {\n onNone: () => fail('Unexpected'),\n onSome: facts => {\n Queue.offerUnsafe(queue, done(facts))\n Queue.endUnsafe(queue)\n },\n })\n }\n request.onerror = () => fail('Network')\n request.open('POST', url)\n for (const [name, value] of Object.entries(headers)) request.setRequestHeader(name, value)\n request.send(body)\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/**\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 sent(file, options.url ?? '/_media/upload', options.headers ?? {}, imageFactsOf, asset =>\n Uploaded.make({ asset }),\n )\n\n/**\n * Sends any `file` to the file route (`/_media/files` by default):\n * `Progressed` as the bytes go, then one `FileUploaded` with the facts to\n * claim on save. The body goes as `application/octet-stream`, which no page\n * can send to another site without a preflight, and the file's name and type\n * in headers of their own; a file the browser gives no type is declared\n * `application/octet-stream`. A refusal fails it with `UploadFailed`, as does a\n * file name that cannot be sent (`Malformed`, status `0`).\n */\nexport const uploadFile = (\n file: File,\n options: UploadOptions = {},\n): Stream.Stream<FileUploadEvent, UploadFailed> =>\n // A name `encodeURIComponent` refuses (a lone surrogate) is a failure of the stream, not a throw here.\n Stream.suspend(() => {\n const name = Option.liftThrowable(encodeURIComponent)(file.name)\n return Option.isNone(name)\n ? Stream.fail(new UploadFailed({ reason: 'Malformed', status: 0 }))\n : sent(\n file,\n options.url ?? '/_media/files',\n {\n ...options.headers,\n 'content-type': 'application/octet-stream',\n 'x-foldkit-file-name': name.value,\n 'x-foldkit-file-type': file.type === '' ? 'application/octet-stream' : file.type,\n },\n fileFactsOf,\n asset => FileUploaded.make({ asset }),\n )\n })\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,gBAAgB,OAAO,SAAS;CAC3C;CACA;CACA;CACA;CACA;CAEA;CAEA;CAEA;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,MAAa,eAAe,OAAO,aAAa,gBAAgB,EAAE,OAAO,UAAU,CAAC;AACpF,MAAa,kBAAkB,OAAO,MAAM,CAAC,YAAY,YAAY,CAAC;AAGtE,MAAM,WAAoD;CACxD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;;AAGA,MAAM,WACA,YACH,SAAmC;CAClC,IAAI;EACF,OAAO,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,MAAM,IAAI,CAAC;CAC5D,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AACF,MAAM,eAAe,QAAQ,WAAW;AACxC,MAAM,cAA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AAI,IACrB,OAAO,KAAK,IAAI,aAAa;EAAE,QAAQ;EAAa,QAAQ;CAAE,CAAC,CAAC,IAChE,KACE,MACA,QAAQ,OAAO,iBACf;EACE,GAAG,QAAQ;EACX,gBAAgB;EAChB,uBAAuB,KAAK;EAC5B,uBAAuB,KAAK,SAAS,KAAK,6BAA6B,KAAK;CAC9E,GACA,cACA,UAAS,aAAa,KAAK,EAAE,MAAM,CAAC,CACtC;AACN,CAAC"}
|
package/dist/file.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
/** A file's key: 128 random bits the server minted, as lowercase hex. */
|
|
3
|
+
export declare const FileKey: Schema.String;
|
|
4
|
+
/**
|
|
5
|
+
* A file the upload route kept: its key, and the name, type and size its
|
|
6
|
+
* uploader declared. The type is a label the route checked against its list,
|
|
7
|
+
* never what a download is served as.
|
|
8
|
+
*/
|
|
9
|
+
export declare const FileAsset: Schema.Struct<{
|
|
10
|
+
readonly key: Schema.String;
|
|
11
|
+
readonly name: Schema.String;
|
|
12
|
+
readonly type: Schema.String;
|
|
13
|
+
readonly size: Schema.Number;
|
|
14
|
+
}>;
|
|
15
|
+
export type FileAsset = typeof FileAsset.Type;
|
|
16
|
+
//# sourceMappingURL=file.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file.d.ts","names":[],"sources":["../src/file.ts"],"mappings":";;qBAGa,SAAO,OAAA;;;;;;qBAOP,WAAS,OAAA;;;;;;YAMV,mBAAmB,UAAU"}
|
package/dist/file.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// src/file.ts
|
|
3
|
+
/** A file's key: 128 random bits the server minted, as lowercase hex. */
|
|
4
|
+
const FileKey = Schema.String.check(Schema.isPattern(/^[0-9a-f]{32}$/));
|
|
5
|
+
/**
|
|
6
|
+
* A file the upload route kept: its key, and the name, type and size its
|
|
7
|
+
* uploader declared. The type is a label the route checked against its list,
|
|
8
|
+
* never what a download is served as.
|
|
9
|
+
*/
|
|
10
|
+
const FileAsset = Schema.Struct({
|
|
11
|
+
key: FileKey,
|
|
12
|
+
name: Schema.String,
|
|
13
|
+
type: Schema.String,
|
|
14
|
+
size: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))
|
|
15
|
+
});
|
|
16
|
+
export { FileAsset, FileKey };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=file.js.map
|
package/dist/file.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file.js","names":[],"sources":["../src/file.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** A file's key: 128 random bits the server minted, as lowercase hex. */\nexport const FileKey = Schema.String.check(Schema.isPattern(/^[0-9a-f]{32}$/))\n\n/**\n * A file the upload route kept: its key, and the name, type and size its\n * uploader declared. The type is a label the route checked against its list,\n * never what a download is served as.\n */\nexport const FileAsset = Schema.Struct({\n key: FileKey,\n name: Schema.String,\n type: Schema.String,\n size: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n})\nexport type FileAsset = typeof FileAsset.Type\n"],"mappings":";;;AAGA,MAAa,UAAU,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC;;;;;;AAO7E,MAAa,YAAY,OAAO,OAAO;CACrC,KAAK;CACL,MAAM,OAAO;CACb,MAAM,OAAO;CACb,MAAM,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;AAC5E,CAAC"}
|