foldkit-media 0.1.0 → 0.2.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 +95 -58
- package/client.d.ts +2 -2
- package/dist/{asset-BNQ_j5tO.d.mts → asset-Dlkss5qp.d.mts} +32 -3
- package/dist/asset-Dlkss5qp.d.mts.map +1 -0
- package/dist/browser/index.d.mts +1 -1
- package/dist/browser/index.mjs +1 -1
- package/dist/cloudflare/index.d.mts +7 -6
- package/dist/cloudflare/index.d.mts.map +1 -1
- package/dist/cloudflare/index.mjs +11 -5
- package/dist/cloudflare/index.mjs.map +1 -1
- package/dist/{describe-DdYvLhMY.d.mts → describe-CivKHl4x.d.mts} +2 -2
- package/dist/{describe-DdYvLhMY.d.mts.map → describe-CivKHl4x.d.mts.map} +1 -1
- package/dist/{describe-Cqr63Gxa.mjs → describe-h9F5stgR.mjs} +5 -2
- package/dist/describe-h9F5stgR.mjs.map +1 -0
- package/dist/index.d.mts +10 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -1
- package/dist/{provider-DztvQjOr.d.mts → provider-g0Vlvlrb.d.mts} +19 -13
- package/dist/provider-g0Vlvlrb.d.mts.map +1 -0
- package/dist/server/index.d.mts +33 -15
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +172 -2
- package/dist/server/index.mjs.map +1 -1
- package/dist/{services-Ck-7dhIP.d.mts → services-8_h0ubLB.d.mts} +2 -2
- package/dist/{services-Ck-7dhIP.d.mts.map → services-8_h0ubLB.d.mts.map} +1 -1
- package/dist/sharp/index.d.mts +2 -2
- package/dist/sharp/index.mjs +1 -1
- package/dist/{upload-C5YM5jZR.mjs → stores-BtmSl8X3.mjs} +61 -203
- package/dist/stores-BtmSl8X3.mjs.map +1 -0
- package/dist/unpic/index.d.mts +1 -1
- package/dist/{upload-C4_inwfv.d.mts → upload-kp0_oK76.d.mts} +10 -10
- package/dist/{upload-C4_inwfv.d.mts.map → upload-kp0_oK76.d.mts.map} +1 -1
- package/dist/vite/index.mjs +3 -3
- package/dist/vite/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
- package/dist/describe-Cqr63Gxa.mjs.map +0 -1
- package/dist/provider-DztvQjOr.d.mts.map +0 -1
- package/dist/upload-C5YM5jZR.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as OriginalNotFound, c as TransformFailed, o as OriginalTooLarge, s as QuotaExhausted } from "./describe-
|
|
1
|
+
import { a as OriginalNotFound, c as TransformFailed, o as OriginalTooLarge, s as QuotaExhausted } from "./describe-CivKHl4x.mjs";
|
|
2
2
|
import { n as Variant } from "./variant-BOg1M0Wj.mjs";
|
|
3
3
|
import { Context, Effect, Layer, Option } from "effect";
|
|
4
4
|
//#region src/server/services.d.ts
|
|
@@ -51,4 +51,4 @@ declare const variantsNone: Layer.Layer<Variants>;
|
|
|
51
51
|
declare const limitTransforms: (concurrency: number) => <E, R>(transformer: Layer.Layer<Transformer, E, R>) => Layer.Layer<Transformer, E, R>;
|
|
52
52
|
//#endregion
|
|
53
53
|
export { Transformer as a, variantsNone as c, Originals as i, Kept as n, Variants as o, Original as r, limitTransforms as s, Encoded as t };
|
|
54
|
-
//# sourceMappingURL=services-
|
|
54
|
+
//# sourceMappingURL=services-8_h0ubLB.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services-
|
|
1
|
+
{"version":3,"file":"services-8_h0ubLB.d.mts","names":[],"sources":["../src/server/services.ts"],"mappings":";;;;;UAWiB;WACN,MAAM,eAAe;WACrB;;;UAIM;WACN,OAAO,WAAW;WAClB;;;UAIM;WACN,SAAS;WACT;;;WAMO,MAAC,iBAAiB,OAAO,OAAO,UAAU;;;cAF/C,kBAAkB;;WAaP,YAClB,UAAU,UACV,SAAS,YACN,OAAO,OAAO,SAAS,kBAAkB,iBAAiB;;;;;;;cANtD,oBAAoB;;WAiBf,MAAC,gBAAgB,OAAO,OAAO,OAAO,OAAO;WAC7C,MAAC,aAAa,SAAS,YAAY,OAAO;;;;;;cAJ/C,iBAAiB;;cASjB,cAAc,MAAM,MAAM;;;;;;;cAW1B,kBAAe,yBAElB,GAAG,GAAC,aAAe,MAAM,MAAM,aAAa,GAAG,OAAK,MAAM,MAAM,aAAa,GAAG"}
|
package/dist/sharp/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as Inspector } from "../describe-
|
|
2
|
-
import { a as Transformer } from "../services-
|
|
1
|
+
import { n as Inspector } from "../describe-CivKHl4x.mjs";
|
|
2
|
+
import { a as Transformer } from "../services-8_h0ubLB.mjs";
|
|
3
3
|
import { Layer } from "effect";
|
|
4
4
|
//#region src/sharp/index.d.ts
|
|
5
5
|
export declare const transformerSharp: (options?: {
|
package/dist/sharp/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Inspector } from "../describe-
|
|
1
|
+
import { t as Inspector } from "../describe-h9F5stgR.mjs";
|
|
2
2
|
import { t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
|
|
3
3
|
import { i as TransformFailed, n as OriginalTooLarge } from "../errors-qETj7Pgi.mjs";
|
|
4
4
|
import { i as limitTransforms, n as Transformer } from "../services-BeakQl7F.mjs";
|
|
@@ -1,28 +1,12 @@
|
|
|
1
1
|
import { n as mimeType, t as Format } from "./format-BmfnR4jg.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { a as ImageAsset, n as describe } from "./describe-h9F5stgR.mjs";
|
|
3
3
|
import { t as nonNegativeInteger } from "./limits-B6C9OOLl.mjs";
|
|
4
4
|
import { n as OriginalTooLarge, t as OriginalNotFound } from "./errors-qETj7Pgi.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup
|
|
8
|
-
import {
|
|
5
|
+
import { r as Variants, t as Originals } from "./services-BeakQl7F.mjs";
|
|
6
|
+
import { Context, Duration, Effect, Layer, Match, Option, Schema, Stream } from "effect";
|
|
7
|
+
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
8
|
+
import { HttpServerResponse } from "effect/http";
|
|
9
9
|
import { KeyValueStore, RateLimiter } from "effect/persistence";
|
|
10
|
-
//#region src/server/api.ts
|
|
11
|
-
/**
|
|
12
|
-
* The media server's HTTP API: one route, a variant of an original named by
|
|
13
|
-
* its content hash. The route takes its params as text, and the handler
|
|
14
|
-
* decodes them with the space's Schema, the one `Provider.hosted` encodes
|
|
15
|
-
* with, so a variant outside the space is refused before any work, and that
|
|
16
|
-
* refusal, like every answer, carries the headers `headersFor` decides.
|
|
17
|
-
*/
|
|
18
|
-
const MediaApi = HttpApi.make("foldkit-media").add(HttpApiGroup.make("images").add(HttpApiEndpoint.get("variant", PATH, {
|
|
19
|
-
params: {
|
|
20
|
-
hash: Schema.String,
|
|
21
|
-
variant: Schema.String
|
|
22
|
-
},
|
|
23
|
-
success: HttpApiSchema.StreamUint8Array()
|
|
24
|
-
})));
|
|
25
|
-
//#endregion
|
|
26
10
|
//#region src/server/headers.ts
|
|
27
11
|
/** Where a variant came from: the edge's cache, the server's store, or made for this request. */
|
|
28
12
|
const From = Schema.Literals([
|
|
@@ -180,182 +164,6 @@ const admissionRateLimiter = (options) => Layer.effect(Admission, Effect.gen(fun
|
|
|
180
164
|
}))) };
|
|
181
165
|
}));
|
|
182
166
|
//#endregion
|
|
183
|
-
//#region src/server/handlers.ts
|
|
184
|
-
/** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */
|
|
185
|
-
const DEFAULT_MAX_BYTES$2 = 20971520;
|
|
186
|
-
const defaultClientOf = (request) => request.headers["cf-connecting-ip"] ?? Option.getOrElse(request.remoteAddress, () => "unknown");
|
|
187
|
-
const optionsOf = (answer) => ({
|
|
188
|
-
status: statusOf(answer),
|
|
189
|
-
headers: headersFor(answer)
|
|
190
|
-
});
|
|
191
|
-
const served = (etag, from, encoded) => HttpServerResponse.uint8Array(encoded.bytes, {
|
|
192
|
-
...optionsOf(Answer.cases.Variant.make({
|
|
193
|
-
etag,
|
|
194
|
-
from
|
|
195
|
-
})),
|
|
196
|
-
contentType: encoded.contentType
|
|
197
|
-
});
|
|
198
|
-
const notModified = (etag) => HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })));
|
|
199
|
-
const refused$1 = (answer) => HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer));
|
|
200
|
-
/**
|
|
201
|
-
* The handlers of `MediaApi`'s one route. The path is decoded against the
|
|
202
|
-
* space; a variant kept is served as kept, and one the request already holds
|
|
203
|
-
* (`If-None-Match`) is a 304 before the store is read; otherwise the original
|
|
204
|
-
* is read, transformed, kept and served. Every answer, a refusal included,
|
|
205
|
-
* goes through `headersFor`, and a failure is never the original in the
|
|
206
|
-
* variant's place.
|
|
207
|
-
*/
|
|
208
|
-
const handlers = (options = {}) => {
|
|
209
|
-
const { space = standard, maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES$2, coalesce = false, clientOf = defaultClientOf } = options;
|
|
210
|
-
const maxBytes = nonNegativeInteger("maxBytes", requestedMaxBytes);
|
|
211
|
-
const decodeHash = Schema.decodeUnknownOption(ContentHash);
|
|
212
|
-
const decodeVariant = Schema.decodeUnknownOption(space.schema);
|
|
213
|
-
const isSpelling = Schema.is(Spelling);
|
|
214
|
-
const spell = Schema.encodeSync(space.schema);
|
|
215
|
-
return HttpApiBuilder.group(MediaApi, "images", (group) => Effect.gen(function* () {
|
|
216
|
-
const originals = yield* Originals;
|
|
217
|
-
const transformer = yield* Transformer;
|
|
218
|
-
const variants = yield* Variants;
|
|
219
|
-
const admit = Option.match(yield* Effect.serviceOption(Admission), {
|
|
220
|
-
onNone: () => (_client) => Effect.void,
|
|
221
|
-
onSome: (admission) => admission.admit
|
|
222
|
-
});
|
|
223
|
-
const make = Effect.fn("Media.make")(function* (hash, variant) {
|
|
224
|
-
const original = yield* originals.get(hash);
|
|
225
|
-
if (original.size > maxBytes) return yield* new OriginalTooLarge({
|
|
226
|
-
size: original.size,
|
|
227
|
-
limit: maxBytes,
|
|
228
|
-
unit: "bytes"
|
|
229
|
-
});
|
|
230
|
-
return yield* transformer.transform(original, variant);
|
|
231
|
-
});
|
|
232
|
-
const makeAndKeep = (key, hash, variant) => make(hash, variant).pipe(Effect.tap((made) => variants.put(key, made)));
|
|
233
|
-
const shared = yield* Cache.make({
|
|
234
|
-
capacity: 1e4,
|
|
235
|
-
timeToLive: 0,
|
|
236
|
-
lookup: (key) => {
|
|
237
|
-
const at = key.indexOf("/");
|
|
238
|
-
const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1));
|
|
239
|
-
return makeAndKeep(key, key.slice(0, at), variant);
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
const serve = Effect.fn("Media.serve")(function* (hash, variant, ifNoneMatch, client) {
|
|
243
|
-
const key = `${hash}/${spell(variant)}`;
|
|
244
|
-
const etag = `"${key}"`;
|
|
245
|
-
if (matches(ifNoneMatch, etag)) return notModified(etag);
|
|
246
|
-
return yield* Option.match(yield* variants.get(key), {
|
|
247
|
-
onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),
|
|
248
|
-
onNone: () => admit(client).pipe(Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)), Effect.map((made) => served(etag, "made", made)), Effect.catchTags({
|
|
249
|
-
OriginalNotFound: () => Effect.succeed(refused$1(Answer.cases.NotFound.make({}))),
|
|
250
|
-
OriginalTooLarge: () => Effect.succeed(refused$1(Answer.cases.TooLarge.make({}))),
|
|
251
|
-
TransformFailed: () => Effect.succeed(refused$1(Answer.cases.Failed.make({}))),
|
|
252
|
-
QuotaExhausted: () => Effect.succeed(refused$1(Answer.cases.Exhausted.make({}))),
|
|
253
|
-
RateLimited: ({ retryAfterSeconds }) => Effect.succeed(refused$1(Answer.cases.RateLimited.make({ retryAfterSeconds })))
|
|
254
|
-
}))
|
|
255
|
-
});
|
|
256
|
-
});
|
|
257
|
-
/**
|
|
258
|
-
* A spelling of the grammar this space does not read. An earlier revision of a variant
|
|
259
|
-
* it makes is served while kept and else sent to its current URL; anything else (a later
|
|
260
|
-
* revision, a width another release offers) is `Unoffered`, kept briefly.
|
|
261
|
-
*/
|
|
262
|
-
const elsewhere = (hash, spelling, ifNoneMatch) => {
|
|
263
|
-
const current = respell(spelling, space.revision);
|
|
264
|
-
if (revisionOf(spelling) >= space.revision || Option.isNone(decodeVariant(current))) return Effect.succeed(refused$1(Answer.cases.Unoffered.make({})));
|
|
265
|
-
const key = `${hash}/${spelling}`;
|
|
266
|
-
const etag = `"${key}"`;
|
|
267
|
-
if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag));
|
|
268
|
-
return Effect.map(variants.get(key), (kept) => Option.match(kept, {
|
|
269
|
-
onSome: ({ encoded, from }) => served(etag, from, encoded),
|
|
270
|
-
onNone: () => refused$1(Answer.cases.Moved.make({ location: PATH.replace(":hash", hash).replace(":variant", current) }))
|
|
271
|
-
}));
|
|
272
|
-
};
|
|
273
|
-
return group.handle("variant", ({ params, request }) => Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {
|
|
274
|
-
onNone: () => Option.match(decodeHash(params.hash), {
|
|
275
|
-
onNone: () => Effect.succeed(refused$1(Answer.cases.Malformed.make({}))),
|
|
276
|
-
onSome: (hash) => isSpelling(params.variant) ? elsewhere(hash, params.variant, request.headers["if-none-match"]) : Effect.succeed(refused$1(Answer.cases.Malformed.make({})))
|
|
277
|
-
}),
|
|
278
|
-
onSome: ([hash, variant]) => serve(hash, variant, request.headers["if-none-match"], clientOf(request))
|
|
279
|
-
}));
|
|
280
|
-
}));
|
|
281
|
-
};
|
|
282
|
-
/**
|
|
283
|
-
* The media server as an Effect HTTP application: its route registered with
|
|
284
|
-
* the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
|
|
285
|
-
*/
|
|
286
|
-
const layer = (options = {}) => HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({
|
|
287
|
-
coalesce: true,
|
|
288
|
-
...options
|
|
289
|
-
})));
|
|
290
|
-
/**
|
|
291
|
-
* A Worker's fetch handler over `app`, built from each environment's bindings
|
|
292
|
-
* once and kept, since a Worker hands every request the same bindings. A
|
|
293
|
-
* layer that fails to build answers a 500.
|
|
294
|
-
*/
|
|
295
|
-
const fetchOf = (app) => {
|
|
296
|
-
const built = /* @__PURE__ */ new WeakMap();
|
|
297
|
-
return (request, env) => {
|
|
298
|
-
const known = built.get(env);
|
|
299
|
-
if (known !== void 0) return known(request);
|
|
300
|
-
const { handler } = HttpRouter.toWebHandler(app(env).pipe(Layer.provide(HttpServer.layerServices)), { disableLogger: true });
|
|
301
|
-
const answer = (incoming) => handler(incoming);
|
|
302
|
-
built.set(env, answer);
|
|
303
|
-
return answer(request);
|
|
304
|
-
};
|
|
305
|
-
};
|
|
306
|
-
/**
|
|
307
|
-
* The media server as a Worker's fetch handler, its services from each
|
|
308
|
-
* environment's bindings. It answers its own route and 404s anything else, so
|
|
309
|
-
* route to it by path (`/_image/`).
|
|
310
|
-
*/
|
|
311
|
-
const serveFetch = (options) => fetchOf((env) => layer({
|
|
312
|
-
coalesce: false,
|
|
313
|
-
...options
|
|
314
|
-
}).pipe(Layer.provide(options.layer(env))));
|
|
315
|
-
//#endregion
|
|
316
|
-
//#region src/server/stores.ts
|
|
317
|
-
const mediaTypeOf = (key) => {
|
|
318
|
-
const extension = key.slice(key.lastIndexOf(".") + 1);
|
|
319
|
-
return Schema.is(Format)(extension) ? mimeType(extension) : "application/octet-stream";
|
|
320
|
-
};
|
|
321
|
-
/**
|
|
322
|
-
* `Variants` over a `KeyValueStore`. A variant's bytes are its value and its
|
|
323
|
-
* media type is its key's extension, so nothing else is stored. A store that
|
|
324
|
-
* fails is logged and read as a miss, or a write it drops: a variant is a
|
|
325
|
-
* cache, and the request is answered either way.
|
|
326
|
-
*/
|
|
327
|
-
const makeVariants = (store) => ({
|
|
328
|
-
get: (key) => store.getUint8Array(key).pipe(Effect.map((bytes) => Option.map(Option.fromNullishOr(bytes), (value) => ({
|
|
329
|
-
encoded: {
|
|
330
|
-
bytes: new Uint8Array(value),
|
|
331
|
-
contentType: mediaTypeOf(key)
|
|
332
|
-
},
|
|
333
|
-
from: "store"
|
|
334
|
-
}))), Effect.catch((error) => Effect.logWarning("Media: the variant store failed a read", error).pipe(Effect.as(Option.none())))),
|
|
335
|
-
put: (key, encoded) => store.set(key, encoded.bytes).pipe(Effect.catch((error) => Effect.logWarning("Media: the variant store failed a write", error)))
|
|
336
|
-
});
|
|
337
|
-
/**
|
|
338
|
-
* Variants kept in the application's `KeyValueStore`, under `prefix`:
|
|
339
|
-
* `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,
|
|
340
|
-
* `layerSql` over SQLite or D1.
|
|
341
|
-
*/
|
|
342
|
-
const variantsKeyValueStore = (options = {}) => Layer.effect(Variants, Effect.gen(function* () {
|
|
343
|
-
const store = yield* KeyValueStore.KeyValueStore;
|
|
344
|
-
return makeVariants(KeyValueStore.prefix(store, options.prefix ?? "variants/"));
|
|
345
|
-
}));
|
|
346
|
-
/**
|
|
347
|
-
* Originals in the application's `KeyValueStore`, each under its content
|
|
348
|
-
* hash after `prefix`. A store that fails is a defect, not a missing
|
|
349
|
-
* original: the original is the data, and a 404 would say it is gone.
|
|
350
|
-
*/
|
|
351
|
-
const originalsKeyValueStore = (options = {}) => Layer.effect(Originals, Effect.gen(function* () {
|
|
352
|
-
const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? "");
|
|
353
|
-
return { get: (hash) => store.getUint8Array(hash).pipe(Effect.orDie, Effect.flatMap((bytes) => bytes === void 0 ? Effect.fail(new OriginalNotFound({ hash })) : Effect.succeed({
|
|
354
|
-
body: new Blob([new Uint8Array(bytes)]).stream(),
|
|
355
|
-
size: bytes.byteLength
|
|
356
|
-
}))) };
|
|
357
|
-
}));
|
|
358
|
-
//#endregion
|
|
359
167
|
//#region src/server/facts.ts
|
|
360
168
|
/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */
|
|
361
169
|
var FactsUnavailable = class extends Schema.TaggedError()("FactsUnavailable", {
|
|
@@ -569,12 +377,19 @@ const uploadHandlers = (options = {}) => {
|
|
|
569
377
|
* `Inspector` and the `UploadPolicy`.
|
|
570
378
|
*/
|
|
571
379
|
const uploadLayer = (options = {}) => HttpApiBuilder.layer(UploadApi).pipe(Layer.provide(uploadHandlers(options)));
|
|
380
|
+
const digestOf = (text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => new Uint8Array(digest)));
|
|
572
381
|
/**
|
|
573
|
-
*
|
|
574
|
-
*
|
|
575
|
-
*
|
|
382
|
+
* Admits a request whose `Authorization` is `Bearer <token>`, and with no
|
|
383
|
+
* token (unset or empty) admits nobody, whatever it sends. The two are
|
|
384
|
+
* compared by digest, every byte, so the time taken says nothing of the
|
|
385
|
+
* token. For a deployment's secret (`wrangler secret put`); who may upload
|
|
386
|
+
* by session is the application's own `UploadPolicy`.
|
|
576
387
|
*/
|
|
577
|
-
const
|
|
388
|
+
const uploadPolicyBearer = (token) => Layer.succeed(UploadPolicy, { admit: (request) => Effect.all([digestOf(request.headers["authorization"] ?? ""), digestOf(`Bearer ${token}`)]).pipe(Effect.flatMap(([given, expected]) => {
|
|
389
|
+
let difference = token === void 0 || token === "" ? 1 : 0;
|
|
390
|
+
for (let at = 0; at < expected.length; at++) difference |= given[at] ^ expected[at];
|
|
391
|
+
return difference === 0 ? Effect.void : Effect.fail(new UploadForbidden({}));
|
|
392
|
+
})) });
|
|
578
393
|
/**
|
|
579
394
|
* Uploads kept in the application's `KeyValueStore`, each under its content
|
|
580
395
|
* hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the
|
|
@@ -585,6 +400,49 @@ const uploadsKeyValueStore = (options = {}) => Layer.effect(Uploads, Effect.gen(
|
|
|
585
400
|
return { put: (hash, bytes) => store.set(hash, bytes).pipe(Effect.orDie) };
|
|
586
401
|
}));
|
|
587
402
|
//#endregion
|
|
588
|
-
|
|
403
|
+
//#region src/server/stores.ts
|
|
404
|
+
const mediaTypeOf = (key) => {
|
|
405
|
+
const extension = key.slice(key.lastIndexOf(".") + 1);
|
|
406
|
+
return Schema.is(Format)(extension) ? mimeType(extension) : "application/octet-stream";
|
|
407
|
+
};
|
|
408
|
+
/**
|
|
409
|
+
* `Variants` over a `KeyValueStore`. A variant's bytes are its value and its
|
|
410
|
+
* media type is its key's extension, so nothing else is stored. A store that
|
|
411
|
+
* fails is logged and read as a miss, or a write it drops: a variant is a
|
|
412
|
+
* cache, and the request is answered either way.
|
|
413
|
+
*/
|
|
414
|
+
const makeVariants = (store) => ({
|
|
415
|
+
get: (key) => store.getUint8Array(key).pipe(Effect.map((bytes) => Option.map(Option.fromNullishOr(bytes), (value) => ({
|
|
416
|
+
encoded: {
|
|
417
|
+
bytes: new Uint8Array(value),
|
|
418
|
+
contentType: mediaTypeOf(key)
|
|
419
|
+
},
|
|
420
|
+
from: "store"
|
|
421
|
+
}))), Effect.catch((error) => Effect.logWarning("Media: the variant store failed a read", error).pipe(Effect.as(Option.none())))),
|
|
422
|
+
put: (key, encoded) => store.set(key, encoded.bytes).pipe(Effect.catch((error) => Effect.logWarning("Media: the variant store failed a write", error)))
|
|
423
|
+
});
|
|
424
|
+
/**
|
|
425
|
+
* Variants kept in the application's `KeyValueStore`, under `prefix`:
|
|
426
|
+
* `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,
|
|
427
|
+
* `layerSql` over SQLite or D1.
|
|
428
|
+
*/
|
|
429
|
+
const variantsKeyValueStore = (options = {}) => Layer.effect(Variants, Effect.gen(function* () {
|
|
430
|
+
const store = yield* KeyValueStore.KeyValueStore;
|
|
431
|
+
return makeVariants(KeyValueStore.prefix(store, options.prefix ?? "variants/"));
|
|
432
|
+
}));
|
|
433
|
+
/**
|
|
434
|
+
* Originals in the application's `KeyValueStore`, each under its content
|
|
435
|
+
* hash after `prefix`. A store that fails is a defect, not a missing
|
|
436
|
+
* original: the original is the data, and a 404 would say it is gone.
|
|
437
|
+
*/
|
|
438
|
+
const originalsKeyValueStore = (options = {}) => Layer.effect(Originals, Effect.gen(function* () {
|
|
439
|
+
const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? "");
|
|
440
|
+
return { get: (hash) => store.getUint8Array(hash).pipe(Effect.orDie, Effect.flatMap((bytes) => bytes === void 0 ? Effect.fail(new OriginalNotFound({ hash })) : Effect.succeed({
|
|
441
|
+
body: new Blob([new Uint8Array(bytes)]).stream(),
|
|
442
|
+
size: bytes.byteLength
|
|
443
|
+
}))) };
|
|
444
|
+
}));
|
|
445
|
+
//#endregion
|
|
446
|
+
export { Answer as _, UploadForbidden as a, statusOf as b, uploadHandlers as c, uploadsKeyValueStore as d, FactsUnavailable as f, admissionRateLimiter as g, RateLimited as h, UploadApi as i, uploadLayer as l, Admission as m, originalsKeyValueStore as n, UploadPolicy as o, factsOf as p, variantsKeyValueStore as r, Uploads as s, makeVariants as t, uploadPolicyBearer as u, headersFor as v, matches as y };
|
|
589
447
|
|
|
590
|
-
//# sourceMappingURL=
|
|
448
|
+
//# sourceMappingURL=stores-BtmSl8X3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores-BtmSl8X3.mjs","names":["DEFAULT_MAX_BYTES"],"sources":["../src/server/headers.ts","../src/server/admission.ts","../src/server/facts.ts","../src/server/upload.ts","../src/server/stores.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Where a variant came from: the edge's cache, the server's store, or made for this request. */\nexport const From = Schema.Literals(['edge', 'store', 'made'])\nexport type From = typeof From.Type\n\n/** Every answer the media server gives, and nothing else: each has its status and its headers. */\nexport const Answer = Schema.TaggedUnion({\n /** A variant's bytes. */\n Variant: { etag: Schema.String, from: From },\n /** The variant the request's `If-None-Match` already holds. */\n NotModified: { etag: Schema.String },\n /**\n * No URL of this server's grammar. A later release may read it (a new format\n * or parameter, in a rollout), so it is kept as briefly as `NotFound`.\n */\n Malformed: {},\n /** No original under the hash: an upload may yet put one there. */\n NotFound: {},\n /**\n * A spelling of the grammar outside this space: another release (the next\n * one, in a rollout) may offer it, so it is kept as briefly as `NotFound`.\n */\n Unoffered: {},\n /**\n * A variant of an earlier revision, made no longer and not kept: its URL now names the\n * current revision's, at `location`. A 302 kept briefly, since a rollback to that revision,\n * or a server of it still in the rollout, answers the old URL again.\n */\n Moved: { location: Schema.String },\n /** The original is larger than the server reads: a server configured to read more may. */\n TooLarge: {},\n /** The transformer failed: perhaps not for good. */\n Failed: {},\n /** The client has had too many variants made lately. */\n RateLimited: { retryAfterSeconds: Schema.Number },\n /** The host's allowance is spent. */\n Exhausted: {},\n /** An upload kept; its facts are the body. */\n Uploaded: {},\n /** The upload policy refused the request. */\n Forbidden: {},\n /** An upload that is not an image the server reads. */\n Unsupported: {},\n /** The facts of an image named by URL; the facts are the body. */\n Described: {},\n /** No facts could be read for that URL: a host not allowed, a read that failed, no image. */\n Unavailable: {},\n})\nexport type Answer = typeof Answer.Type\n\nconst YEAR = 'public, max-age=31536000, immutable'\n\n// What may yet be answered: the browser keeps nothing, and the edge a minute, to blunt a crawler.\nconst BRIEFLY: Readonly<Record<string, string>> = {\n 'cache-control': 'no-store',\n 'cdn-cache-control': 'public, max-age=60',\n}\n\n// Retry a spent allowance after an hour: the host's window is not known here.\nconst EXHAUSTED_RETRY_SECONDS = '3600'\n\n/** The status of each answer. */\nexport const statusOf: (answer: Answer) => number = Answer.match({\n Variant: () => 200,\n NotModified: () => 304,\n Malformed: () => 400,\n NotFound: () => 404,\n Unoffered: () => 404,\n Moved: () => 302,\n TooLarge: () => 413,\n Failed: () => 502,\n RateLimited: () => 429,\n Exhausted: () => 503,\n Uploaded: () => 201,\n Forbidden: () => 403,\n Unsupported: () => 415,\n Described: () => 200,\n Unavailable: () => 422,\n})\n\n/**\n * Every response's headers, decided in one place, so the server, the edge\n * and a static host cannot disagree. A variant's URL names its bytes, so it\n * is kept for a year. A refusal of a variant is not: another release, or the\n * same one configured otherwise, may answer it, so only a CDN keeps it,\n * briefly; a failure is never kept. Every image may be read by a canvas on\n * another origin, and its type is never sniffed.\n */\nexport const headersFor = (answer: Answer): Readonly<Record<string, string>> => ({\n 'x-content-type-options': 'nosniff',\n 'access-control-allow-origin': '*',\n 'cross-origin-resource-policy': 'cross-origin',\n 'timing-allow-origin': '*',\n ...Answer.match(answer, {\n Variant: ({ etag, from }): Record<string, string> => ({\n 'cache-control': YEAR,\n etag,\n 'server-timing': `media;desc=\"${from}\"`,\n }),\n NotModified: ({ etag }): Record<string, string> => ({ 'cache-control': YEAR, etag }),\n Malformed: (): Record<string, string> => BRIEFLY,\n NotFound: (): Record<string, string> => BRIEFLY,\n Unoffered: (): Record<string, string> => BRIEFLY,\n Moved: ({ location }): Record<string, string> => ({ ...BRIEFLY, location }),\n TooLarge: (): Record<string, string> => BRIEFLY,\n Failed: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n RateLimited: ({ retryAfterSeconds }): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': String(retryAfterSeconds),\n }),\n Exhausted: (): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': EXHAUSTED_RETRY_SECONDS,\n }),\n // An upload's answers are about one request, and are never kept.\n Uploaded: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Forbidden: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unsupported: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Described: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unavailable: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n }),\n})\n\n/** Whether an `If-None-Match` names `etag` (weakly, as a GET compares, or `*`). */\nexport const matches = (ifNoneMatch: string | undefined, etag: string): boolean =>\n ifNoneMatch !== undefined &&\n ifNoneMatch\n .split(',')\n .map(tag => tag.trim().replace(/^W\\//, ''))\n .some(tag => tag === '*' || tag === etag)\n","import { Context, Duration, Effect, Layer, Match, Schema } from 'effect'\nimport { RateLimiter } from 'effect/persistence'\n\n/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */\nexport class RateLimited extends Schema.TaggedError<RateLimited>()(\n 'RateLimited',\n { retryAfterSeconds: Schema.Number },\n { httpApiStatus: 429 },\n) {}\n\n/**\n * Whether a client may have a variant made now. Asked only on a miss, after\n * the store and before the original is read: a variant already made costs a\n * read, and only making one costs work. Optional: without it, every miss is\n * admitted.\n */\nexport class Admission extends Context.Service<\n Admission,\n { readonly admit: (client: string) => Effect.Effect<void, RateLimited> }\n>()('foldkit-media/Admission') {}\n\n/**\n * Admission through Effect's `RateLimiter`, `limit` misses a client per\n * `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one\n * process, Redis for several). A store that fails admits the request, logged:\n * a limiter that is down should not take the images down with it.\n */\nexport const admissionRateLimiter = (options: {\n readonly limit: number\n readonly window: Duration.Input\n readonly algorithm?: 'fixed-window' | 'token-bucket'\n}): Layer.Layer<Admission, never, RateLimiter.RateLimiter> =>\n Layer.effect(\n Admission,\n Effect.gen(function* () {\n const limiter = yield* RateLimiter.RateLimiter\n return {\n admit: (client: string) =>\n limiter\n .consume({\n key: `foldkit-media:${client}`,\n limit: options.limit,\n window: options.window,\n algorithm: options.algorithm ?? 'token-bucket',\n onExceeded: 'fail',\n })\n .pipe(\n Effect.asVoid,\n Effect.catch(error =>\n Match.valueTags(error.reason, {\n RateLimitExceeded: ({ retryAfter }) =>\n Effect.fail(\n new RateLimited({\n retryAfterSeconds: Math.max(1, Math.ceil(Duration.toSeconds(retryAfter))),\n }),\n ),\n RateLimitStoreError: () =>\n Effect.logWarning('Media: the rate limiter failed; admitting', error),\n }),\n ),\n ),\n }\n }),\n )\n","import { Effect, Option, Schema } from 'effect'\nimport type { KeyValueStore } from 'effect/persistence'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\n\n/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */\nexport class FactsUnavailable extends Schema.TaggedError<FactsUnavailable>()('FactsUnavailable', {\n url: Schema.String,\n reason: Schema.String,\n}) {}\n\nconst Cached = Schema.Struct({\n target: Schema.String,\n etag: Schema.OptionFromNullOr(Schema.String),\n asset: ImageAsset,\n})\nconst CachedJson = Schema.fromJsonString(Cached)\n\n// A redirect chain longer than this is refused, not followed.\nconst MAX_REDIRECTS = 3\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface FactsOptions {\n /** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */\n readonly allow: ReadonlyArray<string>\n /** The largest original read, in bytes, counted as it streams. */\n readonly maxBytes?: number\n /** Facts kept by URL and revalidated with the original's `ETag`. */\n readonly cache?: KeyValueStore.KeyValueStore\n /** How to fetch; the platform's `fetch` by default. */\n readonly fetch?: (request: Request) => Promise<Response>\n}\n\n/**\n * The facts of an image a page names only by URL (a rich-text image, a CMS\n * block), so it is drawn with its box and placeholder like any other: its\n * original read from an allowed host and described (`describe`), with the\n * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every\n * redirect is checked again, so content cannot point the build at an\n * internal address. Kept in `cache`, an unchanged original is asked for\n * with its `ETag` and not read or inspected again.\n */\nexport const factsOf = (\n url: string,\n options: FactsOptions,\n): Effect.Effect<ImageAsset, FactsUnavailable, Inspector> => {\n const unavailable = (reason: string) => new FactsUnavailable({ url, reason })\n const fetchOne = options.fetch ?? ((request: Request) => fetch(request))\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n // An allowed host on its own port alone: another port of it is another service.\n const allowed = (target: URL) =>\n target.protocol === 'https:' && target.port === '' && options.allow.includes(target.hostname)\n const cacheKey = `facts/${url}`\n\n const readCached = Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => Effect.succeed(Option.none<typeof Cached.Type>()),\n onSome: store =>\n store.get(cacheKey).pipe(\n Effect.map(text =>\n Option.flatMap(Option.fromNullishOr(text), Schema.decodeUnknownOption(CachedJson)),\n ),\n Effect.catch(() => Effect.succeed(Option.none<typeof Cached.Type>())),\n ),\n })\n\n const request = (cached: Option.Option<typeof Cached.Type>) =>\n Effect.tryPromise({\n try: async () => {\n let target = new URL(url)\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n if (!allowed(target))\n return { refused: `${target.origin} is not an allowed host` } as const\n const etag = Option.flatMap(cached, entry =>\n entry.target === target.href ? entry.etag : Option.none(),\n )\n const headers = Option.match(etag, {\n onNone: () => ({}),\n onSome: tag => ({ 'if-none-match': tag }),\n })\n const response = await fetchOne(new Request(target, { headers, redirect: 'manual' }))\n const location = response.headers.get('location')\n if (\n response.status < 300 ||\n response.status >= 400 ||\n response.status === 304 ||\n location === null\n ) {\n return { response, target: target.href } as const\n }\n target = new URL(location, target)\n }\n return { refused: `more than ${MAX_REDIRECTS} redirects` } as const\n },\n catch: cause => unavailable(`the fetch failed: ${String(cause)}`),\n })\n\n // Counted as it streams: a missing or false Content-Length does not let a larger body through.\n const bytesOf = (response: Response) =>\n Effect.tryPromise({\n try: async () => {\n const chunks: Array<Uint8Array> = []\n let size = 0\n const reader = response.body?.getReader()\n for (\n let read = await reader?.read();\n read !== undefined && !read.done;\n read = await reader?.read()\n ) {\n size += read.value.byteLength\n if (size > maxBytes) {\n await reader?.cancel()\n return undefined\n }\n chunks.push(read.value)\n }\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n },\n catch: cause => unavailable(`the body could not be read: ${String(cause)}`),\n })\n\n return Effect.gen(function* () {\n const cached = yield* readCached\n const answer = yield* request(cached)\n if ('refused' in answer) return yield* unavailable(answer.refused)\n const { response, target } = answer\n const unchanged = Option.filter(cached, entry => entry.target === target)\n if (response.status === 304 && Option.isSome(unchanged)) return unchanged.value.asset\n if (response.status !== 200)\n return yield* unavailable(`the original answered ${response.status}`)\n const bytes = yield* bytesOf(response)\n if (bytes === undefined)\n return yield* unavailable(`the original is larger than ${maxBytes} bytes`)\n const asset = yield* describe(url, bytes).pipe(\n Effect.mapError(error => unavailable(`the original could not be inspected: ${error._tag}`)),\n )\n const store = options.cache\n if (store !== undefined) {\n const entry = Schema.encodeSync(CachedJson)({\n target,\n etag: Option.fromNullishOr(response.headers.get('etag')),\n asset,\n })\n yield* store.set(cacheKey, entry).pipe(Effect.ignore)\n }\n return asset\n })\n}\n","/**\n * Where an original enters: `POST /_media/upload` takes an image's bytes,\n * reads its facts (`describe`, through the `Inspector`), keeps the bytes\n * under their content hash (`Uploads`), and answers the facts as an\n * `ImageAsset`, for whoever registers them (a CMS's asset row). The bytes\n * travel once, over HTTP; only the facts go on to the application's data.\n */\nimport { Context, Effect, Layer, Option, Schema, Stream } from 'effect'\nimport { HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from 'effect/http-api'\nimport { KeyValueStore } from 'effect/persistence'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { factsOf, type FactsOptions } from './facts.js'\nimport { Answer, headersFor, statusOf } from './headers.js'\n\n/**\n * Where an original's facts enter, apart from `MediaApi`, so the variant server needs none of\n * its services: an upload, and the facts of an image named by URL.\n */\nexport const UploadApi = HttpApi.make('foldkit-media-upload').add(\n HttpApiGroup.make('uploads').add(\n HttpApiEndpoint.post('upload', '/_media/upload'),\n HttpApiEndpoint.get('facts', '/_media/facts'),\n ),\n)\n\n/** Keeps an uploaded original under its content hash: the one writer of what `Originals` reads. */\nexport class Uploads extends Context.Service<\n Uploads,\n { readonly put: (hash: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<void> }\n>()('foldkit-media/Uploads') {}\n\n/** The request may not upload. Why stays with the policy: the answer says only no. */\nexport class UploadForbidden extends Schema.TaggedError<UploadForbidden>()(\n 'UploadForbidden',\n {},\n { httpApiStatus: 403 },\n) {}\n\n/**\n * Who may upload, asked of every request before its body is read. The route\n * has no default: an application that serves uploads says who may (a\n * `foldkit-guard` policy over the session, an API key), so a server is never\n * open to every upload by omission.\n */\nexport class UploadPolicy extends Context.Service<\n UploadPolicy,\n {\n readonly admit: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<void, UploadForbidden>\n }\n>()('foldkit-media/UploadPolicy') {}\n\n/** The Cloudflare Images binding reads at most 20 MB; so does the variant server by default. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface UploadOptions {\n /** The largest upload read, in bytes; a larger one is a 413, read no further. */\n readonly maxBytes?: number\n /**\n * How `GET /_media/facts?url=` reads an image named by URL (`factsOf`): the hosts it may\n * fetch from, and a cache. No hosts unless given, so a server names every host it reads.\n */\n readonly facts?: Omit<FactsOptions, 'allow'> & { readonly allow?: ReadonlyArray<string> }\n}\n\nconst answered = (answer: Answer, body: unknown) =>\n HttpServerResponse.jsonUnsafe(body, { status: statusOf(answer), headers: headersFor(answer) })\n\nconst refused = (answer: Answer) => answered(answer, { error: answer._tag })\n\n/** The body, refused past `maxBytes` as it streams: a declared length is the client's to write, so it is not read. */\nconst bodyOf = (request: HttpServerRequest.HttpServerRequest, maxBytes: number) =>\n Effect.gen(function* () {\n const chunks: Array<Uint8Array> = []\n let size = 0\n yield* request.stream.pipe(\n Stream.runForEach(chunk =>\n Effect.suspend(() => {\n size += chunk.byteLength\n if (size > maxBytes) {\n return Effect.fail(new OriginalTooLarge({ size, limit: maxBytes, unit: 'bytes' }))\n }\n chunks.push(chunk)\n return Effect.void\n }),\n ),\n )\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n })\n\n/**\n * The upload route's handler. It asks the `UploadPolicy` first; takes only\n * an `image/*` body, which a browser cannot send to another origin without a\n * preflight this route never answers, so a cookie alone cannot upload from\n * another site; reads at most `maxBytes`; and refuses what the `Inspector`\n * cannot read as an image (415). Its answer is the facts, with the hash as\n * the key, `201`.\n */\nexport const uploadHandlers = (options: UploadOptions = {}) => {\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n const encode = Schema.encodeSync(ImageAsset)\n return HttpApiBuilder.group(UploadApi, 'uploads', group =>\n Effect.gen(function* () {\n const uploads = yield* Uploads\n const policy = yield* UploadPolicy\n const services = yield* Effect.context<Inspector>()\n const facts = { ...options.facts, allow: options.facts?.allow ?? [] }\n return group\n .handle('upload', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request)\n if (!(request.headers['content-type'] ?? '').startsWith('image/')) {\n return refused(Answer.cases.Unsupported.make({}))\n }\n const bytes = yield* bodyOf(request, maxBytes)\n const described = yield* describe('upload', bytes)\n const hash = Option.getOrThrow(described.hash)\n yield* uploads.put(hash, bytes)\n return answered(Answer.cases.Uploaded.make({}), encode({ ...described, key: hash }))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Unsupported.make({}))),\n // The body broke off or could not be read: the request's fault, not the server's.\n HttpServerError: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n Effect.withSpan('Media.upload'),\n ),\n )\n .handle('facts', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request)\n const url = new URL(request.url, 'http://media.invalid').searchParams.get('url')\n if (url === null) return refused(Answer.cases.Malformed.make({}))\n return answered(Answer.cases.Described.make({}), encode(yield* factsOf(url, facts)))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n // Why stays in the server: a host refused, a read failed, a file that is no image.\n FactsUnavailable: () => Effect.succeed(refused(Answer.cases.Unavailable.make({}))),\n }),\n Effect.withSpan('Media.facts'),\n ),\n )\n }),\n )\n}\n\n/**\n * The upload route as an Effect HTTP application, registered with the\n * `HttpRouter` beside the variant server's, needing `Uploads`, an\n * `Inspector` and the `UploadPolicy`.\n */\nexport const uploadLayer = (options: UploadOptions = {}) =>\n HttpApiBuilder.layer(UploadApi).pipe(Layer.provide(uploadHandlers(options)))\n\nconst digestOf = (text: string) =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => new Uint8Array(digest)),\n )\n\n/**\n * Admits a request whose `Authorization` is `Bearer <token>`, and with no\n * token (unset or empty) admits nobody, whatever it sends. The two are\n * compared by digest, every byte, so the time taken says nothing of the\n * token. For a deployment's secret (`wrangler secret put`); who may upload\n * by session is the application's own `UploadPolicy`.\n */\nexport const uploadPolicyBearer = (token: string | undefined): Layer.Layer<UploadPolicy> =>\n Layer.succeed(UploadPolicy, {\n admit: request =>\n Effect.all([\n digestOf(request.headers['authorization'] ?? ''),\n digestOf(`Bearer ${token}`),\n ]).pipe(\n Effect.flatMap(([given, expected]) => {\n let difference = token === undefined || token === '' ? 1 : 0\n for (let at = 0; at < expected.length; at++) difference |= given[at]! ^ expected[at]!\n return difference === 0 ? Effect.void : Effect.fail(new UploadForbidden({}))\n }),\n ),\n })\n\n/**\n * Uploads kept in the application's `KeyValueStore`, each under its content\n * hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the\n * same `prefix`. A store that fails is a defect: an upload it dropped is lost.\n */\nexport const uploadsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Uploads,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n put: (hash: string, bytes: Uint8Array<ArrayBuffer>) =>\n store.set(hash, bytes).pipe(Effect.orDie),\n }\n }),\n )\n","import { Effect, Layer, Option, Schema } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Format, mimeType } from '../format.js'\nimport { OriginalNotFound } from './errors.js'\nimport { Originals, Variants } from './services.js'\n\n// A key ends in its variant's spelling (`<hash>/w640.avif`), which names the format.\nconst mediaTypeOf = (key: string): string => {\n const extension = key.slice(key.lastIndexOf('.') + 1)\n return Schema.is(Format)(extension) ? mimeType(extension) : 'application/octet-stream'\n}\n\n/**\n * `Variants` over a `KeyValueStore`. A variant's bytes are its value and its\n * media type is its key's extension, so nothing else is stored. A store that\n * fails is logged and read as a miss, or a write it drops: a variant is a\n * cache, and the request is answered either way.\n */\nexport const makeVariants = (store: KeyValueStore.KeyValueStore): Variants['Service'] => ({\n get: key =>\n store.getUint8Array(key).pipe(\n Effect.map(bytes =>\n Option.map(Option.fromNullishOr(bytes), value => ({\n encoded: { bytes: new Uint8Array(value), contentType: mediaTypeOf(key) },\n from: 'store' as const,\n })),\n ),\n Effect.catch(error =>\n Effect.logWarning('Media: the variant store failed a read', error).pipe(\n Effect.as(Option.none()),\n ),\n ),\n ),\n put: (key, encoded) =>\n store\n .set(key, encoded.bytes)\n .pipe(\n Effect.catch(error => Effect.logWarning('Media: the variant store failed a write', error)),\n ),\n})\n\n/**\n * Variants kept in the application's `KeyValueStore`, under `prefix`:\n * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,\n * `layerSql` over SQLite or D1.\n */\nexport const variantsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Variants, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Variants,\n Effect.gen(function* () {\n const store = yield* KeyValueStore.KeyValueStore\n return makeVariants(KeyValueStore.prefix(store, options.prefix ?? 'variants/'))\n }),\n )\n\n/**\n * Originals in the application's `KeyValueStore`, each under its content\n * hash after `prefix`. A store that fails is a defect, not a missing\n * original: the original is the data, and a 404 would say it is gone.\n */\nexport const originalsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Originals, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Originals,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n get: (hash: string) =>\n store.getUint8Array(hash).pipe(\n Effect.orDie,\n Effect.flatMap(bytes =>\n bytes === undefined\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n body: new Blob([new Uint8Array(bytes)]).stream(),\n size: bytes.byteLength,\n }),\n ),\n ),\n }\n }),\n )\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAS;AAAM,CAAC;;AAI7D,MAAa,SAAS,OAAO,YAAY;;CAEvC,SAAS;EAAE,MAAM,OAAO;EAAQ,MAAM;CAAK;;CAE3C,aAAa,EAAE,MAAM,OAAO,OAAO;;;;;CAKnC,WAAW,CAAC;;CAEZ,UAAU,CAAC;;;;;CAKX,WAAW,CAAC;;;;;;CAMZ,OAAO,EAAE,UAAU,OAAO,OAAO;;CAEjC,UAAU,CAAC;;CAEX,QAAQ,CAAC;;CAET,aAAa,EAAE,mBAAmB,OAAO,OAAO;;CAEhD,WAAW,CAAC;;CAEZ,UAAU,CAAC;;CAEX,WAAW,CAAC;;CAEZ,aAAa,CAAC;;CAEd,WAAW,CAAC;;CAEZ,aAAa,CAAC;AAChB,CAAC;AAGD,MAAM,OAAO;AAGb,MAAM,UAA4C;CAChD,iBAAiB;CACjB,qBAAqB;AACvB;AAGA,MAAM,0BAA0B;;AAGhC,MAAa,WAAuC,OAAO,MAAM;CAC/D,eAAe;CACf,mBAAmB;CACnB,iBAAiB;CACjB,gBAAgB;CAChB,iBAAiB;CACjB,aAAa;CACb,gBAAgB;CAChB,cAAc;CACd,mBAAmB;CACnB,iBAAiB;CACjB,g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Aa,yBACX,UAAwC,CAAC,MAEzC,MAAM,OACJ,UACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,cAAc;CACnC,OAAO,aAAa,cAAc,OAAO,OAAO,QAAQ,UAAU,WAAW,CAAC;AAChF,CAAC,CACH;;;;;;AAOF,MAAa,0BACX,UAAwC,CAAC,MAEzC,MAAM,OACJ,WACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,cAAc,OAAO,OAAO,cAAc,eAAe,QAAQ,UAAU,EAAE;CAC3F,OAAO,EACL,MAAM,SACJ,MAAM,cAAc,IAAI,CAAC,CAAC,KACxB,OAAO,OACP,OAAO,SAAQ,UACb,UAAU,KAAA,IACN,OAAO,KAAK,IAAI,iBAAiB,EAAE,KAAK,CAAC,CAAC,IAC1C,OAAO,QAAQ;EACb,MAAM,IAAI,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO;EAC/C,MAAM,MAAM;CACd,CAAC,CACP,CACF,EACJ;AACF,CAAC,CACH"}
|
package/dist/unpic/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as Format, r as Encoding, t as Widths } from "../widths-Cg7-x89y.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { n as Provider } from "../provider-g0Vlvlrb.mjs";
|
|
3
3
|
import { Option } from "effect";
|
|
4
4
|
//#region src/unpic/index.d.ts
|
|
5
5
|
export interface DetectOptions {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as Inspector } from "./describe-
|
|
1
|
+
import { r as ImageAsset } from "./asset-Dlkss5qp.mjs";
|
|
2
|
+
import { n as Inspector } from "./describe-CivKHl4x.mjs";
|
|
3
3
|
import { Context, Duration, Effect, Layer, Schema } from "effect";
|
|
4
4
|
import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
5
5
|
import { HttpServerRequest } from "effect/http";
|
|
@@ -111,13 +111,13 @@ declare const uploadHandlers: (options?: UploadOptions) => Layer.Layer<HttpApiGr
|
|
|
111
111
|
*/
|
|
112
112
|
declare const uploadLayer: (options?: UploadOptions) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpRouter").HttpRouter | Inspector | import("effect/Path").Path | UploadPolicy | Uploads>;
|
|
113
113
|
/**
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
114
|
+
* Admits a request whose `Authorization` is `Bearer <token>`, and with no
|
|
115
|
+
* token (unset or empty) admits nobody, whatever it sends. The two are
|
|
116
|
+
* compared by digest, every byte, so the time taken says nothing of the
|
|
117
|
+
* token. For a deployment's secret (`wrangler secret put`); who may upload
|
|
118
|
+
* by session is the application's own `UploadPolicy`.
|
|
117
119
|
*/
|
|
118
|
-
declare const
|
|
119
|
-
readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>;
|
|
120
|
-
}) => ((request: Request, env: Env) => Promise<Response>);
|
|
120
|
+
declare const uploadPolicyBearer: (token: string | undefined) => Layer.Layer<UploadPolicy>;
|
|
121
121
|
/**
|
|
122
122
|
* Uploads kept in the application's `KeyValueStore`, each under its content
|
|
123
123
|
* hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the
|
|
@@ -127,5 +127,5 @@ declare const uploadsKeyValueStore: (options?: {
|
|
|
127
127
|
readonly prefix?: string;
|
|
128
128
|
}) => Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore>;
|
|
129
129
|
//#endregion
|
|
130
|
-
export { Uploads as a,
|
|
131
|
-
//# sourceMappingURL=upload-
|
|
130
|
+
export { Uploads as a, uploadPolicyBearer as c, FactsUnavailable as d, factsOf as f, admissionRateLimiter as h, UploadPolicy as i, uploadsKeyValueStore as l, RateLimited as m, UploadForbidden as n, uploadHandlers as o, Admission as p, UploadOptions as r, uploadLayer as s, UploadApi as t, FactsOptions as u };
|
|
131
|
+
//# sourceMappingURL=upload-kp0_oK76.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-
|
|
1
|
+
{"version":3,"file":"upload-kp0_oK76.d.mts","names":[],"sources":["../src/server/admission.ts","../src/server/facts.ts","../src/server/upload.ts"],"mappings":";;;;;;;;;;;cAIa,oBAAoB;;WAcb,QAAC,mBAAmB,OAAO,aAAa;;;;;;;;cAF/C,kBAAkB;;;;;;;cAWlB,uBAAoB;WACtB;WACA,QAAQ,SAAS;WACjB;MACP,MAAM,MAAM,kBAAkB,YAAY;;;;;;;;cCxBjC,yBAAyB;UAiBrB;;WAEN,OAAO;;WAEP;;WAEA,QAAQ,cAAc;;WAEtB,SAAS,SAAS,YAAY,QAAQ;;;;;;;;;;;cAYpC,UAAO,aACP,SACF,iBACR,OAAO,OAAO,YAAY,kBAAkB;;;;;;;cCzBlC,WAAS,QAAA,gCAAA,aAAA,wBAAA,gBAAA,6EAAA,OAAA,oDAAA,mCAAA,gBAAA,gFAAA,OAAA,oDAAA;;WAUJ,MAAC,cAAc,OAAO,WAAW,iBAAiB,OAAO;;;cAF9D,gBAAgB;;;cAMhB,wBAAwB;;WAejB,QACd,SAAS,kBAAkB,sBACxB,OAAO,aAAa;;;;;;;;cALhB,qBAAqB;UAYjB;;WAEN;;;;;WAKA,QAAQ,KAAK;aAAoC,QAAQ;;;;;;;;;;;cA0CvD,iBAAc,UAAa,kBAAa,MAAA,MAAA,aAAA,mDAAA,YAAA,eAAA;;;;;;cA0DxC,cAAW,UAAa,kBAAa,MAAA,gDAAA,wCAAA,+CAAA,gDAAA,aAAA,kCAAA,OAAA,eAAA;;;;;;;;cAerC,qBAAkB,8BAAgC,MAAM,MAAM;;;;;;cAoB9D,uBAAoB;WACX;MACnB,MAAM,MAAM,gBAAgB,cAAc"}
|
package/dist/vite/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as standard } from "../widths-BEa9odY6.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { a as ImageAsset, n as describe } from "../describe-h9F5stgR.mjs";
|
|
3
3
|
import { IconifySet, fromIconify, namesOf, parse } from "../icons/index.mjs";
|
|
4
4
|
import { n as Transformer } from "../services-BeakQl7F.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
@@ -134,9 +134,9 @@ const images = (options = {}) => {
|
|
|
134
134
|
})));
|
|
135
135
|
return [
|
|
136
136
|
`import { Schema } from 'effect'`,
|
|
137
|
-
`import {
|
|
137
|
+
`import { HashedAsset, Provider } from 'foldkit-media'`,
|
|
138
138
|
`export default {`,
|
|
139
|
-
` asset: Schema.decodeUnknownSync(
|
|
139
|
+
` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,
|
|
140
140
|
` provider: Provider.fromFiles([${files.join(", ")}], ${JSON.stringify({
|
|
141
141
|
sources,
|
|
142
142
|
fallback
|