foldkit-media 0.3.1 → 0.4.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 (175) hide show
  1. package/README.md +65 -4
  2. package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
  3. package/dist/asset.d.ts.map +1 -0
  4. package/dist/asset.js +66 -0
  5. package/dist/asset.js.map +1 -0
  6. package/dist/browser/index.d.ts +15 -0
  7. package/dist/browser/index.d.ts.map +1 -0
  8. package/dist/browser/index.js +69 -0
  9. package/dist/browser/index.js.map +1 -0
  10. package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
  11. package/dist/browser/upload.d.ts.map +1 -0
  12. package/dist/browser/upload.js +87 -0
  13. package/dist/browser/upload.js.map +1 -0
  14. package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
  15. package/dist/cloudflare/index.d.ts.map +1 -0
  16. package/dist/cloudflare/{index.mjs → index.js} +35 -15
  17. package/dist/cloudflare/index.js.map +1 -0
  18. package/dist/describe.d.ts +32 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +30 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/format.d.ts +12 -0
  23. package/dist/format.d.ts.map +1 -0
  24. package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
  25. package/dist/format.js.map +1 -0
  26. package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
  27. package/dist/icon.d.ts.map +1 -0
  28. package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
  29. package/dist/icon.js.map +1 -0
  30. package/dist/icons/{index.d.mts → index.d.ts} +2 -2
  31. package/dist/icons/index.d.ts.map +1 -0
  32. package/dist/icons/{index.mjs → index.js} +2 -2
  33. package/dist/icons/index.js.map +1 -0
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +10 -0
  36. package/dist/layout.d.ts +60 -0
  37. package/dist/layout.d.ts.map +1 -0
  38. package/dist/layout.js +72 -0
  39. package/dist/layout.js.map +1 -0
  40. package/dist/limits.d.ts +3 -0
  41. package/dist/limits.d.ts.map +1 -0
  42. package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
  43. package/dist/limits.js.map +1 -0
  44. package/dist/picture.d.ts +88 -0
  45. package/dist/picture.d.ts.map +1 -0
  46. package/dist/picture.js +113 -0
  47. package/dist/picture.js.map +1 -0
  48. package/dist/placeholder.d.ts +16 -0
  49. package/dist/placeholder.d.ts.map +1 -0
  50. package/dist/placeholder.js +38 -0
  51. package/dist/placeholder.js.map +1 -0
  52. package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
  53. package/dist/provider.d.ts.map +1 -0
  54. package/dist/provider.js +93 -0
  55. package/dist/provider.js.map +1 -0
  56. package/dist/server/admission.d.ts +31 -0
  57. package/dist/server/admission.d.ts.map +1 -0
  58. package/dist/server/admission.js +41 -0
  59. package/dist/server/admission.js.map +1 -0
  60. package/dist/server/api.d.ts +14 -0
  61. package/dist/server/api.d.ts.map +1 -0
  62. package/dist/server/api.js +21 -0
  63. package/dist/server/api.js.map +1 -0
  64. package/dist/server/diagnostics.d.ts +53 -0
  65. package/dist/server/diagnostics.d.ts.map +1 -0
  66. package/dist/server/diagnostics.js +50 -0
  67. package/dist/server/diagnostics.js.map +1 -0
  68. package/dist/server/errors.d.ts +24 -0
  69. package/dist/server/errors.d.ts.map +1 -0
  70. package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
  71. package/dist/server/errors.js.map +1 -0
  72. package/dist/server/facts.d.ts +36 -0
  73. package/dist/server/facts.d.ts.map +1 -0
  74. package/dist/server/facts.js +126 -0
  75. package/dist/server/facts.js.map +1 -0
  76. package/dist/server/fetch.d.ts +29 -0
  77. package/dist/server/fetch.d.ts.map +1 -0
  78. package/dist/server/fetch.js +32 -0
  79. package/dist/server/fetch.js.map +1 -0
  80. package/dist/server/handlers.d.ts +48 -0
  81. package/dist/server/handlers.d.ts.map +1 -0
  82. package/dist/server/handlers.js +151 -0
  83. package/dist/server/handlers.js.map +1 -0
  84. package/dist/server/headers.d.ts +47 -0
  85. package/dist/server/headers.d.ts.map +1 -0
  86. package/dist/server/headers.js +134 -0
  87. package/dist/server/headers.js.map +1 -0
  88. package/dist/server/index.d.ts +13 -0
  89. package/dist/server/index.js +12 -0
  90. package/dist/server/materialize.d.ts +36 -0
  91. package/dist/server/materialize.d.ts.map +1 -0
  92. package/dist/server/materialize.js +62 -0
  93. package/dist/server/materialize.js.map +1 -0
  94. package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
  95. package/dist/server/services.d.ts.map +1 -0
  96. package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
  97. package/dist/server/services.js.map +1 -0
  98. package/dist/server/stores.d.ts +27 -0
  99. package/dist/server/stores.d.ts.map +1 -0
  100. package/dist/server/stores.js +62 -0
  101. package/dist/server/stores.js.map +1 -0
  102. package/dist/server/upload.d.ts +113 -0
  103. package/dist/server/upload.d.ts.map +1 -0
  104. package/dist/server/upload.js +185 -0
  105. package/dist/server/upload.js.map +1 -0
  106. package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
  107. package/dist/sharp/index.d.ts.map +1 -0
  108. package/dist/sharp/{index.mjs → index.js} +11 -9
  109. package/dist/sharp/index.js.map +1 -0
  110. package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
  111. package/dist/unpic/index.d.ts.map +1 -0
  112. package/dist/unpic/{index.mjs → index.js} +3 -3
  113. package/dist/unpic/index.js.map +1 -0
  114. package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
  115. package/dist/variant.d.ts.map +1 -0
  116. package/dist/variant.js +75 -0
  117. package/dist/variant.js.map +1 -0
  118. package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
  119. package/dist/vite/icons.d.ts.map +1 -0
  120. package/dist/vite/{index.mjs → icons.js} +7 -168
  121. package/dist/vite/icons.js.map +1 -0
  122. package/dist/vite/images.d.ts +20 -0
  123. package/dist/vite/images.d.ts.map +1 -0
  124. package/dist/vite/images.js +167 -0
  125. package/dist/vite/images.js.map +1 -0
  126. package/dist/vite/index.d.ts +3 -0
  127. package/dist/vite/index.js +3 -0
  128. package/dist/widths.d.ts +22 -0
  129. package/dist/widths.d.ts.map +1 -0
  130. package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
  131. package/dist/widths.js.map +1 -0
  132. package/package.json +22 -21
  133. package/dist/asset-BLo8VWmd.d.mts.map +0 -1
  134. package/dist/browser/index.d.mts.map +0 -1
  135. package/dist/browser/index.mjs +0 -150
  136. package/dist/browser/index.mjs.map +0 -1
  137. package/dist/cloudflare/index.d.mts.map +0 -1
  138. package/dist/cloudflare/index.mjs.map +0 -1
  139. package/dist/describe-BOgc0xbR.d.mts +0 -52
  140. package/dist/describe-BOgc0xbR.d.mts.map +0 -1
  141. package/dist/describe-C6sWA_8p.mjs +0 -171
  142. package/dist/describe-C6sWA_8p.mjs.map +0 -1
  143. package/dist/errors-BhEgXJ4m.mjs.map +0 -1
  144. package/dist/format-BCRTFU9j.mjs.map +0 -1
  145. package/dist/icon-0A2dBtqj.mjs.map +0 -1
  146. package/dist/icon-BGtxExTN.d.mts.map +0 -1
  147. package/dist/icons/index.d.mts.map +0 -1
  148. package/dist/icons/index.mjs.map +0 -1
  149. package/dist/index.d.mts +0 -157
  150. package/dist/index.d.mts.map +0 -1
  151. package/dist/index.mjs +0 -322
  152. package/dist/index.mjs.map +0 -1
  153. package/dist/limits-B4hHpyfE.mjs.map +0 -1
  154. package/dist/provider-CB0nqu0m.d.mts.map +0 -1
  155. package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
  156. package/dist/server/index.d.mts +0 -170
  157. package/dist/server/index.d.mts.map +0 -1
  158. package/dist/server/index.mjs +0 -231
  159. package/dist/server/index.mjs.map +0 -1
  160. package/dist/services-7B4hsQM7.mjs.map +0 -1
  161. package/dist/services-BZoK2VOY.d.mts.map +0 -1
  162. package/dist/sharp/index.d.mts.map +0 -1
  163. package/dist/sharp/index.mjs.map +0 -1
  164. package/dist/stores-CxraN3kt.mjs +0 -490
  165. package/dist/stores-CxraN3kt.mjs.map +0 -1
  166. package/dist/unpic/index.d.mts.map +0 -1
  167. package/dist/unpic/index.mjs.map +0 -1
  168. package/dist/upload-lVLMRJoC.d.mts +0 -160
  169. package/dist/upload-lVLMRJoC.d.mts.map +0 -1
  170. package/dist/variant-B-vyMmFB.d.mts.map +0 -1
  171. package/dist/vite/index.d.mts.map +0 -1
  172. package/dist/vite/index.mjs.map +0 -1
  173. package/dist/widths-qp3jshiF.mjs.map +0 -1
  174. package/dist/widths-upkgLdek.d.mts +0 -36
  175. package/dist/widths-upkgLdek.d.mts.map +0 -1
