foldkit-media 0.2.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.
Files changed (70) hide show
  1. package/README.md +92 -28
  2. package/dist/{asset-Dlkss5qp.d.mts → asset-BLo8VWmd.d.mts} +1 -3
  3. package/dist/asset-BLo8VWmd.d.mts.map +1 -0
  4. package/dist/browser/index.d.mts +86 -4
  5. package/dist/browser/index.d.mts.map +1 -1
  6. package/dist/browser/index.mjs +88 -7
  7. package/dist/browser/index.mjs.map +1 -1
  8. package/dist/cloudflare/index.d.mts +9 -6
  9. package/dist/cloudflare/index.d.mts.map +1 -1
  10. package/dist/cloudflare/index.mjs +19 -9
  11. package/dist/cloudflare/index.mjs.map +1 -1
  12. package/dist/{describe-CivKHl4x.d.mts → describe-BOgc0xbR.d.mts} +2 -6
  13. package/dist/describe-BOgc0xbR.d.mts.map +1 -0
  14. package/dist/{describe-h9F5stgR.mjs → describe-C6sWA_8p.mjs} +6 -9
  15. package/dist/{describe-h9F5stgR.mjs.map → describe-C6sWA_8p.mjs.map} +1 -1
  16. package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
  17. package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
  18. package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
  19. package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
  20. package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
  21. package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
  22. package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
  23. package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
  24. package/dist/icons/index.d.mts +1 -3
  25. package/dist/icons/index.d.mts.map +1 -1
  26. package/dist/icons/index.mjs +2 -3
  27. package/dist/index.d.mts +6 -9
  28. package/dist/index.d.mts.map +1 -1
  29. package/dist/index.mjs +9 -13
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
  32. package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
  33. package/dist/{provider-g0Vlvlrb.d.mts → provider-CB0nqu0m.d.mts} +4 -5
  34. package/dist/{provider-g0Vlvlrb.d.mts.map → provider-CB0nqu0m.d.mts.map} +1 -1
  35. package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  36. package/dist/server/index.d.mts +8 -19
  37. package/dist/server/index.d.mts.map +1 -1
  38. package/dist/server/index.mjs +11 -15
  39. package/dist/server/index.mjs.map +1 -1
  40. package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
  41. package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
  42. package/dist/{services-8_h0ubLB.d.mts → services-BZoK2VOY.d.mts} +3 -5
  43. package/dist/services-BZoK2VOY.d.mts.map +1 -0
  44. package/dist/sharp/index.d.mts +2 -4
  45. package/dist/sharp/index.d.mts.map +1 -1
  46. package/dist/sharp/index.mjs +5 -6
  47. package/dist/{stores-BtmSl8X3.mjs → stores-CxraN3kt.mjs} +73 -31
  48. package/dist/stores-CxraN3kt.mjs.map +1 -0
  49. package/dist/unpic/index.d.mts +2 -4
  50. package/dist/unpic/index.d.mts.map +1 -1
  51. package/dist/unpic/index.mjs +2 -3
  52. package/dist/{upload-kp0_oK76.d.mts → upload-lVLMRJoC.d.mts} +47 -18
  53. package/dist/upload-lVLMRJoC.d.mts.map +1 -0
  54. package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
  55. package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
  56. package/dist/vite/index.d.mts +1 -5
  57. package/dist/vite/index.d.mts.map +1 -1
  58. package/dist/vite/index.mjs +5 -7
  59. package/dist/vite/index.mjs.map +1 -1
  60. package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
  61. package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
  62. package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
  63. package/dist/widths-upkgLdek.d.mts.map +1 -0
  64. package/package.json +6 -6
  65. package/dist/asset-Dlkss5qp.d.mts.map +0 -1
  66. package/dist/describe-CivKHl4x.d.mts.map +0 -1
  67. package/dist/services-8_h0ubLB.d.mts.map +0 -1
  68. package/dist/stores-BtmSl8X3.mjs.map +0 -1
  69. package/dist/upload-kp0_oK76.d.mts.map +0 -1
  70. package/dist/widths-Cg7-x89y.d.mts.map +0 -1
package/README.md CHANGED
@@ -416,26 +416,26 @@ An original that no CDN or build holds, such as an editor's upload, enters
416
416
  through `POST /_media/upload`: the bytes are the body, with an `image/*`
417
417
  `Content-Type`. The route reads at most `maxBytes` (20 MB by default) as the
418
418
  body streams, reads its facts through the `Inspector`, keeps the bytes under
419
- their SHA-256 in `Uploads` (where `Originals` reads them), and answers the
420
- facts as a `HashedAsset`, keyed by that hash, with a `201`. The variant server
421
- serves it at once. Only the facts go on to the application's data (a CMS's
422
- asset row); the bytes never travel through RPC. The answer is the server's
423
- reading of the bytes, but once it has passed through a client it is the
424
- client's word: a client can change a width or name another original's hash.
425
- Decoding with `HashedAsset` checks the facts' shape, not that they are true,
426
- so store facts your server read, not ones a client sends back.
427
-
428
- Who may upload is the application's to say, and the route has no default:
429
- `UploadPolicy` is asked before a byte is read. `uploadPolicyBearer(secret)` is
430
- the one for a deployment's secret: it admits `Authorization: Bearer <secret>`,
431
- compared by digest so the time taken says nothing of the secret, and admits
432
- nobody while the secret is unset or empty. Who may upload by session is a
433
- policy of your own (`Layer.succeed(UploadPolicy, { admit })`, a `foldkit-guard`
434
- check).
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.
422
+
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.
435
429
 
