foldkit-media 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -4
- package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
- package/dist/asset.d.ts.map +1 -0
- package/dist/asset.js +66 -0
- package/dist/asset.js.map +1 -0
- package/dist/browser/index.d.ts +15 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +69 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
- package/dist/browser/upload.d.ts.map +1 -0
- package/dist/browser/upload.js +87 -0
- package/dist/browser/upload.js.map +1 -0
- package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
- package/dist/cloudflare/index.d.ts.map +1 -0
- package/dist/cloudflare/{index.mjs → index.js} +35 -15
- package/dist/cloudflare/index.js.map +1 -0
- package/dist/describe.d.ts +32 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +30 -0
- package/dist/describe.js.map +1 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
- package/dist/format.js.map +1 -0
- package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
- package/dist/icon.d.ts.map +1 -0
- package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
- package/dist/icon.js.map +1 -0
- package/dist/icons/{index.d.mts → index.d.ts} +2 -2
- package/dist/icons/index.d.ts.map +1 -0
- package/dist/icons/{index.mjs → index.js} +2 -2
- package/dist/icons/index.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/layout.d.ts +60 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +72 -0
- package/dist/layout.js.map +1 -0
- package/dist/limits.d.ts +3 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
- package/dist/limits.js.map +1 -0
- package/dist/picture.d.ts +88 -0
- package/dist/picture.d.ts.map +1 -0
- package/dist/picture.js +113 -0
- package/dist/picture.js.map +1 -0
- package/dist/placeholder.d.ts +16 -0
- package/dist/placeholder.d.ts.map +1 -0
- package/dist/placeholder.js +38 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +93 -0
- package/dist/provider.js.map +1 -0
- package/dist/server/admission.d.ts +31 -0
- package/dist/server/admission.d.ts.map +1 -0
- package/dist/server/admission.js +41 -0
- package/dist/server/admission.js.map +1 -0
- package/dist/server/api.d.ts +14 -0
- package/dist/server/api.d.ts.map +1 -0
- package/dist/server/api.js +21 -0
- package/dist/server/api.js.map +1 -0
- package/dist/server/diagnostics.d.ts +53 -0
- package/dist/server/diagnostics.d.ts.map +1 -0
- package/dist/server/diagnostics.js +50 -0
- package/dist/server/diagnostics.js.map +1 -0
- package/dist/server/errors.d.ts +24 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
- package/dist/server/errors.js.map +1 -0
- package/dist/server/facts.d.ts +36 -0
- package/dist/server/facts.d.ts.map +1 -0
- package/dist/server/facts.js +126 -0
- package/dist/server/facts.js.map +1 -0
- package/dist/server/fetch.d.ts +29 -0
- package/dist/server/fetch.d.ts.map +1 -0
- package/dist/server/fetch.js +32 -0
- package/dist/server/fetch.js.map +1 -0
- package/dist/server/handlers.d.ts +48 -0
- package/dist/server/handlers.d.ts.map +1 -0
- package/dist/server/handlers.js +151 -0
- package/dist/server/handlers.js.map +1 -0
- package/dist/server/headers.d.ts +47 -0
- package/dist/server/headers.d.ts.map +1 -0
- package/dist/server/headers.js +134 -0
- package/dist/server/headers.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/materialize.d.ts +36 -0
- package/dist/server/materialize.d.ts.map +1 -0
- package/dist/server/materialize.js +62 -0
- package/dist/server/materialize.js.map +1 -0
- package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
- package/dist/server/services.d.ts.map +1 -0
- package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
- package/dist/server/services.js.map +1 -0
- package/dist/server/stores.d.ts +27 -0
- package/dist/server/stores.d.ts.map +1 -0
- package/dist/server/stores.js +62 -0
- package/dist/server/stores.js.map +1 -0
- package/dist/server/upload.d.ts +113 -0
- package/dist/server/upload.d.ts.map +1 -0
- package/dist/server/upload.js +185 -0
- package/dist/server/upload.js.map +1 -0
- package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
- package/dist/sharp/index.d.ts.map +1 -0
- package/dist/sharp/{index.mjs → index.js} +11 -9
- package/dist/sharp/index.js.map +1 -0
- package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
- package/dist/unpic/index.d.ts.map +1 -0
- package/dist/unpic/{index.mjs → index.js} +3 -3
- package/dist/unpic/index.js.map +1 -0
- package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
- package/dist/variant.d.ts.map +1 -0
- package/dist/variant.js +75 -0
- package/dist/variant.js.map +1 -0
- package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
- package/dist/vite/icons.d.ts.map +1 -0
- package/dist/vite/{index.mjs → icons.js} +7 -168
- package/dist/vite/icons.js.map +1 -0
- package/dist/vite/images.d.ts +20 -0
- package/dist/vite/images.d.ts.map +1 -0
- package/dist/vite/images.js +167 -0
- package/dist/vite/images.js.map +1 -0
- package/dist/vite/index.d.ts +3 -0
- package/dist/vite/index.js +3 -0
- package/dist/widths.d.ts +22 -0
- package/dist/widths.d.ts.map +1 -0
- package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
- package/dist/widths.js.map +1 -0
- package/package.json +23 -22
- package/dist/asset-BLo8VWmd.d.mts.map +0 -1
- package/dist/browser/index.d.mts.map +0 -1
- package/dist/browser/index.mjs +0 -150
- package/dist/browser/index.mjs.map +0 -1
- package/dist/cloudflare/index.d.mts.map +0 -1
- package/dist/cloudflare/index.mjs.map +0 -1
- package/dist/describe-BOgc0xbR.d.mts +0 -52
- package/dist/describe-BOgc0xbR.d.mts.map +0 -1
- package/dist/describe-C6sWA_8p.mjs +0 -171
- package/dist/describe-C6sWA_8p.mjs.map +0 -1
- package/dist/errors-BhEgXJ4m.mjs.map +0 -1
- package/dist/format-BCRTFU9j.mjs.map +0 -1
- package/dist/icon-0A2dBtqj.mjs.map +0 -1
- package/dist/icon-BGtxExTN.d.mts.map +0 -1
- package/dist/icons/index.d.mts.map +0 -1
- package/dist/icons/index.mjs.map +0 -1
- package/dist/index.d.mts +0 -157
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -322
- package/dist/index.mjs.map +0 -1
- package/dist/limits-B4hHpyfE.mjs.map +0 -1
- package/dist/provider-CB0nqu0m.d.mts.map +0 -1
- package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
- package/dist/server/index.d.mts +0 -170
- package/dist/server/index.d.mts.map +0 -1
- package/dist/server/index.mjs +0 -231
- package/dist/server/index.mjs.map +0 -1
- package/dist/services-7B4hsQM7.mjs.map +0 -1
- package/dist/services-BZoK2VOY.d.mts.map +0 -1
- package/dist/sharp/index.d.mts.map +0 -1
- package/dist/sharp/index.mjs.map +0 -1
- package/dist/stores-CxraN3kt.mjs +0 -490
- package/dist/stores-CxraN3kt.mjs.map +0 -1
- package/dist/unpic/index.d.mts.map +0 -1
- package/dist/unpic/index.mjs.map +0 -1
- package/dist/upload-lVLMRJoC.d.mts +0 -160
- package/dist/upload-lVLMRJoC.d.mts.map +0 -1
- package/dist/variant-B-vyMmFB.d.mts.map +0 -1
- package/dist/vite/index.d.mts.map +0 -1
- package/dist/vite/index.mjs.map +0 -1
- package/dist/widths-qp3jshiF.mjs.map +0 -1
- package/dist/widths-upkgLdek.d.mts +0 -36
- package/dist/widths-upkgLdek.d.mts.map +0 -1
package/dist/widths.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
/**
|
|
3
|
+
* The widths an image is made at, ascending. The view takes candidates from
|
|
4
|
+
* it, a server's request Schema accepts only these, and a build emits only
|
|
5
|
+
* these, so the three cannot disagree.
|
|
6
|
+
*/
|
|
7
|
+
export interface Widths {
|
|
8
|
+
readonly values: ReadonlyArray<number>;
|
|
9
|
+
/** Decodes a width on the ladder and refuses any other. */
|
|
10
|
+
readonly Schema: Schema.Codec<number>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* A ladder from its widths. Refuses an empty list, a width that is not a
|
|
14
|
+
* positive integer, and a repeated width: each is a mistake in the
|
|
15
|
+
* declaration, not something to repair quietly.
|
|
16
|
+
*/
|
|
17
|
+
export declare const make: (values: ReadonlyArray<number>) => Widths;
|
|
18
|
+
/** Phones through a 2560px screen at 1x, and 1280px at 2x. */
|
|
19
|
+
export declare const standard: Widths;
|
|
20
|
+
/** The smallest width at or above `width`, or the largest when none is. */
|
|
21
|
+
export declare const atLeast: (widths: Widths, width: number) => number;
|
|
22
|
+
//# sourceMappingURL=widths.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widths.d.ts","names":[],"sources":["../src/widths.ts"],"mappings":";;;;;;iBAOiB;WACN,QAAQ;;WAER,QAAQ,OAAO;;;;;;;qBAQb,OAAI,QAAY,0BAAwB;;qBAiBxC,UAAU;;qBAGV,UAAO,QAAY,QAAM"}
|
|
@@ -1,11 +1,5 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
1
|
import { Schema } from "effect";
|
|
3
2
|
// src/widths.ts
|
|
4
|
-
var widths_exports = /* @__PURE__ */ __exportAll({
|
|
5
|
-
atLeast: () => atLeast,
|
|
6
|
-
make: () => make,
|
|
7
|
-
standard: () => standard
|
|
8
|
-
});
|
|
9
3
|
/**
|
|
10
4
|
* A ladder from its widths. Refuses an empty list, a width that is not a
|
|
11
5
|
* positive integer, and a repeated width: each is a mistake in the
|
|
@@ -34,6 +28,6 @@ const standard = make([
|
|
|
34
28
|
]);
|
|
35
29
|
/** The smallest width at or above `width`, or the largest when none is. */
|
|
36
30
|
const atLeast = (widths, width) => widths.values.find((value) => value >= width) ?? widths.values[widths.values.length - 1];
|
|
37
|
-
export {
|
|
31
|
+
export { atLeast, make, standard };
|
|
38
32
|
|
|
39
|
-
//# sourceMappingURL=widths
|
|
33
|
+
//# sourceMappingURL=widths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widths.js","names":[],"sources":["../src/widths.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/**\n * The widths an image is made at, ascending. The view takes candidates from\n * it, a server's request Schema accepts only these, and a build emits only\n * these, so the three cannot disagree.\n */\nexport interface Widths {\n readonly values: ReadonlyArray<number>\n /** Decodes a width on the ladder and refuses any other. */\n readonly Schema: Schema.Codec<number>\n}\n\n/**\n * A ladder from its widths. Refuses an empty list, a width that is not a\n * positive integer, and a repeated width: each is a mistake in the\n * declaration, not something to repair quietly.\n */\nexport const make = (values: ReadonlyArray<number>): Widths => {\n if (values.length === 0) throw new Error('Widths.make: a ladder needs at least one width')\n for (const width of values) {\n if (!Number.isInteger(width) || width <= 0) {\n throw new Error(`Widths.make: ${width} is not a positive integer width`)\n }\n }\n const sorted = [...values].sort((a, b) => a - b)\n for (let index = 1; index < sorted.length; index++) {\n if (sorted[index] === sorted[index - 1]) {\n throw new Error(`Widths.make: ${sorted[index]} appears twice`)\n }\n }\n return { values: sorted, Schema: Schema.Literals(sorted) }\n}\n\n/** Phones through a 2560px screen at 1x, and 1280px at 2x. */\nexport const standard: Widths = make([320, 480, 640, 828, 1080, 1280, 1920, 2560])\n\n/** The smallest width at or above `width`, or the largest when none is. */\nexport const atLeast = (widths: Widths, width: number): number =>\n widths.values.find(value => value >= width) ?? widths.values[widths.values.length - 1]!\n"],"mappings":";;;;;;;AAkBA,MAAa,QAAQ,WAA0C;CAC7D,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,MAAM,gDAAgD;CACzF,KAAK,MAAM,SAAS,QAClB,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,MAAM,gBAAgB,MAAM,iCAAiC;CAG3E,MAAM,SAAS,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;CAC/C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SACzC,IAAI,OAAO,WAAW,OAAO,QAAQ,IACnC,MAAM,IAAI,MAAM,gBAAgB,OAAO,OAAO,eAAe;CAGjE,OAAO;EAAE,QAAQ;EAAQ,QAAQ,OAAO,SAAS,MAAM;CAAE;AAC3D;;AAGA,MAAa,WAAmB,KAAK;CAAC;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;AAAI,CAAC;;AAGjF,MAAa,WAAW,QAAgB,UACtC,OAAO,OAAO,MAAK,UAAS,SAAS,KAAK,KAAK,OAAO,OAAO,OAAO,OAAO,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-media",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Responsive images for Foldkit Plus: an image is a URL to write, through providers that share one width ladder.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -27,43 +27,43 @@
|
|
|
27
27
|
"exports": {
|
|
28
28
|
".": {
|
|
29
29
|
"foldkit-plus:source": "./src/index.ts",
|
|
30
|
-
"types": "./dist/index.d.
|
|
31
|
-
"import": "./dist/index.
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.js"
|
|
32
32
|
},
|
|
33
33
|
"./browser": {
|
|
34
34
|
"foldkit-plus:source": "./src/browser/index.ts",
|
|
35
|
-
"types": "./dist/browser/index.d.
|
|
36
|
-
"import": "./dist/browser/index.
|
|
35
|
+
"types": "./dist/browser/index.d.ts",
|
|
36
|
+
"import": "./dist/browser/index.js"
|
|
37
37
|
},
|
|
38
38
|
"./icons": {
|
|
39
39
|
"foldkit-plus:source": "./src/icons/index.ts",
|
|
40
|
-
"types": "./dist/icons/index.d.
|
|
41
|
-
"import": "./dist/icons/index.
|
|
40
|
+
"types": "./dist/icons/index.d.ts",
|
|
41
|
+
"import": "./dist/icons/index.js"
|
|
42
42
|
},
|
|
43
43
|
"./server": {
|
|
44
44
|
"foldkit-plus:source": "./src/server/index.ts",
|
|
45
|
-
"types": "./dist/server/index.d.
|
|
46
|
-
"import": "./dist/server/index.
|
|
45
|
+
"types": "./dist/server/index.d.ts",
|
|
46
|
+
"import": "./dist/server/index.js"
|
|
47
47
|
},
|
|
48
48
|
"./cloudflare": {
|
|
49
49
|
"foldkit-plus:source": "./src/cloudflare/index.ts",
|
|
50
|
-
"types": "./dist/cloudflare/index.d.
|
|
51
|
-
"import": "./dist/cloudflare/index.
|
|
50
|
+
"types": "./dist/cloudflare/index.d.ts",
|
|
51
|
+
"import": "./dist/cloudflare/index.js"
|
|
52
52
|
},
|
|
53
53
|
"./sharp": {
|
|
54
54
|
"foldkit-plus:source": "./src/sharp/index.ts",
|
|
55
|
-
"types": "./dist/sharp/index.d.
|
|
56
|
-
"import": "./dist/sharp/index.
|
|
55
|
+
"types": "./dist/sharp/index.d.ts",
|
|
56
|
+
"import": "./dist/sharp/index.js"
|
|
57
57
|
},
|
|
58
58
|
"./unpic": {
|
|
59
59
|
"foldkit-plus:source": "./src/unpic/index.ts",
|
|
60
|
-
"types": "./dist/unpic/index.d.
|
|
61
|
-
"import": "./dist/unpic/index.
|
|
60
|
+
"types": "./dist/unpic/index.d.ts",
|
|
61
|
+
"import": "./dist/unpic/index.js"
|
|
62
62
|
},
|
|
63
63
|
"./vite": {
|
|
64
64
|
"foldkit-plus:source": "./src/vite/index.ts",
|
|
65
|
-
"types": "./dist/vite/index.d.
|
|
66
|
-
"import": "./dist/vite/index.
|
|
65
|
+
"types": "./dist/vite/index.d.ts",
|
|
66
|
+
"import": "./dist/vite/index.js"
|
|
67
67
|
},
|
|
68
68
|
"./client": {
|
|
69
69
|
"foldkit-plus:source": "./client.d.ts",
|
|
@@ -77,17 +77,18 @@
|
|
|
77
77
|
"client.d.ts"
|
|
78
78
|
],
|
|
79
79
|
"dependencies": {
|
|
80
|
-
"thumbhash": "^0.1.1"
|
|
80
|
+
"thumbhash": "^0.1.1",
|
|
81
|
+
"foldkit-surface": "0.12.0"
|
|
81
82
|
},
|
|
82
83
|
"peerDependencies": {
|
|
83
|
-
"effect": "^4.
|
|
84
|
+
"effect": "^4.1.0",
|
|
84
85
|
"sharp": ">=0.34.0",
|
|
85
86
|
"unpic": "^4.0.0"
|
|
86
87
|
},
|
|
87
88
|
"devDependencies": {
|
|
88
89
|
"@cloudflare/workers-types": "5.20261022.1",
|
|
89
|
-
"@effect/platform-node": "^4.
|
|
90
|
-
"effect": "^4.
|
|
90
|
+
"@effect/platform-node": "^4.1.1",
|
|
91
|
+
"effect": "^4.1.1",
|
|
91
92
|
"miniflare": "4.20260730.0",
|
|
92
93
|
"sharp": "^0.35.5",
|
|
93
94
|
"tsdown": "^0.23.1",
|
|
@@ -104,7 +105,7 @@
|
|
|
104
105
|
}
|
|
105
106
|
},
|
|
106
107
|
"scripts": {
|
|
107
|
-
"build": "tsdown",
|
|
108
|
+
"build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
|
|
108
109
|
"typecheck": "tsc -b"
|
|
109
110
|
}
|
|
110
111
|
}
|
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/browser/upload.ts","../../src/browser/index.ts"],"mappings":";;;;qBAUa,eAAa,OAAA;YAWd,uBAAuB,cAAc;;;;;;qBAEpC,qBAAqB;;qBAOrB,YAAU,OAAA;;;;;qBAKV,UAAQ,OAAA;;;;;;;;;;;;;;;;;;;;;;qBACR,aAAW,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YACZ,qBAAqB,YAAY;UAqB5B;;WAEN;;;;;;WAMA,UAAU,SAAS;;;;;;;;;;qBAWjB,SAAM,MACX,MAAI,UACD,kBACR,OAAO,OAAO,aAAa;;;;;;;;qBCpDjB,mBAAgB;WACP;MACnB,MAAM,MAAM"}
|
package/dist/browser/index.mjs
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
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
|
|
88
|
-
/**
|
|
89
|
-
* An image's facts read in the browser, where it is chosen: `describe(key,
|
|
90
|
-
* bytes)` over `inspectorBrowser()` gives its `ImageAsset`, size, hash and
|
|
91
|
-
* ThumbHash included, before it is uploaded or stored, with no server to ask.
|
|
92
|
-
* The browser's own decoder reads it, so what it cannot show is refused here.
|
|
93
|
-
*/
|
|
94
|
-
const THUMBNAIL_SIDE = 100;
|
|
95
|
-
const ALPHA_TILE_SIDE = 512;
|
|
96
|
-
const DEFAULT_MAX_PIXELS = 5e7;
|
|
97
|
-
/**
|
|
98
|
-
* The `Inspector` in a browser or a web worker: the size from the decoded
|
|
99
|
-
* picture, a thumbnail drawn on an `OffscreenCanvas`, and alpha where any
|
|
100
|
-
* decoded pixel is not opaque. A file the browser cannot decode is
|
|
101
|
-
* `TransformFailed`; one above `maxPixels` is `OriginalTooLarge`, its pixels
|
|
102
|
-
* released at once.
|
|
103
|
-
*/
|
|
104
|
-
const inspectorBrowser = (options = {}) => {
|
|
105
|
-
const maxPixels = nonNegativeInteger("maxPixels", options.maxPixels ?? DEFAULT_MAX_PIXELS);
|
|
106
|
-
return Layer.succeed(Inspector, { inspect: (bytes) => Effect.acquireUseRelease(Effect.tryPromise({
|
|
107
|
-
try: () => createImageBitmap(new Blob([bytes])),
|
|
108
|
-
catch: () => new TransformFailed({})
|
|
109
|
-
}), (bitmap) => Effect.gen(function* () {
|
|
110
|
-
const { width, height } = bitmap;
|
|
111
|
-
if (width * height > maxPixels) return yield* new OriginalTooLarge({
|
|
112
|
-
size: width * height,
|
|
113
|
-
limit: maxPixels,
|
|
114
|
-
unit: "pixels"
|
|
115
|
-
});
|
|
116
|
-
const alphaCanvas = new OffscreenCanvas(Math.min(width, ALPHA_TILE_SIDE), Math.min(height, ALPHA_TILE_SIDE));
|
|
117
|
-
const alphaContext = alphaCanvas.getContext("2d");
|
|
118
|
-
if (alphaContext === null) return yield* new TransformFailed({});
|
|
119
|
-
let alpha = false;
|
|
120
|
-
for (let top = 0; top < height && !alpha; top += ALPHA_TILE_SIDE) for (let left = 0; left < width && !alpha; left += ALPHA_TILE_SIDE) {
|
|
121
|
-
const tileWidth = Math.min(ALPHA_TILE_SIDE, width - left);
|
|
122
|
-
const tileHeight = Math.min(ALPHA_TILE_SIDE, height - top);
|
|
123
|
-
alphaCanvas.width = tileWidth;
|
|
124
|
-
alphaCanvas.height = tileHeight;
|
|
125
|
-
alphaContext.drawImage(bitmap, left, top, tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);
|
|
126
|
-
const pixels = alphaContext.getImageData(0, 0, tileWidth, tileHeight).data;
|
|
127
|
-
for (let at = 3; at < pixels.length && !alpha; at += 4) alpha = pixels[at] < 255;
|
|
128
|
-
}
|
|
129
|
-
const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(width, height));
|
|
130
|
-
const side = (length) => Math.max(1, Math.round(length * scale));
|
|
131
|
-
const canvas = new OffscreenCanvas(side(width), side(height));
|
|
132
|
-
const context = canvas.getContext("2d");
|
|
133
|
-
if (context === null) return yield* new TransformFailed({});
|
|
134
|
-
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
135
|
-
const rgba = new Uint8Array(context.getImageData(0, 0, canvas.width, canvas.height).data.buffer);
|
|
136
|
-
return {
|
|
137
|
-
width,
|
|
138
|
-
height,
|
|
139
|
-
alpha,
|
|
140
|
-
thumbnail: Option.some({
|
|
141
|
-
width: canvas.width,
|
|
142
|
-
height: canvas.height,
|
|
143
|
-
rgba
|
|
144
|
-
})
|
|
145
|
-
};
|
|
146
|
-
}), (bitmap) => Effect.sync(() => bitmap.close())) });
|
|
147
|
-
};
|
|
148
|
-
export { Progressed, UploadEvent, UploadFailed, UploadRefusal, Uploaded, inspectorBrowser, upload };
|
|
149
|
-
|
|
150
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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;EAC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O,MAAM,CAAC,CAC5C,EACJ,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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;;;;;AAMH,MAAa,aAAa,WACxB,MAAM,QAAQ,SAAS,EACrB,MAAM,MAAM,OAAO,UACjB,OAAO,QAAQ,YAAY;CACzB,MAAM,OAAO,IAAI,MAAM,KAAK;CAC5B,MAAM,OAAO,IAAI,SAAS,IAAI,GAAG,YAAY,KAAK,CAAC;AACrD,CAAC,EACL,CAAC;;AAGH,MAAa,iBAAiB,WAC5B,MAAM,QAAQ,aAAa,EACzB,MAAK,SACH,OAAO,QAAQ,YAAY;CACzB,MAAM,SAAS,MAAM,OAAO,IAAI,SAAS,IAAI,CAAC;CAC9C,OAAO,WAAW,OAAO,OAAO,KAAK,IAAI,OAAO,KAAK,YAAY,MAAM,OAAO,KAAK,CAAC,CAAC;AACvF,CAAC,EACL,CAAC;AAGH,MAAM,kBAAkB;AAExB,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM;;;;;;AAOvF,MAAa,qBAAqB,WAChC,MAAM,QAAQ,aAAa,EACzB,YAAY,U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H;AACF;;;;;;;AAQA,MAAa,sBACX,SACA,UAAmD,CAAC,MAEpD,MAAM,QAAQ,WAAW,EACvB,QAAO,WACL,OAAO,iBAAiB,QAAQ,MAAM,EAAE,KAAK,iBAAiB,SAAS,CAAC,CAAC,CAAC,CAAC,KACzE,OAAO,OAAM,UACX,OAAO,WAAW,mDAAmD,KAAK,CAAC,CAAC,KAC1E,OAAO,GAAG,EAAE,SAAS,KAAK,CAAC,CAC7B,CACF,GACA,OAAO,SAAS,EAAE,cAChB,UACI,OAAO,OACP,OAAO,KAAK,IAAI,YAAY,EAAE,mBAAmB,QAAQ,qBAAqB,GAAG,CAAC,CAAC,CACzF,CACF,EACJ,CAAC;;;;;;;;;;AAWH,MAAa,mBAAmB,WAC9B,MAAM,QAAQ,WAAW,EACvB,UAAS,UACP,OAAO,WAAW;CAChB,WACE,OAAO,KACL,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAC3B;CACF,QAAO,UAAS;AAClB,CAAC,CAAC,CAAC,KACD,OAAO,SAAQ,SAEb,WAAW,OACP,OAAO,QAAQ;CACb,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,OAAO,KAAK,WAAW;CACvB,WAAW,OAAO,KAAK;AACzB,CAAC,IACD,OAAO,KAAK,IAAI,CACtB,GACA,OAAO,OAAM,UACX,OAAO,WAAW,wBAAwB,KAAK,CAAC,CAAC,KAC/C,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD,CACF,CACF,EACJ,CAAC"}
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { r as ImageAsset } from "./asset-BLo8VWmd.mjs";
|
|
2
|
-
import { Context, Effect, Option, Schema } from "effect";
|
|
3
|
-
declare const OriginalNotFound_base: Schema.Class<OriginalNotFound, Schema.TaggedStruct<"OriginalNotFound", {
|
|
4
|
-
readonly hash: Schema.String;
|
|
5
|
-
}>, import("effect/Cause").YieldableError>;
|
|
6
|
-
/** No original is stored under this hash. */
|
|
7
|
-
declare class OriginalNotFound extends OriginalNotFound_base {}
|
|
8
|
-
declare const OriginalTooLarge_base: Schema.Class<OriginalTooLarge, Schema.TaggedStruct<"OriginalTooLarge", {
|
|
9
|
-
readonly size: Schema.Number;
|
|
10
|
-
readonly limit: Schema.Number;
|
|
11
|
-
readonly unit: Schema.Literals<readonly ["bytes", "pixels"]>;
|
|
12
|
-
}>, import("effect/Cause").YieldableError>;
|
|
13
|
-
/** The original is larger than the server will read: in bytes, or in pixels once decoded. */
|
|
14
|
-
declare class OriginalTooLarge extends OriginalTooLarge_base {}
|
|
15
|
-
declare const TransformFailed_base: Schema.Class<TransformFailed, Schema.TaggedStruct<"TransformFailed", {}>, import("effect/Cause").YieldableError>;
|
|
16
|
-
/**
|
|
17
|
-
* The transformer could not make the variant: the original is not an image it
|
|
18
|
-
* reads, or it failed. Its reason stays in the server's log, not the response.
|
|
19
|
-
*/
|
|
20
|
-
declare class TransformFailed extends TransformFailed_base {}
|
|
21
|
-
declare const QuotaExhausted_base: Schema.Class<QuotaExhausted, Schema.TaggedStruct<"QuotaExhausted", {}>, import("effect/Cause").YieldableError>;
|
|
22
|
-
/** The host's transformation allowance is spent; variants already made still serve. */
|
|
23
|
-
declare class QuotaExhausted extends QuotaExhausted_base {}
|
|
24
|
-
/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */
|
|
25
|
-
interface Thumbnail {
|
|
26
|
-
readonly width: number;
|
|
27
|
-
readonly height: number;
|
|
28
|
-
readonly rgba: Uint8Array;
|
|
29
|
-
}
|
|
30
|
-
/** What an inspector reads of an original. */
|
|
31
|
-
interface Inspected {
|
|
32
|
-
readonly width: number;
|
|
33
|
-
readonly height: number;
|
|
34
|
-
/** Whether it may have transparent pixels; an inspector that cannot tell says yes. */
|
|
35
|
-
readonly alpha: boolean;
|
|
36
|
-
/** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */
|
|
37
|
-
readonly thumbnail: Option.Option<Thumbnail>;
|
|
38
|
-
}
|
|
39
|
-
declare const Inspector_base: Context.ServiceClass<Inspector, "foldkit-media/Inspector", {
|
|
40
|
-
readonly inspect: (bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>;
|
|
41
|
-
}>;
|
|
42
|
-
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
43
|
-
declare class Inspector extends Inspector_base {}
|
|
44
|
-
/**
|
|
45
|
-
* An original's facts, as an `ImageAsset` under `key`: its size and alpha
|
|
46
|
-
* from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the
|
|
47
|
-
* inspector made a thumbnail. Where an original enters (an upload, a build, a
|
|
48
|
-
* page's content naming a URL), so its facts are derived once and stored.
|
|
49
|
-
*/
|
|
50
|
-
declare const describe: (key: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector>;
|
|
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 };
|
|
52
|
-
//# sourceMappingURL=describe-BOgc0xbR.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
-
import { r as standard$1 } from "./widths-qp3jshiF.mjs";
|
|
3
|
-
import { Context, Effect, Option, Schema, SchemaGetter } from "effect";
|
|
4
|
-
import { rgbaToThumbHash } from "thumbhash";
|
|
5
|
-
// src/variant.ts
|
|
6
|
-
var variant_exports = /* @__PURE__ */ __exportAll({
|
|
7
|
-
ContentHash: () => ContentHash,
|
|
8
|
-
PATH: () => PATH,
|
|
9
|
-
Quality: () => Quality,
|
|
10
|
-
Spelling: () => Spelling,
|
|
11
|
-
respell: () => respell,
|
|
12
|
-
revisionOf: () => revisionOf,
|
|
13
|
-
space: () => space,
|
|
14
|
-
standard: () => standard
|
|
15
|
-
});
|
|
16
|
-
/**
|
|
17
|
-
* Where a hosted variant lives: the original's content hash, then the variant.
|
|
18
|
-
* The server routes this path and `Provider.hosted` fills it in, so the two
|
|
19
|
-
* read one string. It ends in the format's extension, so a variant written
|
|
20
|
-
* out as a file is served with its type by any static host.
|
|
21
|
-
*/
|
|
22
|
-
const PATH = "/_image/:hash/:variant";
|
|
23
|
-
/** An original's SHA-256, in lowercase hex: its name in the store. */
|
|
24
|
-
const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/));
|
|
25
|
-
/** A quality from 1 to 100. */
|
|
26
|
-
const Quality = Schema.Int.check(Schema.isBetween({
|
|
27
|
-
minimum: 1,
|
|
28
|
-
maximum: 100
|
|
29
|
-
}));
|
|
30
|
-
const SPELLING = /^w([1-9]\d{0,4})(?:q([1-9]\d?|100))?(?:\.r([1-9]\d{0,3}))?\.(avif|webp|jpeg|png)$/;
|
|
31
|
-
/**
|
|
32
|
-
* The grammar every release reads, whatever its space: a spelling it matches
|
|
33
|
-
* may be one another release offers, so refusing it says nothing for good.
|
|
34
|
-
*/
|
|
35
|
-
const Spelling = Schema.String.check(Schema.isPattern(SPELLING));
|
|
36
|
-
/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */
|
|
37
|
-
const revisionOf = (spelling) => Number(SPELLING.exec(spelling)?.[3] ?? 0);
|
|
38
|
-
/** `spelling` at `revision`: the same variant, as that revision writes it. */
|
|
39
|
-
const respell = (spelling, revision) => spelling.replace(/(?:\.r\d+)?(\.[a-z]+)$/, revision === 0 ? "$1" : `.r${revision}$1`);
|
|
40
|
-
const distinct = (label, values) => {
|
|
41
|
-
if (new Set(values).size !== values.length) throw new Error(`Variant.space: a ${label} appears twice`);
|
|
42
|
-
};
|
|
43
|
-
/**
|
|
44
|
-
* A space from its ladders. Refuses no formats, a repeated format or
|
|
45
|
-
* quality, and a quality outside 1 to 100.
|
|
46
|
-
*/
|
|
47
|
-
const space = (options = {}) => {
|
|
48
|
-
const { widths = standard$1, formats = ["avif", "webp"], qualities = [], revision = 0 } = options;
|
|
49
|
-
if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`);
|
|
50
|
-
const unspellableWidth = widths.values.find((width) => width > 99999);
|
|
51
|
-
if (unspellableWidth !== void 0) throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`);
|
|
52
|
-
if (formats.length === 0) throw new Error("Variant.space: a space needs at least one format");
|
|
53
|
-
distinct("format", formats);
|
|
54
|
-
distinct("quality", qualities);
|
|
55
|
-
for (const quality of qualities) if (!Schema.is(Quality)(quality)) throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`);
|
|
56
|
-
return {
|
|
57
|
-
widths,
|
|
58
|
-
formats,
|
|
59
|
-
qualities,
|
|
60
|
-
revision,
|
|
61
|
-
schema: Spelling.check(Schema.makeFilter((spelling) => revisionOf(spelling) === revision || `not revision ${revision}`)).pipe(Schema.decodeTo(Schema.Struct({
|
|
62
|
-
width: widths.Schema,
|
|
63
|
-
format: Schema.Literals(formats),
|
|
64
|
-
quality: Schema.Option(Schema.Literals(qualities))
|
|
65
|
-
}), {
|
|
66
|
-
decode: SchemaGetter.transform((spelling) => {
|
|
67
|
-
const [, width, quality, , format] = SPELLING.exec(spelling);
|
|
68
|
-
return {
|
|
69
|
-
width: Number(width),
|
|
70
|
-
format,
|
|
71
|
-
quality: Option.map(Option.fromNullishOr(quality), Number)
|
|
72
|
-
};
|
|
73
|
-
}),
|
|
74
|
-
encode: SchemaGetter.transform(({ width, format, quality }) => `w${width}${Option.match(quality, {
|
|
75
|
-
onNone: () => "",
|
|
76
|
-
onSome: (value) => `q${value}`
|
|
77
|
-
})}${revision === 0 ? "" : `.r${revision}`}.${format}`)
|
|
78
|
-
})),
|
|
79
|
-
size: widths.values.length * formats.length * (1 + qualities.length)
|
|
80
|
-
};
|
|
81
|
-
};
|
|
82
|
-
/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */
|
|
83
|
-
const standard = space();
|
|
84
|
-
// src/asset.ts
|
|
85
|
-
const CSS_COLOR = /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z%.,\s/+-]*\))$/i;
|
|
86
|
-
const coefficientCount = (x, y) => {
|
|
87
|
-
let count = 0;
|
|
88
|
-
for (let cy = 0; cy < y; cy++) for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++;
|
|
89
|
-
return count;
|
|
90
|
-
};
|
|
91
|
-
const isThumbHash = (encoded) => {
|
|
92
|
-
try {
|
|
93
|
-
const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
|
|
94
|
-
if (bytes.length < 5) return false;
|
|
95
|
-
const hasAlpha = (bytes[2] & 128) !== 0;
|
|
96
|
-
const landscape = (bytes[4] & 128) !== 0;
|
|
97
|
-
const shorter = bytes[3] & 7;
|
|
98
|
-
if (shorter === 0) return false;
|
|
99
|
-
const long = hasAlpha ? 5 : 7;
|
|
100
|
-
const coefficients = coefficientCount(landscape ? long : shorter, landscape ? shorter : long) + coefficientCount(3, 3) * 2 + (hasAlpha ? coefficientCount(5, 5) : 0);
|
|
101
|
-
return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2);
|
|
102
|
-
} catch {
|
|
103
|
-
return false;
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
/** What stands in an image's place until it loads. */
|
|
107
|
-
const Placeholder = Schema.TaggedUnion({
|
|
108
|
-
/** A flat color, such as one taken from a logo. */
|
|
109
|
-
Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },
|
|
110
|
-
/** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */
|
|
111
|
-
ThumbHash: { hash: Schema.String.check(Schema.makeFilter((encoded) => isThumbHash(encoded) || "not a valid ThumbHash")) },
|
|
112
|
-
/** The provider's smallest width of the image itself, scaled up. */
|
|
113
|
-
LowRes: {}
|
|
114
|
-
});
|
|
115
|
-
const Pixels = Schema.Int.check(Schema.isGreaterThan(0));
|
|
116
|
-
const Share = Schema.Finite.check(Schema.isBetween({
|
|
117
|
-
minimum: 0,
|
|
118
|
-
maximum: 1
|
|
119
|
-
}));
|
|
120
|
-
/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */
|
|
121
|
-
const Focus = Schema.Struct({
|
|
122
|
-
x: Share,
|
|
123
|
-
y: Share
|
|
124
|
-
});
|
|
125
|
-
/**
|
|
126
|
-
* The facts of one original image, derived from it once and stored beside it.
|
|
127
|
-
* `key` is where the original lives, as its provider reads it. `hash` is the
|
|
128
|
-
* original's content hash, absent for an image never read; `alpha` says
|
|
129
|
-
* whether it has transparent pixels. `focus`, the one fact an editor sets
|
|
130
|
-
* rather than one derived, is where a crop keeps the subject; a stored asset
|
|
131
|
-
* without it reads as none.
|
|
132
|
-
*/
|
|
133
|
-
const ImageAsset = Schema.Struct({
|
|
134
|
-
key: Schema.String.check(Schema.isNonEmpty()),
|
|
135
|
-
width: Pixels,
|
|
136
|
-
height: Pixels,
|
|
137
|
-
alpha: Schema.Boolean,
|
|
138
|
-
hash: Schema.OptionFromNullOr(ContentHash),
|
|
139
|
-
placeholder: Schema.OptionFromNullOr(Placeholder),
|
|
140
|
-
focus: Schema.OptionFromOptionalNullOr(Focus)
|
|
141
|
-
});
|
|
142
|
-
const isHashed = (asset) => Option.isSome(asset.hash);
|
|
143
|
-
/** `ImageAsset`, refusing facts with no content hash. */
|
|
144
|
-
const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed));
|
|
145
|
-
// src/describe.ts
|
|
146
|
-
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
147
|
-
var Inspector = class extends Context.Service()("foldkit-media/Inspector") {};
|
|
148
|
-
const hex = (buffer) => Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
149
|
-
const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
|
|
150
|
-
/**
|
|
151
|
-
* An original's facts, as an `ImageAsset` under `key`: its size and alpha
|
|
152
|
-
* from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the
|
|
153
|
-
* inspector made a thumbnail. Where an original enters (an upload, a build, a
|
|
154
|
-
* page's content naming a URL), so its facts are derived once and stored.
|
|
155
|
-
*/
|
|
156
|
-
const describe = (key, bytes) => Effect.gen(function* () {
|
|
157
|
-
const inspected = yield* Inspector.use((inspector) => inspector.inspect(bytes));
|
|
158
|
-
const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", bytes));
|
|
159
|
-
return {
|
|
160
|
-
key,
|
|
161
|
-
width: inspected.width,
|
|
162
|
-
height: inspected.height,
|
|
163
|
-
alpha: inspected.alpha,
|
|
164
|
-
hash: Option.some(hex(digest)),
|
|
165
|
-
placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) => Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) })),
|
|
166
|
-
focus: Option.none()
|
|
167
|
-
};
|
|
168
|
-
});
|
|
169
|
-
export { ImageAsset as a, ContentHash as c, Spelling as d, respell as f, variant_exports as h, HashedAsset as i, PATH as l, standard as m, describe as n, Placeholder as o, revisionOf as p, Focus as r, isHashed as s, Inspector as t, Quality as u };
|
|
170
|
-
|
|
171
|
-
//# sourceMappingURL=describe-C6sWA_8p.mjs.map
|