package/README.md CHANGED
@@ -350,8 +350,9 @@ const stores = Layer.mergeAll(originalsKeyValueStore(), variantsKeyValueStore())
350
350
  `layerSql` over SQLite or D1, `keyValueStoreR2` (below) over R2.
351
351
  - `variantsKeyValueStore({ prefix })` keeps a variant's bytes under
352
352
  `variants/<hash>/<spelling>`; its media type is the key's extension, so
353
- nothing else is stored. A store that fails a read or a write is logged and
354
- the request is answered by making the variant: variants are a cache.
353
+ nothing else is stored. A store that fails a read or a write is reported
354
+ (`StoreFailed`) and the request is answered by making the variant: variants
355
+ are a cache.
355
356
  - `originalsKeyValueStore({ prefix })` reads an original under its hash. A
356
357
  store that fails is a 500, not a 404: the original is the data.
357
358
 
@@ -368,7 +369,8 @@ served to anyone. It is optional; without it every miss is admitted.
368
369
  rate-limit binding (`[[ratelimits]]`), whose limit and period are its
369
370
  configuration.
370
371
  - A refused client gets a 429 with `Retry-After`. A limiter that fails admits
371
- the request, logged: a limiter that is down should not take the images down.
372
+ the request, reported (`AdmissionFailed`): a limiter that is down should not
373
+ take the images down.
372
374
  - The client is `CF-Connecting-IP`, else the connection's address. Pass
373
375
  `clientOf` to read your own proxy's header; `X-Forwarded-For` is the
374
376
  client's to write, so it is not read by default.