436
430
  ```ts
437
431
  import { Layer } from 'effect'
438
- import { uploadLayer, uploadPolicyBearer, uploadsKeyValueStore } from 'foldkit-media/server'
432
+ import { GuardMedia } from 'foldkit-guard/media'
433
+ import {
434
+ uploadLayer,
435
+ uploadPolicyAny,
436
+ uploadPolicyBearer,
437
+ uploadsKeyValueStore,
438
+ } from 'foldkit-media/server'
439
439
  import { inspectorSharp } from 'foldkit-media/sharp'
440
440
 
441
441
  const uploads = uploadLayer({ maxBytes: 10 * 1024 * 1024 }).pipe(
@@ -443,25 +443,89 @@ const uploads = uploadLayer({ maxBytes: 10 * 1024 * 1024 }).pipe(
443
443
  Layer.mergeAll(
444
444
  uploadsKeyValueStore(),
445
445
  inspectorSharp(),
446
- uploadPolicyBearer(process.env['UPLOAD_TOKEN']),
446
+ uploadPolicyAny(
447
+ uploadPolicyBearer(process.env['UPLOAD_TOKEN']),
448
+ GuardMedia.uploadPolicy(Policy, { resolve, Upload: [G.isEditor] }),
449
+ ),
447
450
  ),
448
451
  ),
449
452
  )
450
453
  ```
451
454
 
452
- `uploadsKeyValueStore()` keeps them where `originalsKeyValueStore()` reads,
453
- over the same `KeyValueStore`; on Cloudflare, `uploadsR2(bucket)` beside
454
- `originalsR2(bucket)`, and `serveFetch`'s `uploads` hosts the route in a
455
- Worker. A refusal answers its kind and nothing more, and no browser keeps it:
456
- `403` from the policy, `415` for a body that is not `image/*` or not an image
457
- the inspector reads, `413` past `maxBytes` or the inspector's pixel limit, and
458
- `400` for a body that broke off. Because the body must be `image/*`, which is
459
- not a type a browser sends to another origin without a preflight, and the
460
- route answers no preflight, a cookie alone cannot upload from another site.
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.
461
525
 
462
526
  An image a page names only by URL gets its facts from the same route set:
463
527
  `GET /_media/facts?url=` reads it with `factsOf`, behind the same
