foldkit-media 0.6.0 → 0.7.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.
@@ -0,0 +1,195 @@
1
+ import { Context, Data, Duration, Effect, Layer, Option, Schema, Semaphore, Stream } from "effect";
2
+ import { FileAsset } from "../file.js";
3
+ import { nonNegativeInteger, positiveInteger } from "../limits.js";
4
+ import { Diagnostics } from "foldkit-surface";
5
+ import { Admission } from "./admission.js";
6
+ import { ownerMissing } from "./diagnostics.js";
7
+ import "./upload.js";
8
+ import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
9
+ import { acceptor, fileHeaders, fileNameOf, isFileKey, mediaTypeOf } from "./fileRules.js";
10
+ import { HttpServerResponse } from "effect/http";
11
+ import { FileStore } from "./fileStore.js";
12
+ // src/server/files.ts
13
+ /**
14
+ * Where any file enters and leaves: `POST /_media/files` keeps one under a
15
+ * key the server mints, and `GET /_media/files/:key` serves it back as a
16
+ * download to whoever `FileReadPolicy` lets read it. Apart from `UploadApi`,
17
+ * so a server that mounts only the image routes serves no file.
18
+ */
19
+ /** The file routes, mounted alone: `fileLayer`. */
20
+ const FileApi = HttpApi.make("foldkit-media-files").add(HttpApiGroup.make("files").add(HttpApiEndpoint.post("upload", "/_media/files"), HttpApiEndpoint.get("download", "/_media/files/:key", { params: { key: Schema.String } })));
21
+ /**
22
+ * Who may upload a file, asked before the body is read, answering the
23
+ * uploader's id: only that id may later claim the file. It must be stable
24
+ * and never given to anyone else; an empty id is refused. No default, so a
25
+ * server is never open to uploads by omission.
26
+ */
27
+ var FileUploadPolicy = class extends Context.Service()("foldkit-media/FileUploadPolicy") {};
28
+ /** The read policy could not tell who is asking: the download answers 401. */
29
+ var FileUnauthenticated = class extends Schema.TaggedError()("FileUnauthenticated", {}) {};
30
+ /**
31
+ * Who may read which file, asked before the store is read: `resolve` says who
32
+ * is asking from the request alone, never the key, and answers what they may
33
+ * read. Build it with `fileReadPolicy`.
34
+ */
35
+ var FileReadPolicy = class extends Context.Service()("foldkit-media/FileReadPolicy") {};
36
+ /**
37
+ * A `FileReadPolicy` in its two steps: `resolve` says who is asking (a
38
+ * principal, a visitor) or fails `FileUnauthenticated`; `read` says whether
39
+ * they may read a key, typically by finding the application's row that holds
40
+ * it. A no is a 404, as an unknown key is.
41
+ */
42
+ const fileReadPolicy = (policy) => Layer.succeed(FileReadPolicy, { resolve: (request) => Effect.map(policy.resolve(request), (asker) => (key) => policy.read(asker, key)) });
43
+ /** An `inspect` hook's refusal of an upload: answered 415, with nothing kept. */
44
+ var FileRefused = class extends Schema.TaggedError()("FileRefused", {}) {};
45
+ const DEFAULT_MAX_BYTES = 20971520;
46
+ const DEFAULT_MIN_BYTES_PER_SECOND = 32768;
47
+ const RATE_WINDOW = Duration.seconds(10);
48
+ var BodyTooLarge = class extends Data.TaggedError("BodyTooLarge") {};
49
+ var BodyTooSlow = class extends Data.TaggedError("BodyTooSlow") {};
50
+ /**
51
+ * The body, refused past `maxBytes` as it streams, and cut off when a window
52
+ * brings fewer than `floor` bytes: a client trickling bytes cannot hold a
53
+ * slot, while a slow honest connection still finishes.
54
+ */
55
+ const bodyWithin = (stream, maxBytes, floor) => Effect.gen(function* () {
56
+ const chunks = [];
57
+ let size = 0;
58
+ let inWindow = 0;
59
+ const read = stream.pipe(Stream.runForEach((chunk) => Effect.suspend(() => {
60
+ size += chunk.byteLength;
61
+ inWindow += chunk.byteLength;
62
+ if (size > maxBytes) return Effect.fail(new BodyTooLarge());
63
+ chunks.push(chunk);
64
+ return Effect.void;
65
+ })));
66
+ const watch = Effect.sleep(RATE_WINDOW).pipe(Effect.andThen(Effect.suspend(() => {
67
+ if (inWindow < floor) return Effect.fail(new BodyTooSlow());
68
+ inWindow = 0;
69
+ return Effect.void;
70
+ })), Effect.forever);
71
+ yield* Effect.raceFirst(read, watch);
72
+ const bytes = new Uint8Array(size);
73
+ let at = 0;
74
+ for (const chunk of chunks) {
75
+ bytes.set(chunk, at);
76
+ at += chunk.byteLength;
77
+ }
78
+ return bytes;
79
+ });
80
+ const UPLOAD_HEADERS = {
81
+ "cache-control": "no-store",
82
+ "x-content-type-options": "nosniff"
83
+ };
84
+ const refused = (status, error) => HttpServerResponse.jsonUnsafe({ error }, {
85
+ status,
86
+ headers: UPLOAD_HEADERS
87
+ });
88
+ const notFound = HttpServerResponse.empty({
89
+ status: 404,
90
+ headers: fileHeaders(Option.none())
91
+ });
92
+ const unauthenticated = HttpServerResponse.empty({
93
+ status: 401,
94
+ headers: fileHeaders(Option.none())
95
+ });
96
+ /**
97
+ * The file routes' handlers. An upload is asked of the `FileUploadPolicy`
98
+ * first, then must be `application/octet-stream` (which no page on another
99
+ * site can send without a preflight this route never answers), declare a
100
+ * name and an accepted type in its headers, pass `Admission` when one is
101
+ * given, find a free slot, arrive within `maxBytes` and the minimum rate, and
102
+ * pass `inspect`; it answers the kept `FileAsset`, 201. A download checks
103
+ * the key's grammar, then the `FileReadPolicy`, then the store, and answers
104
+ * the bytes as an attachment that cannot run on this origin.
105
+ */
106
+ const fileHandlers = (options) => {
107
+ const accepts = acceptor(options.accept);
108
+ const maxBytes = nonNegativeInteger("maxBytes", options.maxBytes ?? DEFAULT_MAX_BYTES);
109
+ const maxConcurrent = positiveInteger("maxConcurrent", options.maxConcurrent ?? 2);
110
+ const floor = nonNegativeInteger("minBytesPerSecond", options.minBytesPerSecond ?? DEFAULT_MIN_BYTES_PER_SECOND) * Duration.toSeconds(RATE_WINDOW);
111
+ const inspect = options.inspect ?? (() => Effect.void);
112
+ const encode = Schema.encodeSync(FileAsset);
113
+ return HttpApiBuilder.group(FileApi, "files", (group) => Effect.gen(function* () {
114
+ const files = yield* FileStore;
115
+ const uploadPolicy = yield* FileUploadPolicy;
116
+ const readPolicy = yield* FileReadPolicy;
117
+ const admit = Option.match(yield* Effect.serviceOption(Admission), {
118
+ onNone: () => (_client) => Effect.void,
119
+ onSome: (admission) => admission.admit
120
+ });
121
+ const slots = yield* Semaphore.make(maxConcurrent);
122
+ const uploading = /* @__PURE__ */ new Set();
123
+ const inSlot = (owner, effect) => Effect.uninterruptibleMask((restore) => Effect.suspend(() => {
124
+ if (uploading.has(owner)) return Effect.succeedNone;
125
+ uploading.add(owner);
126
+ return restore(Semaphore.withPermitsIfAvailable(slots, 1)(effect)).pipe(Effect.ensuring(Effect.sync(() => uploading.delete(owner))));
127
+ }));
128
+ return group.handle("upload", ({ request }) => Effect.gen(function* () {
129
+ const owner = yield* uploadPolicy.admit(request);
130
+ if (owner === "") {
131
+ yield* Diagnostics.report(ownerMissing);
132
+ return refused(403, "Forbidden");
133
+ }
134
+ if (!Option.contains(mediaTypeOf(request.headers["content-type"]), "application/octet-stream")) return refused(415, "Unsupported");
135
+ const name = fileNameOf(request.headers["x-foldkit-file-name"]);
136
+ if (Option.isNone(name)) return refused(400, "Malformed");
137
+ const type = Option.filter(mediaTypeOf(request.headers["x-foldkit-file-type"]), accepts);
138
+ if (Option.isNone(type)) return refused(415, "Unsupported");
139
+ const declared = {
140
+ name: name.value,
141
+ type: type.value
142
+ };
143
+ yield* admit(`files:${owner}`);
144
+ const kept = yield* inSlot(owner, Effect.gen(function* () {
145
+ const bytes = yield* bodyWithin(request.stream, maxBytes, floor);
146
+ yield* inspect(bytes, declared);
147
+ return yield* files.keep(bytes, {
148
+ ...declared,
149
+ owner
150
+ });
151
+ }));
152
+ return Option.match(kept, {
153
+ onNone: () => refused(503, "Busy"),
154
+ onSome: (asset) => HttpServerResponse.jsonUnsafe(encode(asset), {
155
+ status: 201,
156
+ headers: UPLOAD_HEADERS
157
+ })
158
+ });
159
+ }).pipe(Effect.catchTags({
160
+ UploadForbidden: () => Effect.succeed(refused(403, "Forbidden")),
161
+ UploadUnauthenticated: () => Effect.succeed(refused(401, "Unauthenticated")),
162
+ RateLimited: ({ retryAfterSeconds }) => Effect.succeed(HttpServerResponse.jsonUnsafe({ error: "RateLimited" }, {
163
+ status: 429,
164
+ headers: {
165
+ ...UPLOAD_HEADERS,
166
+ "retry-after": String(retryAfterSeconds)
167
+ }
168
+ })),
169
+ BodyTooLarge: () => Effect.succeed(refused(413, "TooLarge")),
170
+ BodyTooSlow: () => Effect.succeed(refused(408, "TooSlow")),
171
+ FileRefused: () => Effect.succeed(refused(415, "Unsupported")),
172
+ HttpServerError: () => Effect.succeed(refused(400, "Malformed"))
173
+ }), Effect.withSpan("Media.fileUpload"))).handle("download", ({ params, request }) => Effect.gen(function* () {
174
+ if (!isFileKey(params.key)) return notFound;
175
+ if (!(yield* (yield* readPolicy.resolve(request))(params.key))) return notFound;
176
+ return Option.match(yield* files.read(params.key), {
177
+ onNone: () => notFound,
178
+ onSome: ({ asset, bytes }) => HttpServerResponse.uint8Array(bytes, {
179
+ status: 200,
180
+ headers: fileHeaders(Option.some(asset.name)),
181
+ contentType: "application/octet-stream"
182
+ })
183
+ });
184
+ }).pipe(Effect.catchTag("FileUnauthenticated", () => Effect.succeed(unauthenticated)), Effect.withSpan("Media.fileDownload")));
185
+ }));
186
+ };
187
+ /**
188
+ * The file routes as an Effect HTTP application, registered with the
189
+ * `HttpRouter`, needing a `FileStore`, a `FileUploadPolicy` and a
190
+ * `FileReadPolicy`, and `Admission` if one is given.
191
+ */
192
+ const fileLayer = (options) => HttpApiBuilder.layer(FileApi).pipe(Layer.provide(fileHandlers(options)));
193
+ export { FileApi, FileReadPolicy, FileRefused, FileUnauthenticated, FileUploadPolicy, fileHandlers, fileLayer, fileReadPolicy };
194
+
195
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.js","names":[],"sources":["../../src/server/files.ts"],"sourcesContent":["/**\n * Where any file enters and leaves: `POST /_media/files` keeps one under a\n * key the server mints, and `GET /_media/files/:key` serves it back as a\n * download to whoever `FileReadPolicy` lets read it. Apart from `UploadApi`,\n * so a server that mounts only the image routes serves no file.\n */\nimport { Context, Data, Duration, Effect, Layer, Option, Schema, Semaphore, Stream } from 'effect'\nimport { HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from 'effect/http-api'\nimport { Diagnostics } from 'foldkit-surface'\nimport { FileAsset } from '../file.js'\nimport { nonNegativeInteger, positiveInteger } from '../limits.js'\nimport { Admission } from './admission.js'\nimport { ownerMissing } from './diagnostics.js'\nimport {\n acceptor,\n fileHeaders,\n fileNameOf,\n isFileKey,\n mediaTypeOf,\n type Accept,\n} from './fileRules.js'\nimport { FileStore } from './fileStore.js'\nimport { UploadForbidden, UploadUnauthenticated } from './upload.js'\n\n/** The file routes, mounted alone: `fileLayer`. */\nexport const FileApi = HttpApi.make('foldkit-media-files').add(\n HttpApiGroup.make('files').add(\n HttpApiEndpoint.post('upload', '/_media/files'),\n HttpApiEndpoint.get('download', '/_media/files/:key', { params: { key: Schema.String } }),\n ),\n)\n\n/**\n * Who may upload a file, asked before the body is read, answering the\n * uploader's id: only that id may later claim the file. It must be stable\n * and never given to anyone else; an empty id is refused. No default, so a\n * server is never open to uploads by omission.\n */\nexport class FileUploadPolicy extends Context.Service<\n FileUploadPolicy,\n {\n readonly admit: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<string, UploadForbidden | UploadUnauthenticated>\n }\n>()('foldkit-media/FileUploadPolicy') {}\n\n/** The read policy could not tell who is asking: the download answers 401. */\nexport class FileUnauthenticated extends Schema.TaggedError<FileUnauthenticated>()(\n 'FileUnauthenticated',\n {},\n) {}\n\n/** Whether the asker may read the file under a key. */\nexport type FileReader = (key: string) => Effect.Effect<boolean>\n\n/**\n * Who may read which file, asked before the store is read: `resolve` says who\n * is asking from the request alone, never the key, and answers what they may\n * read. Build it with `fileReadPolicy`.\n */\nexport class FileReadPolicy extends Context.Service<\n FileReadPolicy,\n {\n readonly resolve: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<FileReader, FileUnauthenticated>\n }\n>()('foldkit-media/FileReadPolicy') {}\n\n/**\n * A `FileReadPolicy` in its two steps: `resolve` says who is asking (a\n * principal, a visitor) or fails `FileUnauthenticated`; `read` says whether\n * they may read a key, typically by finding the application's row that holds\n * it. A no is a 404, as an unknown key is.\n */\nexport const fileReadPolicy = <Asker>(policy: {\n readonly resolve: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<Asker, FileUnauthenticated>\n readonly read: (asker: Asker, key: string) => Effect.Effect<boolean>\n}): Layer.Layer<FileReadPolicy> =>\n Layer.succeed(FileReadPolicy, {\n resolve: request =>\n Effect.map(policy.resolve(request), asker => (key: string) => policy.read(asker, key)),\n })\n\n/** An `inspect` hook's refusal of an upload: answered 415, with nothing kept. */\nexport class FileRefused extends Schema.TaggedError<FileRefused>()('FileRefused', {}) {}\n\nexport interface FileOptions {\n /**\n * The declared types an upload may have: media types or `type/*` patterns,\n * or `'*'` for any. The client writes the type, so this shapes the product\n * and secures nothing: a download is never served as its type.\n */\n readonly accept: Accept\n /** The largest file read, in bytes, counted as it streams; 20 MB by default. */\n readonly maxBytes?: number\n /**\n * Uploads read at once, each holding about twice its size; 2 by default.\n * One past it, or a second from one owner, answers 503 rather than waiting.\n */\n readonly maxConcurrent?: number\n /** The slowest a body may arrive, over each 10 seconds, before it is cut off (408); 32 KB/s by default. */\n readonly minBytesPerSecond?: number\n /** Reads the bytes before anything is kept: a magic-number check, a scan. */\n readonly inspect?: (\n bytes: Uint8Array<ArrayBuffer>,\n declared: { readonly name: string; readonly type: string },\n ) => Effect.Effect<void, FileRefused>\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\nconst DEFAULT_MIN_BYTES_PER_SECOND = 32 * 1024\nconst RATE_WINDOW = Duration.seconds(10)\n\nclass BodyTooLarge extends Data.TaggedError('BodyTooLarge') {}\nclass BodyTooSlow extends Data.TaggedError('BodyTooSlow') {}\n\n/**\n * The body, refused past `maxBytes` as it streams, and cut off when a window\n * brings fewer than `floor` bytes: a client trickling bytes cannot hold a\n * slot, while a slow honest connection still finishes.\n */\nconst bodyWithin = <E>(\n stream: Stream.Stream<Uint8Array, E>,\n maxBytes: number,\n floor: number,\n): Effect.Effect<Uint8Array<ArrayBuffer>, E | BodyTooLarge | BodyTooSlow> =>\n Effect.gen(function* () {\n const chunks: Array<Uint8Array> = []\n let size = 0\n let inWindow = 0\n const read = stream.pipe(\n Stream.runForEach(chunk =>\n Effect.suspend(() => {\n size += chunk.byteLength\n inWindow += chunk.byteLength\n if (size > maxBytes) return Effect.fail(new BodyTooLarge())\n chunks.push(chunk)\n return Effect.void\n }),\n ),\n )\n const watch: Effect.Effect<never, BodyTooSlow> = Effect.sleep(RATE_WINDOW).pipe(\n Effect.andThen(\n Effect.suspend(() => {\n if (inWindow < floor) return Effect.fail(new BodyTooSlow())\n inWindow = 0\n return Effect.void\n }),\n ),\n Effect.forever,\n )\n yield* Effect.raceFirst(read, watch)\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\nconst UPLOAD_HEADERS = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }\n\n// A refusal names its kind, and nothing of the server's internals.\nconst refused = (status: number, error: string) =>\n HttpServerResponse.jsonUnsafe({ error }, { status, headers: UPLOAD_HEADERS })\n\nconst notFound = HttpServerResponse.empty({ status: 404, headers: fileHeaders(Option.none()) })\nconst unauthenticated = HttpServerResponse.empty({\n status: 401,\n headers: fileHeaders(Option.none()),\n})\n\n/**\n * The file routes' handlers. An upload is asked of the `FileUploadPolicy`\n * first, then must be `application/octet-stream` (which no page on another\n * site can send without a preflight this route never answers), declare a\n * name and an accepted type in its headers, pass `Admission` when one is\n * given, find a free slot, arrive within `maxBytes` and the minimum rate, and\n * pass `inspect`; it answers the kept `FileAsset`, 201. A download checks\n * the key's grammar, then the `FileReadPolicy`, then the store, and answers\n * the bytes as an attachment that cannot run on this origin.\n */\nexport const fileHandlers = (options: FileOptions) => {\n const accepts = acceptor(options.accept)\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n const maxConcurrent = positiveInteger('maxConcurrent', options.maxConcurrent ?? 2)\n const floor =\n nonNegativeInteger(\n 'minBytesPerSecond',\n options.minBytesPerSecond ?? DEFAULT_MIN_BYTES_PER_SECOND,\n ) * Duration.toSeconds(RATE_WINDOW)\n const inspect = options.inspect ?? (() => Effect.void)\n const encode = Schema.encodeSync(FileAsset)\n return HttpApiBuilder.group(FileApi, 'files', group =>\n Effect.gen(function* () {\n const files = yield* FileStore\n const uploadPolicy = yield* FileUploadPolicy\n const readPolicy = yield* FileReadPolicy\n const admit = Option.match(yield* Effect.serviceOption(Admission), {\n onNone: () => (_client: string) => Effect.void,\n onSome: admission => admission.admit,\n })\n // Built with the route, so the slots are the server's (a Worker isolate's), not a request's.\n const slots = yield* Semaphore.make(maxConcurrent)\n const uploading = new Set<string>()\n // Masked, so no interruption lands between taking the owner's mark and arranging its release.\n const inSlot = <A, E>(owner: string, effect: Effect.Effect<A, E>) =>\n Effect.uninterruptibleMask(restore =>\n Effect.suspend(() => {\n if (uploading.has(owner)) return Effect.succeedNone\n uploading.add(owner)\n return restore(Semaphore.withPermitsIfAvailable(slots, 1)(effect)).pipe(\n Effect.ensuring(Effect.sync(() => uploading.delete(owner))),\n )\n }),\n )\n return group\n .handle('upload', ({ request }) =>\n Effect.gen(function* () {\n const owner = yield* uploadPolicy.admit(request)\n if (owner === '') {\n yield* Diagnostics.report(ownerMissing)\n return refused(403, 'Forbidden')\n }\n if (\n !Option.contains(\n mediaTypeOf(request.headers['content-type']),\n 'application/octet-stream',\n )\n ) {\n return refused(415, 'Unsupported')\n }\n const name = fileNameOf(request.headers['x-foldkit-file-name'])\n if (Option.isNone(name)) return refused(400, 'Malformed')\n const type = Option.filter(mediaTypeOf(request.headers['x-foldkit-file-type']), accepts)\n if (Option.isNone(type)) return refused(415, 'Unsupported')\n const declared = { name: name.value, type: type.value }\n yield* admit(`files:${owner}`)\n const kept = yield* inSlot(\n owner,\n Effect.gen(function* () {\n const bytes = yield* bodyWithin(request.stream, maxBytes, floor)\n yield* inspect(bytes, declared)\n return yield* files.keep(bytes, { ...declared, owner })\n }),\n )\n return Option.match(kept, {\n onNone: () => refused(503, 'Busy'),\n onSome: asset =>\n HttpServerResponse.jsonUnsafe(encode(asset), {\n status: 201,\n headers: UPLOAD_HEADERS,\n }),\n })\n }).pipe(\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(403, 'Forbidden')),\n UploadUnauthenticated: () => Effect.succeed(refused(401, 'Unauthenticated')),\n RateLimited: ({ retryAfterSeconds }) =>\n Effect.succeed(\n HttpServerResponse.jsonUnsafe(\n { error: 'RateLimited' },\n {\n status: 429,\n headers: { ...UPLOAD_HEADERS, 'retry-after': String(retryAfterSeconds) },\n },\n ),\n ),\n BodyTooLarge: () => Effect.succeed(refused(413, 'TooLarge')),\n BodyTooSlow: () => Effect.succeed(refused(408, 'TooSlow')),\n FileRefused: () => Effect.succeed(refused(415, 'Unsupported')),\n // The body broke off or could not be read: the request's fault, not the server's.\n HttpServerError: () => Effect.succeed(refused(400, 'Malformed')),\n }),\n Effect.withSpan('Media.fileUpload'),\n ),\n )\n .handle('download', ({ params, request }) =>\n Effect.gen(function* () {\n // Before any policy: a key outside the grammar names nothing a policy could allow.\n if (!isFileKey(params.key)) return notFound\n const mayRead = yield* readPolicy.resolve(request)\n if (!(yield* mayRead(params.key))) return notFound\n return Option.match(yield* files.read(params.key), {\n onNone: () => notFound,\n onSome: ({ asset, bytes }) =>\n HttpServerResponse.uint8Array(bytes, {\n status: 200,\n headers: fileHeaders(Option.some(asset.name)),\n contentType: 'application/octet-stream',\n }),\n })\n }).pipe(\n Effect.catchTag('FileUnauthenticated', () => Effect.succeed(unauthenticated)),\n Effect.withSpan('Media.fileDownload'),\n ),\n )\n }),\n )\n}\n\n/**\n * The file routes as an Effect HTTP application, registered with the\n * `HttpRouter`, needing a `FileStore`, a `FileUploadPolicy` and a\n * `FileReadPolicy`, and `Admission` if one is given.\n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AAM,KAAK,OAAO,GAAG,GAAG;IACjD,cAAc;IACd,SAAS,EAAE,OAAO,YAChB,mBAAmB,WAAW,OAAO;KACnC,QAAQ;KACR,SAAS,YAAY,OAAO,KAAK,MAAM,IAAI,CAAC;KAC5C,aAAa;IACf,CAAC;GACL,CAAC;EACH,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,6BAA6B,OAAO,QAAQ,eAAe,CAAC,GAC5E,OAAO,SAAS,oBAAoB,CACtC,CACF;CACJ,CAAC,CACH;AACF;;;;;;AAOA,MAAa,aAAa,YACxB,eAAe,MAAM,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,aAAa,OAAO,CAAC,CAAC"}
@@ -1,13 +1,16 @@
1
1
  import { OriginalNotFound, OriginalTooLarge, QuotaExhausted, TransformFailed } from "./errors.js";
2
2
  import { Admission, RateLimited, admissionRateLimiter } from "./admission.js";
3
- import { AdmissionFailed, FactsUnanswered, ImageFailed, MediaDiagnostic, RequestDefect, StoreFailed } from "./diagnostics.js";
3
+ import { AdmissionFailed, FactsUnanswered, ImageFailed, MediaDiagnostic, OwnerMissing, RequestDefect, StoreFailed } from "./diagnostics.js";
4
4
  import { Encoded, Kept, Original, Originals, Transformer, Variants, limitTransforms, variantsNone } from "./services.js";
5
5
  import { StoredFacts, UploadApi, UploadForbidden, UploadOptions, UploadPolicy, UploadRoute, UploadUnauthenticated, Uploads, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore } from "./upload.js";
6
6
  import { originalsKeyValueStore, variantsKeyValueStore } from "./stores.js";
7
+ import { FileApi, FileOptions, FileReadPolicy, FileReader, FileRefused, FileUnauthenticated, FileUploadPolicy, fileHandlers, fileLayer, fileReadPolicy } from "./files.js";
7
8
  import { Options, handlers, layer } from "./handlers.js";
9
+ import { Accept } from "./fileRules.js";
10
+ import { Declared, FileStore, FileStoreOptions, FileUnclaimed, StoredFile, filesKeyValueStore, keepOrClaim } from "./fileStore.js";
8
11
  import { MediaApi } from "./api.js";
9
12
  import { Answer, headersFor, statusOf } from "./headers.js";
10
13
  import { FetchOptions, serveFetch } from "./fetch.js";
11
14
  import { Materialized, headersRule, materialize } from "./materialize.js";
12
15
  import { FactsOptions, FactsUnavailable, factsOf } from "./facts.js";
13
- export { Admission, type AdmissionFailed, Answer, type Encoded, type FactsOptions, type FactsUnanswered, FactsUnavailable, type FetchOptions, type ImageFailed, type Kept, type Materialized, MediaApi, type MediaDiagnostic, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, type RequestDefect, type StoreFailed, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, type UploadRoute, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
16
+ export { type Accept, Admission, type AdmissionFailed, Answer, type Declared, type Encoded, type FactsOptions, type FactsUnanswered, FactsUnavailable, type FetchOptions, FileApi, type FileOptions, FileReadPolicy, type FileReader, FileRefused, FileStore, type FileStoreOptions, FileUnauthenticated, FileUnclaimed, FileUploadPolicy, type ImageFailed, type Kept, type Materialized, MediaApi, type MediaDiagnostic, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, type OwnerMissing, QuotaExhausted, RateLimited, type RequestDefect, type StoreFailed, StoredFacts, type StoredFile, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, type UploadRoute, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, fileHandlers, fileLayer, fileReadPolicy, filesKeyValueStore, handlers, headersFor, headersRule, keepOrClaim, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
@@ -3,10 +3,12 @@ import { Admission, RateLimited, admissionRateLimiter } from "./admission.js";
3
3
  import { Originals, Transformer, Variants, limitTransforms, variantsNone } from "./services.js";
4
4
  import { StoredFacts, UploadApi, UploadForbidden, UploadPolicy, UploadUnauthenticated, Uploads, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore } from "./upload.js";
5
5
  import { originalsKeyValueStore, variantsKeyValueStore } from "./stores.js";
6
+ import { FileApi, FileReadPolicy, FileRefused, FileUnauthenticated, FileUploadPolicy, fileHandlers, fileLayer, fileReadPolicy } from "./files.js";
6
7
  import { handlers, layer } from "./handlers.js";
8
+ import { FileStore, FileUnclaimed, filesKeyValueStore, keepOrClaim } from "./fileStore.js";
7
9
  import { MediaApi } from "./api.js";
8
10
  import { Answer, headersFor, statusOf } from "./headers.js";
9
11
  import { serveFetch } from "./fetch.js";
10
12
  import { headersRule, materialize } from "./materialize.js";
11
13
  import { FactsUnavailable, factsOf } from "./facts.js";
12
- export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
14
+ export { Admission, Answer, FactsUnavailable, FileApi, FileReadPolicy, FileRefused, FileStore, FileUnauthenticated, FileUnclaimed, FileUploadPolicy, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, fileHandlers, fileLayer, fileReadPolicy, filesKeyValueStore, handlers, headersFor, headersRule, keepOrClaim, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-media",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",
@@ -78,7 +78,7 @@
78
78
  ],
79
79
  "dependencies": {
80
80
  "thumbhash": "^0.1.1",
81
- "foldkit-surface": "0.13.0"
81
+ "foldkit-surface": "0.14.0"
82
82
  },
83
83
  "peerDependencies": {
84
84
  "effect": "^4.1.0",