@@ -579,6 +581,25 @@ export const site = {
579
581
  `serveFetch` is the Worker:
580
582
 
581
583
  ```ts
584
+ import type { ImagesBinding, R2Bucket, RateLimit } from '@cloudflare/workers-types'
585
+ import { Layer } from 'effect'
586
+ import {
587
+ admissionRateLimit,
588
+ inspectorImages,
589
+ originalsR2,
590
+ transformerImages,
591
+ uploadsR2,
592
+ variantsR2,
593
+ } from 'foldkit-media/cloudflare'
594
+ import { serveFetch, uploadPolicyBearer } from 'foldkit-media/server'
595
+
596
+ interface WorkerEnv {
597
+ readonly MEDIA: R2Bucket
598
+ readonly IMAGES: ImagesBinding
599
+ readonly LIMITER: RateLimit
600
+ readonly UPLOAD_TOKEN: string
601
+ }
602
+
582
603
  export default {
583
604
  fetch: serveFetch<WorkerEnv>({
584
605
  images: {
@@ -606,7 +627,7 @@ export default {
606
627
 
607
628
  - `transformerImages(images)` is the Images binding: it scales down, never up,
608
629
  and names the format. Cloudflare's code for a spent allowance (9422) is the
609
- 503; any other refusal is the 502, its reason logged.
630
+ 503; any other refusal is the 502, its reason reported (`ImageFailed`).
610
631
  - `keyValueStoreR2(bucket)` is an R2 bucket as a `KeyValueStore`, for the
611
632
  store adapters above or the application's own (`clear` and `size` list the
612
633
  bucket).
@@ -625,6 +646,46 @@ quality do not count), so the ladder is the cost: eight widths are at most
625
646
  eight transformations an original. `examples/cloudflare` is such a Worker,
626
647
  with Remote and Sync as its `otherwise`.
627
648
 
649
+ ### Diagnostics
650
+
651
+ Where the server answers past a failure without telling the caller why, it
652
+ reports a typed diagnostic through `Diagnostics.Reporter` (`foldkit-surface`'s
653
+ channel), which by default is Effect's log, a Worker's `wrangler tail`.
654
+ Reporting changes no answer. Each is exported as a type from
655
+ `foldkit-media/server` (`MediaDiagnostic` is the union):
656
+
657
+ | `_tag` | `level` | When |
658
+ | --- | --- | --- |
659
+ | `StoreFailed` | `error` | A store failed and was worked around: a read taken as a miss, a write dropped. `store` is `variants`, `edge` (the Cache API in front of R2) or `facts` (`factsOf`'s `cache`), with the `operation`, `key` and `cause`. |
660
+ | `AdmissionFailed` | `error` | A rate limiter failed (`limiter`: `RateLimiter` or `binding`), so `client` was admitted with no limit. |
661
+ | `ImageFailed` | `error` for a `transform`, `warning` for an `inspect` | The transformer or inspector failed, answered `TransformFailed` with its `cause` left out. An inspection that fails is most often an upload that is no image. |
662
+ | `FactsUnanswered` | `warning` | The facts route answered `Unavailable`; the diagnostic carries the `url` and the `reason`. |
663
+ | `RequestDefect` | `error` | A defect `serveFetch` answered 500, with its `cause`. Behind `layer`, a defect is the application's router's to log. |
664
+
665
+ Provide another reporter as any service, in the layer the services come from
666
+ (`Diagnostics` is `foldkit-surface`'s):
667
+
668
+ ```ts
669
+ import { Effect, Layer } from 'effect'
670
+ import { Diagnostics } from 'foldkit-surface'
671
+
672
+ serveFetch<WorkerEnv>({
673
+ images: {
674
+ layer: env =>
675
+ Layer.mergeAll(
676
+ originalsR2(env.MEDIA),
677
+ transformerImages(env.IMAGES),
678
+ variantsR2(env.MEDIA, { cache: true }),
679
+ Layer.succeed(Diagnostics.Reporter, diagnostic =>
680
+ Effect.logError(`media: ${diagnostic._tag}: ${diagnostic.message}`),
681
+ ),
682
+ ),
683
+ },
684
+ })
685
+ ```
686
+
687
+ In a test, `Diagnostics.collect()` gives a reporter and the array it fills.
688
+
628
689
  ## Icons
629
690
 
630
691
  An icon is data too: `IconData` holds its `viewBox`, what its root paints
@@ -1,6 +1,6 @@
1
1
  import { Option, Schema } from "effect";
2
2
  /** What stands in an image's place until it loads. */
3
- declare const Placeholder: Schema.TaggedUnion<{
3
+ export declare const Placeholder: Schema.TaggedUnion<{
4
4
  readonly Color: Schema.TaggedStruct<"Color", {
5
5
  readonly value: Schema.String;
6
6
  }>;
@@ -9,13 +9,13 @@ declare const Placeholder: Schema.TaggedUnion<{
9
9
  readonly hash: Schema.String;
10
10
  }>;
11
11
  }>;
12
- type Placeholder = typeof Placeholder.Type;
12
+ export type Placeholder = typeof Placeholder.Type;
13
13
  /** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */
14
- declare const Focus: Schema.Struct<{
14
+ export declare const Focus: Schema.Struct<{
15
15
  readonly x: Schema.Finite;
16
16
  readonly y: Schema.Finite;
17
17
  }>;
18
- type Focus = typeof Focus.Type;
18
+ export type Focus = typeof Focus.Type;
19
19
  /**
20
20
  * The facts of one original image, derived from it once and stored beside it.
21
21
  * `key` is where the original lives, as its provider reads it. `hash` is the
@@ -24,7 +24,7 @@ type Focus = typeof Focus.Type;
24
24
  * rather than one derived, is where a crop keeps the subject; a stored asset
25
25
  * without it reads as none.
26
26
  */
27
- declare const ImageAsset: Schema.Struct<{
27
+ export declare const ImageAsset: Schema.Struct<{
28
28
  readonly key: Schema.String;
29
29
  readonly width: Schema.Int;
30
30
  readonly height: Schema.Int;
@@ -44,17 +44,17 @@ declare const ImageAsset: Schema.Struct<{
44
44
  readonly y: Schema.Finite;
45
45
  }>>;
46
46
  }>;
47
- type ImageAsset = typeof ImageAsset.Type;
47
+ export type ImageAsset = typeof ImageAsset.Type;
48
48
  /**
49
49
  * Facts that name the original by its content hash: what a build or an upload
50
50
  * answers, and what `Provider.hosted` needs to write a URL.
51
51
  */
52
- type HashedAsset = ImageAsset & {
52
+ export type HashedAsset = ImageAsset & {
53
53
  readonly hash: Option.Some<string>;
54
54
  };
55
- declare const isHashed: (asset: ImageAsset) => asset is HashedAsset;
55
+ export declare const isHashed: (asset: ImageAsset) => asset is HashedAsset;
56
56
  /** `ImageAsset`, refusing facts with no content hash. */
57
- declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
57
+ export declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
58
58
  readonly key: Schema.String;
59
59
  readonly width: Schema.Int;
60
60
  readonly height: Schema.Int;
@@ -74,5 +74,4 @@ declare const HashedAsset: Schema.refine<HashedAsset, Schema.Struct<{
74
74
  readonly y: Schema.Finite;
75
75
  }>>;
76
76
  }>>;
77
- export { isHashed as a, Placeholder as i, HashedAsset as n, ImageAsset as r, Focus as t };
78
- //# sourceMappingURL=asset-BLo8VWmd.d.mts.map
77
+ //# sourceMappingURL=asset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asset.d.ts","names":[],"sources":["../src/asset.ts"],"mappings":";;qBAuCa,aAAW,OAAA;;;;;;;;;YAYZ,qBAAqB,YAAY;;qBAOhC,OAAK,OAAA;;;;YACN,eAAe,MAAM;;;;;;;;;qBAUpB,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;YASX,oBAAoB,WAAW;;;;;YAM/B,cAAc;WAAwB,MAAM,OAAO;;qBAElD,WAAQ,OAAW,eAAa,SAAS;;qBAGzC,aAAW,OAAA,OAAA,aAAA,OAAA"}
package/dist/asset.js ADDED
@@ -0,0 +1,66 @@
1
+ import { Option, Schema } from "effect";
2
+ import { ContentHash } from "./variant.js";
3
+ // src/asset.ts
4
+ const CSS_COLOR = /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z%.,\s/+-]*\))$/i;
5
+ const coefficientCount = (x, y) => {
6
+ let count = 0;
7
+ for (let cy = 0; cy < y; cy++) for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++;
8
+ return count;
9
+ };
10
+ const isThumbHash = (encoded) => {
11
+ try {
12
+ const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
13
+ if (bytes.length < 5) return false;
14
+ const hasAlpha = (bytes[2] & 128) !== 0;
15
+ const landscape = (bytes[4] & 128) !== 0;
16
+ const shorter = bytes[3] & 7;
17
+ if (shorter === 0) return false;
18
+ const long = hasAlpha ? 5 : 7;
19
+ const coefficients = coefficientCount(landscape ? long : shorter, landscape ? shorter : long) + coefficientCount(3, 3) * 2 + (hasAlpha ? coefficientCount(5, 5) : 0);
20
+ return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2);
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
25
+ /** What stands in an image's place until it loads. */
26
+ const Placeholder = Schema.TaggedUnion({
27
+ /** A flat color, such as one taken from a logo. */
28
+ Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },
29
+ /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */
30
+ ThumbHash: { hash: Schema.String.check(Schema.makeFilter((encoded) => isThumbHash(encoded) || "not a valid ThumbHash")) },
31
+ /** The provider's smallest width of the image itself, scaled up. */
32
+ LowRes: {}
33
+ });
34
+ const Pixels = Schema.Int.check(Schema.isGreaterThan(0));
35
+ const Share = Schema.Finite.check(Schema.isBetween({
36
+ minimum: 0,
37
+ maximum: 1
38
+ }));
39
+ /** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */
40
+ const Focus = Schema.Struct({
41
+ x: Share,
42
+ y: Share
43
+ });
44
+ /**
45
+ * The facts of one original image, derived from it once and stored beside it.
46
+ * `key` is where the original lives, as its provider reads it. `hash` is the
47
+ * original's content hash, absent for an image never read; `alpha` says
48
+ * whether it has transparent pixels. `focus`, the one fact an editor sets
49
+ * rather than one derived, is where a crop keeps the subject; a stored asset
50
+ * without it reads as none.
51
+ */
52
+ const ImageAsset = Schema.Struct({
53
+ key: Schema.String.check(Schema.isNonEmpty()),
54
+ width: Pixels,
55
+ height: Pixels,
56
+ alpha: Schema.Boolean,
57
+ hash: Schema.OptionFromNullOr(ContentHash),
58
+ placeholder: Schema.OptionFromNullOr(Placeholder),
59
+ focus: Schema.OptionFromOptionalNullOr(Focus)
60
+ });
61
+ const isHashed = (asset) => Option.isSome(asset.hash);
62
+ /** `ImageAsset`, refusing facts with no content hash. */
63
+ const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed));
64
+ export { Focus, HashedAsset, ImageAsset, Placeholder, isHashed };
65
+
66
+ //# sourceMappingURL=asset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asset.js","names":[],"sources":["../src/asset.ts"],"sourcesContent":["import { Option, Schema } from 'effect'\nimport { ContentHash } from './variant.js'\n\n// A placeholder's color lands in a style the page writes, so it is a color\n// and nothing else: no `;`, no `url(`, no second declaration.\nconst CSS_COLOR =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\([0-9a-z%.,\\s/+-]*\\))$/i\n\nconst coefficientCount = (x: number, y: number): number => {\n let count = 0\n for (let cy = 0; cy < y; cy++)\n for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++\n return count\n}\n\n// A ThumbHash's header decides exactly how many coefficient bytes follow it.\n// Checking that layout here keeps malformed stored data out of the renderer.\nconst isThumbHash = (encoded: string): boolean => {\n try {\n const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))\n if (bytes.length < 5) return false\n const hasAlpha = (bytes[2]! & 0x80) !== 0\n const landscape = (bytes[4]! & 0x80) !== 0\n const shorter = bytes[3]! & 7\n if (shorter === 0) return false\n const long = hasAlpha ? 5 : 7\n const lx = landscape ? long : shorter\n const ly = landscape ? shorter : long\n const coefficients =\n coefficientCount(lx, ly) +\n coefficientCount(3, 3) * 2 +\n (hasAlpha ? coefficientCount(5, 5) : 0)\n return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2)\n } catch {\n return false\n }\n}\n\n/** What stands in an image's place until it loads. */\nexport const Placeholder = Schema.TaggedUnion({\n /** A flat color, such as one taken from a logo. */\n Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },\n /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */\n ThumbHash: {\n hash: Schema.String.check(\n Schema.makeFilter(encoded => isThumbHash(encoded) || 'not a valid ThumbHash'),\n ),\n },\n /** The provider's smallest width of the image itself, scaled up. */\n LowRes: {},\n})\nexport type Placeholder = typeof Placeholder.Type\n\nconst Pixels = Schema.Int.check(Schema.isGreaterThan(0))\n\nconst Share = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }))\n\n/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */\nexport const Focus = Schema.Struct({ x: Share, y: Share })\nexport type Focus = typeof Focus.Type\n\n/**\n * The facts of one original image, derived from it once and stored beside it.\n * `key` is where the original lives, as its provider reads it. `hash` is the\n * original's content hash, absent for an image never read; `alpha` says\n * whether it has transparent pixels. `focus`, the one fact an editor sets\n * rather than one derived, is where a crop keeps the subject; a stored asset\n * without it reads as none.\n */\nexport const ImageAsset = Schema.Struct({\n key: Schema.String.check(Schema.isNonEmpty()),\n width: Pixels,\n height: Pixels,\n alpha: Schema.Boolean,\n hash: Schema.OptionFromNullOr(ContentHash),\n placeholder: Schema.OptionFromNullOr(Placeholder),\n focus: Schema.OptionFromOptionalNullOr(Focus),\n})\nexport type ImageAsset = typeof ImageAsset.Type\n\n/**\n * Facts that name the original by its content hash: what a build or an upload\n * answers, and what `Provider.hosted` needs to write a URL.\n */\nexport type HashedAsset = ImageAsset & { readonly hash: Option.Some<string> }\n\nexport const isHashed = (asset: ImageAsset): asset is HashedAsset => Option.isSome(asset.hash)\n\n/** `ImageAsset`, refusing facts with no content hash. */\nexport const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed))\n"],"mappings":";;;AAKA,MAAM,YACJ;AAEF,MAAM,oBAAoB,GAAW,MAAsB;CACzD,IAAI,QAAQ;CACZ,KAAK,IAAI,KAAK,GAAG,KAAK,GAAG,MACvB,KAAK,IAAI,KAAK,OAAO,IAAI,IAAI,GAAG,KAAK,IAAI,KAAK,IAAI,KAAK,MAAM;CAC/D,OAAO;AACT;AAIA,MAAM,eAAe,YAA6B;CAChD,IAAI;EACF,MAAM,QAAQ,WAAW,KAAK,KAAK,OAAO,IAAG,cAAa,UAAU,WAAW,CAAC,CAAC;EACjF,IAAI,MAAM,SAAS,GAAG,OAAO;EAC7B,MAAM,YAAY,MAAM,KAAM,SAAU;EACxC,MAAM,aAAa,MAAM,KAAM,SAAU;EACzC,MAAM,UAAU,MAAM,KAAM;EAC5B,IAAI,YAAY,GAAG,OAAO;EAC1B,MAAM,OAAO,WAAW,IAAI;EAG5B,MAAM,eACJ,iBAHS,YAAY,OAAO,SACnB,YAAY,UAAU,IAER,IACvB,iBAAiB,GAAG,CAAC,IAAI,KACxB,WAAW,iBAAiB,GAAG,CAAC,IAAI;EACvC,OAAO,MAAM,YAAY,WAAW,IAAI,KAAK,KAAK,KAAK,eAAe,CAAC;CACzE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAa,cAAc,OAAO,YAAY;;CAE5C,OAAO,EAAE,OAAO,OAAO,OAAO,MAAM,OAAO,UAAU,SAAS,CAAC,EAAE;;CAEjE,WAAW,EACT,MAAM,OAAO,OAAO,MAClB,OAAO,YAAW,YAAW,YAAY,OAAO,KAAK,uBAAuB,CAC9E,EACF;;CAEA,QAAQ,CAAC;AACX,CAAC;AAGD,MAAM,SAAS,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAEvD,MAAM,QAAQ,OAAO,OAAO,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAE,CAAC,CAAC;;AAG9E,MAAa,QAAQ,OAAO,OAAO;CAAE,GAAG;CAAO,GAAG;AAAM,CAAC;;;;;;;;;AAWzD,MAAa,aAAa,OAAO,OAAO;CACtC,KAAK,OAAO,OAAO,MAAM,OAAO,WAAW,CAAC;CAC5C,OAAO;CACP,QAAQ;CACR,OAAO,OAAO;CACd,MAAM,OAAO,iBAAiB,WAAW;CACzC,aAAa,OAAO,iBAAiB,WAAW;CAChD,OAAO,OAAO,yBAAyB,KAAK;AAC9C,CAAC;AASD,MAAa,YAAY,UAA4C,OAAO,OAAO,MAAM,IAAI;;AAG7F,MAAa,cAAc,WAAW,KAAK,OAAO,OAAO,QAAQ,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { Layer } from "effect";
2
+ import { Inspector } from "../describe.js";
3
+ import { Progressed, UploadEvent, UploadFailed, UploadOptions, UploadRefusal, Uploaded, upload } from "./upload.js";
4
+ /**
5
+ * The `Inspector` in a browser or a web worker: the size from the decoded
6
+ * picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
7
+ * decoded pixel is not opaque. A file the browser cannot decode is
8
+ * `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels
9
+ * released at once.
10
+ */
11
+ export declare const inspectorBrowser: (options?: {
12
+ readonly maxPixels?: number;
13
+ }) => Layer.Layer<Inspector>;
14
+ export { Progressed, UploadEvent, UploadFailed, type UploadOptions, UploadRefusal, Uploaded, upload };
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/browser/index.ts"],"mappings":";;;;;;;;;;qBA4Ba,mBAAgB;WACP;MACnB,MAAM,MAAM"}
@@ -0,0 +1,69 @@
1
+ import { Effect, Layer, Option } from "effect";
2
+ import { Inspector } from "../describe.js";
3
+ import { nonNegativeInteger } from "../limits.js";
4
+ import { OriginalTooLarge, TransformFailed } from "../server/errors.js";
5
+ import { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, upload } from "./upload.js";
6
+ // src/browser/index.ts
7
+ /**
8
+ * An image's facts read in the browser, where it is chosen: `describe(key,
9
+ * bytes)` over `inspectorBrowser()` gives its `ImageAsset`, size, hash and
10
+ * ThumbHash included, before it is uploaded or stored, with no server to ask.
11
+ * The browser's own decoder reads it, so what it cannot show is refused here.
12
+ */
13
+ const THUMBNAIL_SIDE = 100;
14
+ const ALPHA_TILE_SIDE = 512;
15
+ const DEFAULT_MAX_PIXELS = 5e7;
16
+ /**
17
+ * The `Inspector` in a browser or a web worker: the size from the decoded
18
+ * picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
19
+ * decoded pixel is not opaque. A file the browser cannot decode is
20
+ * `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels
21
+ * released at once.
22
+ */
23
+ const inspectorBrowser = (options = {}) => {
24
+ const maxPixels = nonNegativeInteger("maxPixels", options.maxPixels ?? DEFAULT_MAX_PIXELS);
25
+ return Layer.succeed(Inspector, { inspect: (bytes) => Effect.acquireUseRelease(Effect.tryPromise({
26
+ try: () => createImageBitmap(new Blob([bytes])),
27
+ catch: () => new TransformFailed({})
28
+ }), (bitmap) => Effect.gen(function* () {
29
+ const { width, height } = bitmap;
30
+ if (width * height > maxPixels) return yield* new OriginalTooLarge({
31
+ size: width * height,
32
+ limit: maxPixels,
33
+ unit: "pixels"
34
+ });
35
+ const alphaCanvas = new OffscreenCanvas(Math.min(width, ALPHA_TILE_SIDE), Math.min(height, ALPHA_TILE_SIDE));
36
+ const alphaContext = alphaCanvas.getContext("2d");
37
+ if (alphaContext === null) return yield* new TransformFailed({});
38
+ let alpha = false;
39
+ for (let top = 0; top < height && !alpha; top += ALPHA_TILE_SIDE) for (let left = 0; left < width && !alpha; left += ALPHA_TILE_SIDE) {
40
+ const tileWidth = Math.min(ALPHA_TILE_SIDE, width - left);
41
+ const tileHeight = Math.min(ALPHA_TILE_SIDE, height - top);
42
+ alphaCanvas.width = tileWidth;
43
+ alphaCanvas.height = tileHeight;
44
+ alphaContext.drawImage(bitmap, left, top, tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);
45
+ const pixels = alphaContext.getImageData(0, 0, tileWidth, tileHeight).data;
46
+ for (let at = 3; at < pixels.length && !alpha; at += 4) alpha = pixels[at] < 255;
47
+ }
48
+ const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(width, height));
49
+ const side = (length) => Math.max(1, Math.round(length * scale));
50
+ const canvas = new OffscreenCanvas(side(width), side(height));
51
+ const context = canvas.getContext("2d");
52
+ if (context === null) return yield* new TransformFailed({});
53
+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
54
+ const rgba = new Uint8Array(context.getImageData(0, 0, canvas.width, canvas.height).data.buffer);
55
+ return {
56
+ width,
57
+ height,
58
+ alpha,
59
+ thumbnail: Option.some({
60
+ width: canvas.width,
61
+ height: canvas.height,
62
+ rgba
63
+ })
64
+ };
65
+ }), (bitmap) => Effect.sync(() => bitmap.close())) });
66
+ };
67
+ export { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, inspectorBrowser, upload };
68
+
69
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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;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,6 +1,5 @@
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";
1
+ import { Cause, Schema, Stream } from "effect";
2
+ import { HashedAsset } from "../asset.js";
4
3
  /** Why an upload did not end in facts: the route's refusal, or no answer at all. */
5
4
  export declare const UploadRefusal: Schema.Literals<readonly ["Forbidden", "Unauthenticated", "TooLarge", "Unsupported", "Malformed", "Network", "Unexpected"]>;
6
5
  export type UploadRefusal = typeof UploadRefusal.Type;
@@ -64,7 +63,7 @@ export declare const UploadEvent: Schema.Union<readonly [Schema.TaggedStruct<"Pr
64
63
  }>>;
65
64
  }>]>;