464
- `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
465
529
  host in `uploadLayer({ facts: { allow } })` is read, and `allow` is empty
466
530
  unless given, so a server names every host it fetches. An editor asks it when
467
531
  a URL is set, and stores the facts beside the URL. Neither route limits how
@@ -1,5 +1,4 @@
1
1
  import { Option, Schema } from "effect";
2
- //#region src/asset.d.ts
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", {
@@ -75,6 +74,5 @@ declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
75
74
  readonly y: Schema.Finite;
76
75
  }>>;
77
76
  }>>;
78
- //#endregion
79
77
  export { isHashed as a, Placeholder as i, HashedAsset as n, ImageAsset as r, Focus as t };
80
- //# sourceMappingURL=asset-Dlkss5qp.d.mts.map
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"}
@@ -1,6 +1,88 @@
1
- import { n as Inspector } from "../describe-CivKHl4x.mjs";
2
- import { Layer } from "effect";
3
- //#region src/browser/index.d.ts
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
- //#endregion
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":";;;;;;;;;;qBA4Ba,mBAAgB;WACP;MACnB,MAAM,MAAM"}
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"}
@@ -1,8 +1,90 @@
1
- import { t as Inspector } from "../describe-h9F5stgR.mjs";
2
- import { t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
3
- import { i as TransformFailed, n as OriginalTooLarge } from "../errors-qETj7Pgi.mjs";
4
- import { Effect, Layer, Option } from "effect";
5
- //#region src/browser/index.ts
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
- //#endregion
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,QAAQ;EACZ,KAAK,IAAI,MAAM,GAAG,MAAM,UAAU,CAAC,OAAO,OAAO,iBAC/C,KAAK,IAAI,OAAO,GAAG,OAAO,SAAS,CAAC,OAAO,QAAQ,iBAAiB;GAClE,MAAM,YAAY,KAAK,IAAI,iBAAiB,QAAQ,IAAI;GACxD,MAAM,aAAa,KAAK,IAAI,iBAAiB,SAAS,GAAG;GACzD,YAAY,QAAQ;GACpB,YAAY,SAAS;GACrB,aAAa,UACX,QACA,MACA,KACA,WACA,YACA,GACA,GACA,WACA,UACF;GACA,MAAM,SAAS,aAAa,aAAa,GAAG,GAAG,WAAW,UAAU,CAAC,CAAC;GACtE,KAAK,IAAI,KAAK,GAAG,KAAK,OAAO,UAAU,CAAC,OAAO,MAAM,GAAG,QAAQ,OAAO,MAAO;EAChF;EAEF,MAAM,QAAQ,KAAK,IAAI,GAAG,iBAAiB,KAAK,IAAI,OAAO,MAAM,CAAC;EAClE,MAAM,QAAQ,WAAmB,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,KAAK,CAAC;EACvE,MAAM,SAAS,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"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/browser/upload.ts","../../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,MAE1B,OAAO,UAAoC,UACzC,OAAO,eACL,OAAO,WAAW;CAChB,MAAM,UAAU,IAAI,eAAe;CACnC,MAAM,QAAQ,WACZ,MAAM,gBACJ,OACA,MAAM,KAAK,IAAI,aAAa;EAAE;EAAQ,QAAQ,QAAQ;CAAO,CAAC,CAAC,CACjE;CACF,QAAQ,OAAO,cAAa,UAAS;EACnC,MAAM,YACJ,OACA,WAAW,KAAK;GACd,QAAQ,MAAM;GACd,OAAO,MAAM,mBAAmB,MAAM,QAAQ,KAAK;EACrD,CAAC,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AAC,CAC5C,EACJ,CAAC;AACH"}
@@ -1,14 +1,18 @@
1
- import { n as Inspector } from "../describe-CivKHl4x.mjs";
2
- import { a as Uploads, p as Admission } from "../upload-kp0_oK76.mjs";
3
- import { a as Transformer, i as Originals, o as Variants } from "../services-8_h0ubLB.mjs";
1
+ import { n as Inspector } from "../describe-BOgc0xbR.mjs";
2
+ import { c as Uploads, t as StoredFacts, v as Admission } from "../upload-lVLMRJoC.mjs";
3
+ import { a as Transformer, i as Originals, o as Variants } from "../services-BZoK2VOY.mjs";
4
4
  import { Layer } from "effect";
5
5
  import { KeyValueStore } from "effect/persistence";
6
6
  import { Cache as Cache$1, ImagesBinding, R2Bucket, RateLimit } from "@cloudflare/workers-types";
7
- //#region src/cloudflare/index.d.ts
8
7
  /** Originals in an R2 bucket, each under its content hash. */
9
8
  export declare const originalsR2: (bucket: R2Bucket) => Layer.Layer<Originals>;
10
- /** Uploads into an R2 bucket, each under its content hash: what `originalsR2` reads. */
9
+ /**
10
+ * Uploads into an R2 bucket, each under its content hash, what `originalsR2`
11
+ * reads, and its facts under `facts/<hash>`, what `storedFactsR2` reads.
12
+ */
11
13
  export declare const uploadsR2: (bucket: R2Bucket) => Layer.Layer<Uploads>;
14
+ /** An upload's facts, read back from the bucket `uploadsR2` keeps them in. */
15
+ export declare const storedFactsR2: (bucket: R2Bucket) => Layer.Layer<StoredFacts>;
12
16
  /**
13
17
  * The Images binding as the transformer. It scales down, never up, and names
14
18
  * the format, so the variant is what its URL says. A spent allowance is
@@ -50,5 +54,4 @@ export declare const admissionRateLimit: (binding: RateLimit, options?: {
50
54
  * is refused.
51
55
  */
52
56
  export declare const inspectorImages: (images: ImagesBinding) => Layer.Layer<Inspector>;
53
- //#endregion
54
57
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["Cache"],"sources":["../../src/cloudflare/index.ts"],"mappings":";;;;;;;;qBAuBa,cAAW,QAAY,aAAW,MAAM,MAAM;;qBAiB9C,YAAS,QAAY,aAAW,MAAM,MAAM;;;;;;qBAgB5C,oBAAiB,QAAY,kBAAgB,MAAM,MAAM;;;;;;qBAsCzD,kBAAe,QAAY,aAAW,MAAM,MAAM,cAAc;;;;;;;qBA2HhE,aAAU,QACb,UAAQ;WACI;WAA0B,QAAQA;MACrD,MAAM,MAAM;;;;;;;qBAiBF,qBAAkB,SACpB,WAAS;WACE;MACnB,MAAM,MAAM;;;;;;;;;;qBA0BF,kBAAe,QAAY,kBAAgB,MAAM,MAAM"}
1
+ {"version":3,"file":"index.d.mts","names":["Cache"],"sources":["../../src/cloudflare/index.ts"],"mappings":";;;;;;;qBAuBa,cAAW,QAAY,aAAW,MAAM,MAAM;;;;;qBAoB9C,YAAS,QAAY,aAAW,MAAM,MAAM;;qBAU5C,gBAAa,QAAY,aAAW,MAAM,MAAM;;;;;;qBAoBhD,oBAAiB,QAAY,kBAAgB,MAAM,MAAM;;;;;;qBAsCzD,kBAAe,QAAY,aAAW,MAAM,MAAM,cAAc;;;;;;;qBA2HhE,aAAU,QACb,UAAQ;WACI;WAA0B,QAAQA;MACrD,MAAM,MAAM;;;;;;;qBAiBF,qBAAkB,SACpB,WAAS;WACE;MACnB,MAAM,MAAM;;;;;;;;;;qBA0BF,kBAAe,QAAY,kBAAgB,MAAM,MAAM"}
@@ -1,17 +1,28 @@
1
- import { t as Inspector } from "../describe-h9F5stgR.mjs";
2
- import { i as TransformFailed, r as QuotaExhausted, t as OriginalNotFound } from "../errors-qETj7Pgi.mjs";
3
- import { h as RateLimited, m as Admission, s as Uploads, t as makeVariants } from "../stores-BtmSl8X3.mjs";
4
- import { n as Transformer, r as Variants, t as Originals } from "../services-BeakQl7F.mjs";
1
+ import { t as Inspector } from "../describe-C6sWA_8p.mjs";
2
+ import { i as TransformFailed, r as QuotaExhausted, t as OriginalNotFound } from "../errors-BhEgXJ4m.mjs";
3
+ import { S as RateLimited, d as encodeFacts, f as factsKey, i as StoredFacts, l as Uploads, t as makeVariants, u as decodeFacts, x as Admission } from "../stores-CxraN3kt.mjs";
4
+ import { n as Transformer, r as Variants, t as Originals } from "../services-7B4hsQM7.mjs";
5
5
  import { Effect, Layer, Option } from "effect";
6
6
  import { KeyValueStore } from "effect/persistence";
7
- //#region src/cloudflare/index.ts
7
+ // src/cloudflare/index.ts
8
8
  /** Originals in an R2 bucket, each under its content hash. */
9
9
  const originalsR2 = (bucket) => Layer.succeed(Originals, { get: (hash) => Effect.promise(() => bucket.get(hash)).pipe(Effect.flatMap((object) => object === null ? Effect.fail(new OriginalNotFound({ hash })) : Effect.succeed({
10
10
  body: object.body,
11
11
  size: object.size
12
12
  }))) });
13
- /** Uploads into an R2 bucket, each under its content hash: what `originalsR2` reads. */
14
- const uploadsR2 = (bucket) => Layer.succeed(Uploads, { put: (hash, bytes) => Effect.promise(() => bucket.put(hash, bytes)).pipe(Effect.asVoid) });
13
+ /**
14
+ * Uploads into an R2 bucket, each under its content hash, what `originalsR2`
15
+ * reads, and its facts under `facts/<hash>`, what `storedFactsR2` reads.
16
+ */
17
+ const uploadsR2 = (bucket) => Layer.succeed(Uploads, { put: (hash, bytes, facts) => Effect.promise(async () => {
18
+ await bucket.put(hash, bytes);
19
+ await bucket.put(factsKey(hash), encodeFacts(facts));
20
+ }) });
21
+ /** An upload's facts, read back from the bucket `uploadsR2` keeps them in. */
22
+ const storedFactsR2 = (bucket) => Layer.succeed(StoredFacts, { get: (hash) => Effect.promise(async () => {
23
+ const object = await bucket.get(factsKey(hash));
24
+ return object === null ? Option.none() : Option.some(decodeFacts(await object.text()));
25
+ }) });
15
26
  const QUOTA_EXHAUSTED = 9422;
16
27
  const isImagesError = (cause) => typeof cause === "object" && cause !== null && typeof Reflect.get(cause, "code") === "number";
17
28
  /**
@@ -157,7 +168,6 @@ const inspectorImages = (images) => Layer.succeed(Inspector, { inspect: (bytes)
157
168
  alpha: info.format !== "image/jpeg",
158
169
  thumbnail: Option.none()
159
170
  }) : Effect.fail(info)), Effect.catch((cause) => Effect.logWarning("Media.inspect failed", cause).pipe(Effect.andThen(Effect.fail(new TransformFailed({})))))) });
160
- //#endregion
161
- export { admissionRateLimit, inspectorImages, keyValueStoreR2, originalsR2, transformerImages, uploadsR2, variantsR2 };
171
+ export { admissionRateLimit, inspectorImages, keyValueStoreR2, originalsR2, storedFactsR2, transformerImages, uploadsR2, variantsR2 };
162
172
 
163
173
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["/**\n * The media server's services on Cloudflare: originals in R2, the Images\n * binding as the transformer, and variants kept in R2 behind the Cache API.\n * Each takes the binding it needs, so build them in `serveFetch`'s `layer`\n * from the request's environment.\n */\nimport type {\n Cache,\n CacheStorage,\n ImagesBinding,\n R2Bucket,\n RateLimit,\n} from '@cloudflare/workers-types'\nimport { Effect, Layer, Option } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Admission, RateLimited } from '../server/admission.js'\nimport { Inspector } from '../describe.js'\nimport { OriginalNotFound, QuotaExhausted, TransformFailed } from '../server/errors.js'\nimport { Originals, Transformer, Variants, type Encoded, type Kept } from '../server/services.js'\nimport { Uploads } from '../server/upload.js'\nimport { makeVariants } from '../server/stores.js'\n\n/** Originals in an R2 bucket, each under its content hash. */\nexport const originalsR2 = (bucket: R2Bucket): Layer.Layer<Originals> =>\n Layer.succeed(Originals, {\n get: hash =>\n Effect.promise(() => bucket.get(hash)).pipe(\n Effect.flatMap(object =>\n object === null\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n // The two runtimes' stream types differ only in their declarations.\n body: object.body as unknown as ReadableStream<Uint8Array>,\n size: object.size,\n }),\n ),\n ),\n })\n\n/** Uploads into an R2 bucket, each under its content hash: what `originalsR2` reads. */\nexport const uploadsR2 = (bucket: R2Bucket): Layer.Layer<Uploads> =>\n Layer.succeed(Uploads, {\n put: (hash, bytes) => Effect.promise(() => bucket.put(hash, bytes)).pipe(Effect.asVoid),\n })\n\n// Cloudflare's code for a spent transformation allowance.\nconst QUOTA_EXHAUSTED = 9422\n\nconst isImagesError = (cause: unknown): cause is { readonly code: number } =>\n typeof cause === 'object' && cause !== null && typeof Reflect.get(cause, 'code') === 'number'\n\n/**\n * The Images binding as the transformer. It scales down, never up, and names\n * the format, so the variant is what its URL says. A spent allowance is\n * `QuotaExhausted`; any other refusal is `TransformFailed`, its reason logged.\n */\nexport const transformerImages = (images: ImagesBinding): Layer.Layer<Transformer> =>\n Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.tryPromise({\n try: async () => {\n const result = await images\n .input(original.body as unknown as Parameters<ImagesBinding['input']>[0])\n .transform({ width: variant.width, fit: 'scale-down' })\n .output({\n format: `image/${variant.format}`,\n ...Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n })\n const response = result.response()\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: result.contentType(),\n }\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch((cause): Effect.Effect<never, QuotaExhausted | TransformFailed> =>\n isImagesError(cause) && cause.code === QUOTA_EXHAUSTED\n ? Effect.fail(new QuotaExhausted({}))\n : Effect.logWarning('Media.transform failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n\n/**\n * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by\n * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the\n * application's own. `clear` and `size` list the whole bucket.\n */\nexport const keyValueStoreR2 = (bucket: R2Bucket): Layer.Layer<KeyValueStore.KeyValueStore> =>\n Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket))\n\nconst r2Store = (bucket: R2Bucket): KeyValueStore.KeyValueStore => {\n const attempt = <A>(method: string, key: string | undefined, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: cause =>\n new KeyValueStore.KeyValueStoreError({\n message: `R2 ${method} failed`,\n method,\n ...(key === undefined ? {} : { key }),\n cause,\n }),\n })\n // Every key in the bucket, a page of listing at a time.\n const keys = async () => {\n const found: Array<string> = []\n let cursor: string | undefined\n do {\n const page = await bucket.list(cursor === undefined ? {} : { cursor })\n found.push(...page.objects.map(object => object.key))\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor !== undefined)\n return found\n }\n return KeyValueStore.make({\n get: key => attempt('get', key, async () => (await bucket.get(key))?.text()),\n getUint8Array: key =>\n attempt('getUint8Array', key, async () => {\n const object = await bucket.get(key)\n return object === null ? undefined : new Uint8Array(await object.arrayBuffer())\n }),\n set: (key, value) => attempt('set', key, async () => void (await bucket.put(key, value))),\n remove: key => attempt('remove', key, () => bucket.delete(key)),\n clear: attempt('clear', undefined, async () => {\n const all = await keys()\n // R2 deletes at most 1,000 keys a call.\n for (let at = 0; at < all.length; at += 1000) await bucket.delete(all.slice(at, at + 1000))\n }),\n size: attempt('size', undefined, async () => (await keys()).length),\n })\n}\n\n// The Cache API keys by request; this origin is never fetched.\nconst edgeKey = (key: string) => `https://foldkit-media.invalid/${key}`\n\n/**\n * Variants with the edge's Cache API in front: read there first, and filled\n * from what is kept behind it, so a popular variant is served from the edge.\n */\nconst withEdge = (behind: Variants['Service'], edge: Cache): Variants['Service'] => {\n const fill = (key: string, encoded: Encoded) =>\n Effect.tryPromise({\n try: () =>\n edge.put(\n edgeKey(key),\n // The page's Response and workers-types' differ only in their declarations.\n new Response(encoded.bytes, {\n headers: {\n 'content-type': encoded.contentType,\n 'cache-control': 'public, max-age=31536000, immutable',\n },\n }) as never,\n ),\n catch: cause => cause,\n }).pipe(Effect.catch(cause => Effect.logWarning('Media: the edge cache failed a write', cause)))\n const behindEdge = (key: string) =>\n behind.get(key).pipe(\n Effect.tap(found =>\n Option.match(found, {\n onNone: () => Effect.void,\n onSome: kept => fill(key, kept.encoded),\n }),\n ),\n )\n return {\n get: key =>\n Effect.tryPromise({\n try: async () => {\n const hit = await edge.match(edgeKey(key))\n return hit === undefined\n ? Option.none<Kept>()\n : Option.some({\n encoded: {\n bytes: new Uint8Array(await hit.arrayBuffer()),\n contentType: hit.headers.get('content-type') ?? 'application/octet-stream',\n },\n from: 'edge' as const,\n })\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Effect.logWarning('Media: the edge cache failed a read', cause).pipe(\n Effect.as(Option.none<Kept>()),\n ),\n ),\n Effect.flatMap(found => (Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),\n ),\n put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded))),\n }\n}\n\n// A Worker's global, which the DOM's `CacheStorage` declares without `default`.\ndeclare const caches: CacheStorage | undefined\n\nconst cacheOf = (cache: Cache | true): Cache => {\n if (cache !== true) return cache\n if (typeof caches === 'undefined') {\n throw new Error(\n 'variantsR2: `cache: true` reads the Worker global `caches.default`, which this runtime lacks',\n )\n }\n return caches.default\n}\n\n/**\n * Variants kept in R2 under `prefix`, so one made last month is not made, and\n * billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,\n * the Cache API stands in front of it: `true` for the Worker's\n * `caches.default`, or a cache of your own (`await caches.open(…)`).\n */\nexport const variantsR2 = (\n bucket: R2Bucket,\n options: { readonly prefix?: string; readonly cache?: Cache | true } = {},\n): Layer.Layer<Variants> => {\n const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? 'variants/'))\n return Layer.succeed(\n Variants,\n Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => kept,\n onSome: cache => withEdge(kept, cacheOf(cache)),\n }),\n )\n}\n\n/**\n * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose\n * limit and period are its configuration. It answers yes or no, not when, so\n * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60\n * by default). A binding that fails admits the request, logged.\n */\nexport const admissionRateLimit = (\n binding: RateLimit,\n options: { readonly retryAfterSeconds?: number } = {},\n): Layer.Layer<Admission> =>\n Layer.succeed(Admission, {\n admit: client =>\n Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(\n Effect.catch(error =>\n Effect.logWarning('Media: the rate limit binding failed; admitting', error).pipe(\n Effect.as({ success: true }),\n ),\n ),\n Effect.flatMap(({ success }) =>\n success\n ? Effect.void\n : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })),\n ),\n ),\n })\n\n/**\n * The `Inspector` through the Images binding: an original's size from `info`,\n * which costs no transformation. It makes no thumbnail, since raw pixels are\n * not offered offline and could not be tested, so an original described here\n * has no ThumbHash; and as `info` does not say whether pixels are\n * transparent, every format but JPEG is taken to be, which costs a\n * placeholder, never shows a wrong one. An SVG, which has no size in pixels,\n * is refused.\n */\nexport const inspectorImages = (images: ImagesBinding): Layer.Layer<Inspector> =>\n Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.tryPromise({\n try: () =>\n images.info(\n new Blob([bytes]).stream() as unknown as Parameters<ImagesBinding['info']>[0],\n ),\n catch: cause => cause,\n }).pipe(\n Effect.flatMap(info =>\n // An SVG's answer has no width: it has no size in pixels.\n 'width' in info\n ? Effect.succeed({\n width: info.width,\n height: info.height,\n alpha: info.format !== 'image/jpeg',\n thumbnail: Option.none(),\n })\n : Effect.fail(info),\n ),\n Effect.catch(cause =>\n Effect.logWarning('Media.inspect failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n"],"mappings":";;;;;;;;AAuBA,MAAa,eAAe,WAC1B,MAAM,QAAQ,WAAW,EACvB,MAAK,SACH,OAAO,cAAc,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,KACrC,OAAO,SAAQ,WACb,WAAW,OACP,OAAO,KAAK,IAAI,iBAAiB,EAAE,KAAK,CAAC,CAAC,IAC1C,OAAO,QAAQ;CAEb,MAAM,OAAO;CACb,MAAM,OAAO;AACf,CAAC,CACP,CACF,EACJ,CAAC;;AAGH,MAAa,aAAa,WACxB,MAAM,QAAQ,SAAS,EACrB,MAAM,MAAM,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AC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["/**\n * The media server's services on Cloudflare: originals in R2, the Images\n * binding as the transformer, and variants kept in R2 behind the Cache API.\n * Each takes the binding it needs, so build them in `serveFetch`'s `layer`\n * from the request's environment.\n */\nimport type {\n Cache,\n CacheStorage,\n ImagesBinding,\n R2Bucket,\n RateLimit,\n} from '@cloudflare/workers-types'\nimport { Effect, Layer, Option } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Admission, RateLimited } from '../server/admission.js'\nimport { Inspector } from '../describe.js'\nimport { OriginalNotFound, QuotaExhausted, TransformFailed } from '../server/errors.js'\nimport { Originals, Transformer, Variants, type Encoded, type Kept } from '../server/services.js'\nimport { StoredFacts, Uploads, decodeFacts, encodeFacts, factsKey } from '../server/upload.js'\nimport { makeVariants } from '../server/stores.js'\n\n/** Originals in an R2 bucket, each under its content hash. */\nexport const originalsR2 = (bucket: R2Bucket): Layer.Layer<Originals> =>\n Layer.succeed(Originals, {\n get: hash =>\n Effect.promise(() => bucket.get(hash)).pipe(\n Effect.flatMap(object =>\n object === null\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n // The two runtimes' stream types differ only in their declarations.\n body: object.body as unknown as ReadableStream<Uint8Array>,\n size: object.size,\n }),\n ),\n ),\n })\n\n/**\n * Uploads into an R2 bucket, each under its content hash, what `originalsR2`\n * reads, and its facts under `facts/<hash>`, what `storedFactsR2` reads.\n */\nexport const uploadsR2 = (bucket: R2Bucket): Layer.Layer<Uploads> =>\n Layer.succeed(Uploads, {\n put: (hash, bytes, facts) =>\n Effect.promise(async () => {\n await bucket.put(hash, bytes)\n await bucket.put(factsKey(hash), encodeFacts(facts))\n }),\n })\n\n/** An upload's facts, read back from the bucket `uploadsR2` keeps them in. */\nexport const storedFactsR2 = (bucket: R2Bucket): Layer.Layer<StoredFacts> =>\n Layer.succeed(StoredFacts, {\n get: hash =>\n Effect.promise(async () => {\n const object = await bucket.get(factsKey(hash))\n return object === null ? Option.none() : Option.some(decodeFacts(await object.text()))\n }),\n })\n\n// Cloudflare's code for a spent transformation allowance.\nconst QUOTA_EXHAUSTED = 9422\n\nconst isImagesError = (cause: unknown): cause is { readonly code: number } =>\n typeof cause === 'object' && cause !== null && typeof Reflect.get(cause, 'code') === 'number'\n\n/**\n * The Images binding as the transformer. It scales down, never up, and names\n * the format, so the variant is what its URL says. A spent allowance is\n * `QuotaExhausted`; any other refusal is `TransformFailed`, its reason logged.\n */\nexport const transformerImages = (images: ImagesBinding): Layer.Layer<Transformer> =>\n Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.tryPromise({\n try: async () => {\n const result = await images\n .input(original.body as unknown as Parameters<ImagesBinding['input']>[0])\n .transform({ width: variant.width, fit: 'scale-down' })\n .output({\n format: `image/${variant.format}`,\n ...Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n })\n const response = result.response()\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: result.contentType(),\n }\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch((cause): Effect.Effect<never, QuotaExhausted | TransformFailed> =>\n isImagesError(cause) && cause.code === QUOTA_EXHAUSTED\n ? Effect.fail(new QuotaExhausted({}))\n : Effect.logWarning('Media.transform failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n\n/**\n * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by\n * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the\n * application's own. `clear` and `size` list the whole bucket.\n */\nexport const keyValueStoreR2 = (bucket: R2Bucket): Layer.Layer<KeyValueStore.KeyValueStore> =>\n Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket))\n\nconst r2Store = (bucket: R2Bucket): KeyValueStore.KeyValueStore => {\n const attempt = <A>(method: string, key: string | undefined, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: cause =>\n new KeyValueStore.KeyValueStoreError({\n message: `R2 ${method} failed`,\n method,\n ...(key === undefined ? {} : { key }),\n cause,\n }),\n })\n // Every key in the bucket, a page of listing at a time.\n const keys = async () => {\n const found: Array<string> = []\n let cursor: string | undefined\n do {\n const page = await bucket.list(cursor === undefined ? {} : { cursor })\n found.push(...page.objects.map(object => object.key))\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor !== undefined)\n return found\n }\n return KeyValueStore.make({\n get: key => attempt('get', key, async () => (await bucket.get(key))?.text()),\n getUint8Array: key =>\n attempt('getUint8Array', key, async () => {\n const object = await bucket.get(key)\n return object === null ? undefined : new Uint8Array(await object.arrayBuffer())\n }),\n set: (key, value) => attempt('set', key, async () => void (await bucket.put(key, value))),\n remove: key => attempt('remove', key, () => bucket.delete(key)),\n clear: attempt('clear', undefined, async () => {\n const all = await keys()\n // R2 deletes at most 1,000 keys a call.\n for (let at = 0; at < all.length; at += 1000) await bucket.delete(all.slice(at, at + 1000))\n }),\n size: attempt('size', undefined, async () => (await keys()).length),\n })\n}\n\n// The Cache API keys by request; this origin is never fetched.\nconst edgeKey = (key: string) => `https://foldkit-media.invalid/${key}`\n\n/**\n * Variants with the edge's Cache API in front: read there first, and filled\n * from what is kept behind it, so a popular variant is served from the edge.\n */\nconst withEdge = (behind: Variants['Service'], edge: Cache): Variants['Service'] => {\n const fill = (key: string, encoded: Encoded) =>\n Effect.tryPromise({\n try: () =>\n edge.put(\n edgeKey(key),\n // The page's Response and workers-types' differ only in their declarations.\n new Response(encoded.bytes, {\n headers: {\n 'content-type': encoded.contentType,\n 'cache-control': 'public, max-age=31536000, immutable',\n },\n }) as never,\n ),\n catch: cause => cause,\n }).pipe(Effect.catch(cause => Effect.logWarning('Media: the edge cache failed a write', cause)))\n const behindEdge = (key: string) =>\n behind.get(key).pipe(\n Effect.tap(found =>\n Option.match(found, {\n onNone: () => Effect.void,\n onSome: kept => fill(key, kept.encoded),\n }),\n ),\n )\n return {\n get: key =>\n Effect.tryPromise({\n try: async () => {\n const hit = await edge.match(edgeKey(key))\n return hit === undefined\n ? Option.none<Kept>()\n : Option.some({\n encoded: {\n bytes: new Uint8Array(await hit.arrayBuffer()),\n contentType: hit.headers.get('content-type') ?? 'application/octet-stream',\n },\n from: 'edge' as const,\n })\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Effect.logWarning('Media: the edge cache failed a read', cause).pipe(\n Effect.as(Option.none<Kept>()),\n ),\n ),\n Effect.flatMap(found => (Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),\n ),\n put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded))),\n }\n}\n\n// A Worker's global, which the DOM's `CacheStorage` declares without `default`.\ndeclare const caches: CacheStorage | undefined\n\nconst cacheOf = (cache: Cache | true): Cache => {\n if (cache !== true) return cache\n if (typeof caches === 'undefined') {\n throw new Error(\n 'variantsR2: `cache: true` reads the Worker global `caches.default`, which this runtime lacks',\n )\n }\n return caches.default\n}\n\n/**\n * Variants kept in R2 under `prefix`, so one made last month is not made, and\n * billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,\n * the Cache API stands in front of it: `true` for the Worker's\n * `caches.default`, or a cache of your own (`await caches.open(…)`).\n */\nexport const variantsR2 = (\n bucket: R2Bucket,\n options: { readonly prefix?: string; readonly cache?: Cache | true } = {},\n): Layer.Layer<Variants> => {\n const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? 'variants/'))\n return Layer.succeed(\n Variants,\n Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => kept,\n onSome: cache => withEdge(kept, cacheOf(cache)),\n }),\n )\n}\n\n/**\n * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose\n * limit and period are its configuration. It answers yes or no, not when, so\n * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60\n * by default). A binding that fails admits the request, logged.\n */\nexport const admissionRateLimit = (\n binding: RateLimit,\n options: { readonly retryAfterSeconds?: number } = {},\n): Layer.Layer<Admission> =>\n Layer.succeed(Admission, {\n admit: client =>\n Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(\n Effect.catch(error =>\n Effect.logWarning('Media: the rate limit binding failed; admitting', error).pipe(\n Effect.as({ success: true }),\n ),\n ),\n Effect.flatMap(({ success }) =>\n success\n ? Effect.void\n : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })),\n ),\n ),\n })\n\n/**\n * The `Inspector` through the Images binding: an original's size from `info`,\n * which costs no transformation. It makes no thumbnail, since raw pixels are\n * not offered offline and could not be tested, so an original described here\n * has no ThumbHash; and as `info` does not say whether pixels are\n * transparent, every format but JPEG is taken to be, which costs a\n * placeholder, never shows a wrong one. An SVG, which has no size in pixels,\n * is refused.\n */\nexport const inspectorImages = (images: ImagesBinding): Layer.Layer<Inspector> =>\n Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.tryPromise({\n try: () =>\n images.info(\n new Blob([bytes]).stream() as unknown as Parameters<ImagesBinding['info']>[0],\n ),\n catch: cause => cause,\n }).pipe(\n Effect.flatMap(info =>\n // An SVG's answer has no width: it has no size in pixels.\n 'width' in info\n ? Effect.succeed({\n width: info.width,\n height: info.height,\n alpha: info.format !== 'image/jpeg',\n thumbnail: Option.none(),\n })\n : Effect.fail(info),\n ),\n Effect.catch(cause =>\n Effect.logWarning('Media.inspect failed', cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n"],"mappings":";;;;;;;;AAuBA,MAAa,eAAe,WAC1B,MAAM,QAAQ,WAAW,EACvB,MAAK,SACH,OAAO,cAAc,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,KACrC,OAAO,SAAQ,WACb,WAAW,OACP,OAAO,KAAK,IAAI,iBAAiB,EAAE,KAAK,CAAC,CAAC,IAC1C,OAAO,QAAQ;CAEb,MAAM,OAAO;CACb,MAAM,OAAO;AACf,CAAC,CACP,CACF,EACJ,CAAC;;;;;A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AC3B;CACF,QAAO,UAAS;AAClB,CAAC,CAAC,CAAC,KACD,OAAO,SAAQ,SAEb,WAAW,OACP,OAAO,QAAQ;CACb,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,OAAO,KAAK,WAAW;CACvB,WAAW,OAAO,KAAK;AACzB,CAAC,IACD,OAAO,KAAK,IAAI,CACtB,GACA,OAAO,OAAM,UACX,OAAO,WAAW,wBAAwB,KAAK,CAAC,CAAC,KAC/C,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD,CACF,CACF,EACJ,CAAC"}
@@ -1,6 +1,5 @@
1
- import { r as ImageAsset } from "./asset-Dlkss5qp.mjs";
1
+ import { r as ImageAsset } from "./asset-BLo8VWmd.mjs";
2
2
  import { Context, Effect, Option, Schema } from "effect";