66
65
  export type UploadEvent = typeof UploadEvent.Type;
67
- interface UploadOptions {
66
+ export interface UploadOptions {
68
67
  /** Where the route is. Default `/_media/upload`. */
69
68
  readonly url?: string | undefined;
70
69
  /**
@@ -83,15 +82,5 @@ interface UploadOptions {
83
82
  * request.
84
83
  */
85
84
  export declare const upload: (file: Blob, options?: UploadOptions) => Stream.Stream<UploadEvent, UploadFailed>;
86
- /**
87
- * The `Inspector` in a browser or a web worker: the size from the decoded
88
- * picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
89
- * decoded pixel is not opaque. A file the browser cannot decode is
90
- * `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels
91
- * released at once.
92
- */
93
- export declare const inspectorBrowser: (options?: {
94
- readonly maxPixels?: number;
95
- }) => Layer.Layer<Inspector>;
96
- export type { UploadOptions };
97
- //# sourceMappingURL=index.d.mts.map
85
+ export {};
86
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","names":[],"sources":["../../src/browser/upload.ts"],"mappings":";;;qBAUa,eAAa,OAAA;YAWd,uBAAuB,cAAc;;;;;;qBAEpC,qBAAqB;;qBAOrB,YAAU,OAAA;;;;;qBAKV,UAAQ,OAAA;;;;;;;;;;;;;;;;;;;;;;qBACR,aAAW,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YACZ,qBAAqB,YAAY;iBAqB5B;;WAEN;;;;;;WAMA,UAAU,SAAS;;;;;;;;;;qBAWjB,SAAM,MACX,MAAI,UACD,kBACR,OAAO,OAAO,aAAa"}
@@ -0,0 +1,87 @@
1
+ import { Cause, Effect, Option, Queue, Schema, Stream } from "effect";
2
+ import { HashedAsset } from "../asset.js";
3
+ // src/browser/upload.ts
4
+ /**
5
+ * An image sent to the upload route from a browser: the bytes go once, with
6
+ * their progress reported as they go, and the route's facts come back as the
7
+ * `HashedAsset` to store. `fetch` reports no upload progress, so this is an
8
+ * `XMLHttpRequest`, and interrupting the stream aborts it.
9
+ */
10
+ /** Why an upload did not end in facts: the route's refusal, or no answer at all. */
11
+ const UploadRefusal = Schema.Literals([
12
+ "Forbidden",
13
+ "Unauthenticated",
14
+ "TooLarge",
15
+ "Unsupported",
16
+ "Malformed",
17
+ "Network",
18
+ "Unexpected"
19
+ ]);
20
+ var UploadFailed = class extends Schema.TaggedError()("UploadFailed", {
21
+ reason: UploadRefusal,
22
+ /** The HTTP status, `0` when there was no answer. */
23
+ status: Schema.Number
24
+ }) {};
25
+ /** How far the bytes have gone: `loaded` of `total`. */
26
+ const Progressed = Schema.TaggedStruct("Progressed", {
27
+ loaded: Schema.Number,
28
+ total: Schema.Number
29
+ });
30
+ /** The route kept the image, and these are its facts. */
31
+ const Uploaded = Schema.TaggedStruct("Uploaded", { asset: HashedAsset });
32
+ const UploadEvent = Schema.Union([Progressed, Uploaded]);
33
+ const refusals = {
34
+ 400: "Malformed",
35
+ 401: "Unauthenticated",
36
+ 403: "Forbidden",
37
+ 413: "TooLarge",
38
+ 415: "Unsupported"
39
+ };
40
+ const decodeFacts = Schema.decodeUnknownOption(HashedAsset);
41
+ /** The facts in a 201's body, or none for a body that is not them. */
42
+ const factsOf = (body) => {
43
+ try {
44
+ return decodeFacts(JSON.parse(body));
45
+ } catch {
46
+ return Option.none();
47
+ }
48
+ };
49
+ /**
50
+ * Sends `file` to the upload route as its body, which the browser types by the
51
+ * file's own `type`:
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(() => {
58
+ const request = new XMLHttpRequest();
59
+ const fail = (reason) => Queue.failCauseUnsafe(queue, Cause.fail(new UploadFailed({
60
+ reason,
61
+ status: request.status
62
+ })));
63
+ request.upload.onprogress = (event) => {
64
+ Queue.offerUnsafe(queue, Progressed.make({
65
+ loaded: event.loaded,
66
+ total: event.lengthComputable ? event.total : file.size
67
+ }));
68
+ };
69
+ request.onload = () => {
70
+ if (request.status !== 201) return fail(refusals[request.status] ?? "Unexpected");
71
+ Option.match(factsOf(request.responseText), {
72
+ onNone: () => fail("Unexpected"),
73
+ onSome: (asset) => {
74
+ Queue.offerUnsafe(queue, Uploaded.make({ asset }));
75
+ Queue.endUnsafe(queue);
76
+ }
77
+ });
78
+ };
79
+ request.onerror = () => fail("Network");
80
+ request.open("POST", options.url ?? "/_media/upload");
81
+ for (const [name, value] of Object.entries(options.headers ?? {})) request.setRequestHeader(name, value);
82
+ request.send(file);
83
+ return request;
84
+ }), (request) => Effect.sync(() => request.abort())));
85
+ export { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, upload };
86
+
87
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.js","names":[],"sources":["../../src/browser/upload.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"],"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,CACH;CACF;CACA,QAAQ,eAAe;EACrB,IAAI,QAAQ,WAAW,KAAK,OAAO,KAAK,SAAS,QAAQ,WAAW,YAAY;EAChF,OAAO,MAAM,QAAQ,QAAQ,YAAY,GAAG;GAC1C,cAAc,KAAK,YAAY;GAC/B,SAAQ,UAAS;IACf,MAAM,YAAY,OAAO,SAAS,KAAK,EAAE,MAAM,CAAC,CAAC;IACjD,MAAM,UAAU,KAAK;GACvB;EACF,CAAC;CACH;CACA,QAAQ,gBAAgB,KAAK,SAAS;CACtC,QAAQ,KAAK,QAAQ,QAAQ,OAAO,gBAAgB;CACpD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,WAAW,CAAC,CAAC,GAC9D,QAAQ,iBAAiB,MAAM,KAAK;CACtC,QAAQ,KAAK,IAAI;CACjB,OAAO;AACT,CAAC,IAED,YAAW,OAAO,WAAW,QAAQ,MAAM,CAAC,CAC9C,CACF"}
@@ -1,8 +1,9 @@
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
1
  import { Layer } from "effect";
2
+ import { Inspector } from "../describe.js";
5
3
  import { KeyValueStore } from "effect/persistence";
4
+ import { Admission } from "../server/admission.js";
5
+ import { Originals, Transformer, Variants } from "../server/services.js";
6
+ import { StoredFacts, Uploads } from "../server/upload.js";
6
7
  import { Cache as Cache$1, ImagesBinding, R2Bucket, RateLimit } from "@cloudflare/workers-types";
7
8
  /** Originals in an R2 bucket, each under its content hash. */
8
9
  export declare const originalsR2: (bucket: R2Bucket) => Layer.Layer<Originals>;
@@ -22,7 +23,7 @@ export declare const transformerImages: (images: ImagesBinding) => Layer.Layer<T
22
23
  /**
23
24
  * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by
24
25
  * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the
25
- * application's own. `clear` and `size` list the whole bucket.
26
+ * application's own. `keys`, `clear` and `size` list the whole bucket.
26
27
  */
27
28
  export declare const keyValueStoreR2: (bucket: R2Bucket) => Layer.Layer<KeyValueStore.KeyValueStore>;
28
29
  /**
@@ -39,7 +40,8 @@ export declare const variantsR2: (bucket: R2Bucket, options?: {
39
40
  * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose
40
41
  * limit and period are its configuration. It answers yes or no, not when, so
41
42
  * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60
42
- * by default). A binding that fails admits the request, logged.
43
+ * by default). A binding that fails admits the request, reported as
44
+ * `AdmissionFailed`.
43
45
  */
44
46
  export declare const admissionRateLimit: (binding: RateLimit, options?: {
45
47
  readonly retryAfterSeconds?: number;
@@ -54,4 +56,4 @@ export declare const admissionRateLimit: (binding: RateLimit, options?: {
54
56
  * is refused.
55
57
  */
56
58
  export declare const inspectorImages: (images: ImagesBinding) => Layer.Layer<Inspector>;
57
- //# sourceMappingURL=index.d.mts.map
59
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":["Cache"],"sources":["../../src/cloudflare/index.ts"],"mappings":";;;;;;;;qBAyBa,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;;;;;;;qBAgIhE,aAAU,QACb,UAAQ;WACI;WAA0B,QAAQA;MACrD,MAAM,MAAM;;;;;;;;qBAkBF,qBAAkB,SACpB,WAAS;WACE;MACnB,MAAM,MAAM;;;;;;;;;;qBA0BF,kBAAe,QAAY,kBAAgB,MAAM,MAAM"}
@@ -1,9 +1,13 @@
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
1
  import { Effect, Layer, Option } from "effect";
2
+ import { Inspector } from "../describe.js";
3
+ import { OriginalNotFound, QuotaExhausted, TransformFailed } from "../server/errors.js";
6
4
  import { KeyValueStore } from "effect/persistence";
5
+ import { Diagnostics } from "foldkit-surface";
6
+ import { Admission, RateLimited } from "../server/admission.js";
7
+ import { admissionFailed, imageFailed, storeFailed } from "../server/diagnostics.js";
8
+ import { Originals, Transformer, Variants } from "../server/services.js";
9
+ import { StoredFacts, Uploads, decodeFacts, encodeFacts, factsKey } from "../server/upload.js";
10
+ import { makeVariants } from "../server/stores.js";
7
11
  // src/cloudflare/index.ts
8
12
  /** Originals in an R2 bucket, each under its content hash. */
9
13
  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({
@@ -49,11 +53,11 @@ const transformerImages = (images) => Layer.succeed(Transformer, { transform: (o
49
53
  };
50
54
  },
51
55
  catch: (cause) => cause
52
- }).pipe(Effect.catch((cause) => isImagesError(cause) && cause.code === QUOTA_EXHAUSTED ? Effect.fail(new QuotaExhausted({})) : Effect.logWarning("Media.transform failed", cause).pipe(Effect.andThen(Effect.fail(new TransformFailed({})))))) });
56
+ }).pipe(Effect.catch((cause) => isImagesError(cause) && cause.code === QUOTA_EXHAUSTED ? Effect.fail(new QuotaExhausted({})) : Diagnostics.report(imageFailed("transform", cause)).pipe(Effect.andThen(Effect.fail(new TransformFailed({})))))) });
53
57
  /**
54
58
  * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by
55
59
  * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the
56
- * application's own. `clear` and `size` list the whole bucket.
60
+ * application's own. `keys`, `clear` and `size` list the whole bucket.
57
61
  */
58
62
  const keyValueStoreR2 = (bucket) => Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket));
59
63
  const r2Store = (bucket) => {
@@ -66,7 +70,7 @@ const r2Store = (bucket) => {
66
70
  cause
67
71
  })
68
72
  });
69
- const keys = async () => {
73
+ const allKeys = async () => {
70
74
  const found = [];
71
75
  let cursor;
72
76
  do {
@@ -85,10 +89,11 @@ const r2Store = (bucket) => {
85
89
  set: (key, value) => attempt("set", key, async () => void await bucket.put(key, value)),
86
90
  remove: (key) => attempt("remove", key, () => bucket.delete(key)),
87
91
  clear: attempt("clear", void 0, async () => {
88
- const all = await keys();
92
+ const all = await allKeys();
89
93
  for (let at = 0; at < all.length; at += 1e3) await bucket.delete(all.slice(at, at + 1e3));
90
94
  }),
91
- size: attempt("size", void 0, async () => (await keys()).length)
95
+ size: attempt("size", void 0, async () => (await allKeys()).length),
96
+ keys: attempt("keys", void 0, allKeys)
92
97
  });
93
98
  };
94
99
  const edgeKey = (key) => `https://foldkit-media.invalid/${key}`;
@@ -103,7 +108,12 @@ const withEdge = (behind, edge) => {
103
108
  "cache-control": "public, max-age=31536000, immutable"
104
109
  } })),