3
- //#region src/server/errors.d.ts
4
3
  declare const OriginalNotFound_base: Schema.Class<OriginalNotFound, Schema.TaggedStruct<"OriginalNotFound", {
5
4
  readonly hash: Schema.String;
6
5
  }>, import("effect/Cause").YieldableError>;
@@ -22,8 +21,6 @@ declare class TransformFailed extends TransformFailed_base {}
22
21
  declare const QuotaExhausted_base: Schema.Class<QuotaExhausted, Schema.TaggedStruct<"QuotaExhausted", {}>, import("effect/Cause").YieldableError>;
23
22
  /** The host's transformation allowance is spent; variants already made still serve. */
24
23
  declare class QuotaExhausted extends QuotaExhausted_base {}
25
- //#endregion
26
- //#region src/describe.d.ts
27
24
  /** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */
28
25
  interface Thumbnail {
29
26
  readonly width: number;
@@ -51,6 +48,5 @@ declare class Inspector extends Inspector_base {}
51
48
  * page's content naming a URL), so its facts are derived once and stored.
52
49
  */
53
50
  declare const describe: (key: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector>;
54
- //#endregion
55
51
  export { OriginalNotFound as a, TransformFailed as c, describe as i, Inspector as n, OriginalTooLarge as o, Thumbnail as r, QuotaExhausted as s, Inspected as t };
56
- //# sourceMappingURL=describe-CivKHl4x.d.mts.map
52
+ //# sourceMappingURL=describe-BOgc0xbR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"describe-BOgc0xbR.d.mts","names":[],"sources":["../src/server/errors.ts","../src/describe.ts"],"mappings":";;;;;;cAGa,yBAAyB;;;;;;;cAOzB,yBAAyB;;;;;;cAUzB,wBAAwB;;;cAOxB,uBAAuB;;UCrBnB;WACN;WACA;WACA,MAAM;;;UAIA;WACN;WACA;;WAEA;;WAEA,WAAW,OAAO,OAAO;;;WAOd,UAChB,OAAO,WAAW,iBACf,OAAO,OAAO,WAAW,kBAAkB;;;cALvC,kBAAkB;;;;;;;cAoBlB,WAAQ,aACR,OACJ,WAAW,iBACjB,OAAO,OAAO,YAAY,kBAAkB,kBAAkB"}