105
110
  catch: (cause) => cause
106
- }).pipe(Effect.catch((cause) => Effect.logWarning("Media: the edge cache failed a write", cause)));
111
+ }).pipe(Effect.catch((cause) => Diagnostics.report(storeFailed({
112
+ store: "edge",
113
+ operation: "write",
114
+ key,
115
+ cause
116
+ }))));
107
117
  const behindEdge = (key) => behind.get(key).pipe(Effect.tap((found) => Option.match(found, {
108
118
  onNone: () => Effect.void,
109
119
  onSome: (kept) => fill(key, kept.encoded)
@@ -121,7 +131,12 @@ const withEdge = (behind, edge) => {
121
131
  });
122
132
  },
123
133
  catch: (cause) => cause
124
- }).pipe(Effect.catch((cause) => Effect.logWarning("Media: the edge cache failed a read", cause).pipe(Effect.as(Option.none()))), Effect.flatMap((found) => Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),
134
+ }).pipe(Effect.catch((cause) => Diagnostics.report(storeFailed({
135
+ store: "edge",
136
+ operation: "read",
137
+ key,
138
+ cause
139
+ })).pipe(Effect.as(Option.none()))), Effect.flatMap((found) => Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),
125
140
  put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded)))
126
141
  };
127
142
  };
@@ -147,9 +162,14 @@ const variantsR2 = (bucket, options = {}) => {
147
162
  * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose
148
163
  * limit and period are its configuration. It answers yes or no, not when, so
149
164
  * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60
150
- * by default). A binding that fails admits the request, logged.
165
+ * by default). A binding that fails admits the request, reported as
166
+ * `AdmissionFailed`.
151
167
  */
152
- const admissionRateLimit = (binding, options = {}) => Layer.succeed(Admission, { admit: (client) => Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(Effect.catch((error) => Effect.logWarning("Media: the rate limit binding failed; admitting", error).pipe(Effect.as({ success: true }))), Effect.flatMap(({ success }) => success ? Effect.void : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })))) });
168
+ const admissionRateLimit = (binding, options = {}) => Layer.succeed(Admission, { admit: (client) => Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(Effect.catch((cause) => Diagnostics.report(admissionFailed({
169
+ limiter: "binding",
170
+ client,
171
+ cause
172
+ })).pipe(Effect.as({ success: true }))), Effect.flatMap(({ success }) => success ? Effect.void : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })))) });
153
173
  /**
154
174
  * The `Inspector` through the Images binding: an original's size from `info`,
155
175
  * which costs no transformation. It makes no thumbnail, since raw pixels are
@@ -167,7 +187,7 @@ const inspectorImages = (images) => Layer.succeed(Inspector, { inspect: (bytes)
167
187
  height: info.height,
168
188
  alpha: info.format !== "image/jpeg",
169
189
  thumbnail: Option.none()
170
- }) : Effect.fail(info)), Effect.catch((cause) => Effect.logWarning("Media.inspect failed", cause).pipe(Effect.andThen(Effect.fail(new TransformFailed({})))))) });
190
+ }) : Effect.fail(info)), Effect.catch((cause) => Diagnostics.report(imageFailed("inspect", cause)).pipe(Effect.andThen(Effect.fail(new TransformFailed({})))))) });
171
191
  export { admissionRateLimit, inspectorImages, keyValueStoreR2, originalsR2, storedFactsR2, transformerImages, uploadsR2, variantsR2 };
172
192
 
173
- //# sourceMappingURL=index.mjs.map
193
+ //# sourceMappingURL=index.js.map