@softistx/alxia-media 0.0.0-stage → 0.12.1
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/LICENSE +21 -0
- package/README.md +373 -2
- package/dist/body.d.ts +24 -0
- package/dist/body.d.ts.map +1 -0
- package/dist/bucket.d.ts +21 -0
- package/dist/bucket.d.ts.map +1 -0
- package/dist/checks.d.ts +11 -0
- package/dist/checks.d.ts.map +1 -0
- package/dist/chunks/index-8s779ve6.js +106 -0
- package/dist/chunks/index-8s779ve6.js.map +10 -0
- package/dist/headers.d.ts +19 -0
- package/dist/headers.d.ts.map +1 -0
- package/dist/image/index.d.ts +2 -0
- package/dist/image/index.d.ts.map +1 -0
- package/dist/image/index.js +199 -0
- package/dist/image/index.js.map +11 -0
- package/dist/image/peer.d.ts +14 -0
- package/dist/image/peer.d.ts.map +1 -0
- package/dist/image/rendition.d.ts +109 -0
- package/dist/image/rendition.d.ts.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +825 -0
- package/dist/index.js.map +22 -0
- package/dist/key.d.ts +40 -0
- package/dist/key.d.ts.map +1 -0
- package/dist/kind-callbacks.d.ts +28 -0
- package/dist/kind-callbacks.d.ts.map +1 -0
- package/dist/kind-check.d.ts +20 -0
- package/dist/kind-check.d.ts.map +1 -0
- package/dist/kind.d.ts +173 -0
- package/dist/kind.d.ts.map +1 -0
- package/dist/range.d.ts +17 -0
- package/dist/range.d.ts.map +1 -0
- package/dist/read.d.ts +11 -0
- package/dist/read.d.ts.map +1 -0
- package/dist/refusal.d.ts +90 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/rendition.d.ts +94 -0
- package/dist/rendition.d.ts.map +1 -0
- package/dist/routes.d.ts +62 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/sniff.d.ts +16 -0
- package/dist/sniff.d.ts.map +1 -0
- package/dist/write.d.ts +42 -0
- package/dist/write.d.ts.map +1 -0
- package/docs/README.md +11 -0
- package/docs/guide.md +902 -0
- package/docs/roadmap.md +73 -0
- package/docs/troubleshooting.md +563 -0
- package/package.json +65 -5
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/key.ts", "../src/sniff.ts", "../src/kind-check.ts", "../src/kind.ts", "../src/routes.ts", "../src/bucket.ts", "../src/read.ts", "../src/headers.ts", "../src/range.ts", "../src/write.ts", "../src/body.ts", "../src/checks.ts", "../src/rendition.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Media keys. A key is what an upload answers and a record keeps: a fresh\n * lower-case UUID, never a URL. Anything else in a URL's key segment is a\n * 404 before the bucket is asked.\n */\n\nconst KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\n/** A key as the routes mint and read it: a lower-case UUID. */\nexport type MediaKey = string;\n\n/** Whether `value` is a key `newMediaKey` could have made. */\nexport function isMediaKey(value: unknown): value is MediaKey {\n\treturn typeof value === 'string' && KEY.test(value);\n}\n\n/** A fresh key. */\nexport function newMediaKey(): MediaKey {\n\treturn crypto.randomUUID();\n}\n\n/** The name of a kind: lower-case words, digits and hyphens, starting with a letter. */\nconst KIND_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\n/** Whether `value` can name a kind (it is a path segment and the bucket's folder). */\nexport function isMediaKindName(value: unknown): value is string {\n\treturn typeof value === 'string' && KIND_NAME.test(value);\n}\n\n/** A named size of a stored file (`thumb`, `256`): lower-case words and digits, hyphens between. */\nexport function isMediaSize(value: unknown): value is string {\n\treturn typeof value === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);\n}\n\n/**\n * The bucket key of a stored file: `<kind>/<key>`, or `<kind>/<key>/<size>`.\n * It never adds a `keyExtension`; `mediaPlace` does.\n */\nexport function mediaObjectKey(\n\tkind: string,\n\tkey: MediaKey,\n\tsize?: string,\n): string {\n\treturn size === undefined ? `${kind}/${key}` : `${kind}/${key}/${size}`;\n}\n\n/**\n * Where the objects of one request live: `place(key)` or `place(key, size)`, a\n * bucket key. The original is never given an extension.\n */\nexport type MediaPlace = (key: MediaKey, size?: string) => string;\n\nconst PREFIX_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._=-]*$/;\n\n/**\n * The folders a `keyPrefix` hook puts a request's objects under: segments\n * of letters, digits and `. _ = -` joined by `/`, no empty segment, no\n * leading or trailing `/`, no `.` or `..`. Anything else is the app's bug\n * and throws a `TypeError` (a 500): a prefix is never sanitised, since a\n * silent change could move a tenant's objects into another's folder.\n */\nexport function checkedPrefix(value: unknown): string | undefined {\n\tif (value === undefined || value === '') return undefined;\n\tconst valid =\n\t\ttypeof value === 'string' &&\n\t\tvalue\n\t\t\t.split('/')\n\t\t\t.every(\n\t\t\t\t(segment) =>\n\t\t\t\t\tPREFIX_SEGMENT.test(segment) && segment !== '.' && segment !== '..',\n\t\t\t);\n\tif (!valid) {\n\t\tthrow new TypeError(\n\t\t\t`@softistx/alxia-media: keyPrefix gave ${JSON.stringify(value)}, which is not folders of letters, digits and . _ = - joined by \"/\"`,\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * `mediaObjectKey` under an optional prefix (`<prefix>/<kind>/<key>[/<size>]`).\n * With `extension` (`'webp'`), a size's key ends in it:\n * `<prefix>/<kind>/<key>/<size>.<extension>`; the original's does not.\n */\nexport function mediaPlace(\n\tkind: string,\n\tprefix?: string,\n\textension?: string,\n): MediaPlace {\n\tconst folders = checkedPrefix(prefix);\n\tconst suffix = extension === undefined ? '' : `.${extension}`;\n\treturn (key, size) =>\n\t\t`${folders === undefined ? '' : `${folders}/`}${mediaObjectKey(kind, key, size === undefined ? undefined : `${size}${suffix}`)}`;\n}\n",
|
|
6
|
+
"/**\n * Magic-byte sniffing: the first bytes of an upload must be those of the\n * type it declares. A client that sends `image/png` over an HTML page is\n * refused 415 before anything is stored.\n */\n\n/** How many leading bytes `sniffs` needs. */\nexport const SNIFF_BYTES = 16;\n\ntype Signature = (head: Uint8Array) => boolean;\n\nconst at = (head: Uint8Array, offset: number, bytes: readonly number[]) =>\n\tbytes.every((byte, index) => head[offset + index] === byte);\n\nconst ascii = (text: string) => [...text].map((c) => c.charCodeAt(0));\n\n/** The signatures this package knows, by content type. */\nexport const MEDIA_SIGNATURES: Readonly<Record<string, Signature>> = {\n\t'image/png': (h) =>\n\t\tat(h, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),\n\t'image/jpeg': (h) => at(h, 0, [0xff, 0xd8, 0xff]),\n\t'image/gif': (h) => at(h, 0, ascii('GIF87a')) || at(h, 0, ascii('GIF89a')),\n\t'image/webp': (h) => at(h, 0, ascii('RIFF')) && at(h, 8, ascii('WEBP')),\n\t'image/avif': (h) =>\n\t\tat(h, 4, ascii('ftyp')) &&\n\t\t(at(h, 8, ascii('avif')) || at(h, 8, ascii('avis'))),\n\t'application/pdf': (h) => at(h, 0, ascii('%PDF-')),\n\t'audio/mpeg': (h) =>\n\t\tat(h, 0, ascii('ID3')) || (h[0] === 0xff && ((h[1] ?? 0) & 0xe0) === 0xe0),\n\t// ADTS: 12 sync bits, then the layer bits (00), which tells it from MP3.\n\t'audio/aac': (h) => h[0] === 0xff && ((h[1] ?? 0) & 0xf6) === 0xf0,\n\t'audio/ogg': (h) => at(h, 0, ascii('OggS')),\n\t'audio/wav': (h) => at(h, 0, ascii('RIFF')) && at(h, 8, ascii('WAVE')),\n\t'audio/mp4': (h) => at(h, 4, ascii('ftyp')),\n\t'video/mp4': (h) => at(h, 4, ascii('ftyp')),\n\t'video/quicktime': (h) => at(h, 4, ascii('ftyp')) && at(h, 8, ascii('qt ')),\n\t'video/webm': (h) => at(h, 0, [0x1a, 0x45, 0xdf, 0xa3]),\n};\n\n/** Whether this package can sniff `type`. */\nexport function canSniff(type: string): boolean {\n\treturn Object.hasOwn(MEDIA_SIGNATURES, type);\n}\n\n/** Whether the head of a body is a `type` file. A type nobody can sniff is not. */\nexport function sniffs(type: string, head: Uint8Array): boolean {\n\tconst signature = Object.hasOwn(MEDIA_SIGNATURES, type)\n\t\t? MEDIA_SIGNATURES[type]\n\t\t: undefined;\n\treturn signature?.(head) === true;\n}\n",
|
|
7
|
+
"/** The checks `defineMediaKind` shares: content types and renditions. */\n\nimport type { MediaRenditions } from './rendition';\nimport { canSniff } from './sniff';\n\n/** The content type of a header, as the kinds list it: no parameters, lower case. */\nexport function essenceOf(type: string): string {\n\treturn (type.split(';')[0] ?? '').trim().toLowerCase();\n}\n\nconst TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\n\n/** Whether `type` is an exact content type: no wildcard, no parameters, lower case. */\nexport const isExactType = (type: string) =>\n\tTYPE.test(essenceOf(type)) && essenceOf(type) === type;\n\n/** The `accept` that takes every content type. */\nexport const ANY_TYPE = '*';\n\n/** Whether a kind's `accept` takes every content type. */\nexport const acceptsAny = (accept: readonly string[]) =>\n\taccept.length === 1 && accept[0] === ANY_TYPE;\n\n/** Whether `type` is a well-formed content type, whatever it is. */\nexport const isWellFormedType = (type: string) => TYPE.test(type);\n\nexport function checkRenditions(\n\twhere: string,\n\tsizes: readonly string[],\n\trenditions: MediaRenditions | undefined,\n): void {\n\tif (renditions === undefined) return;\n\tif (sizes.length === 0) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: renditions needs sizes, the names of what it makes`,\n\t\t);\n\t}\n\tif (renditions.types.length === 0) {\n\t\tthrow new TypeError(`${where}: renditions lists no content type`);\n\t}\n\tconst { keyExtension } = renditions;\n\tif (\n\t\tkeyExtension !== undefined &&\n\t\t!(typeof keyExtension === 'string' && /^[a-z0-9]+$/.test(keyExtension))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: renditions keyExtension must be lower-case letters and digits with no dot, got ${JSON.stringify(keyExtension)}`,\n\t\t);\n\t}\n\tfor (const type of renditions.types) {\n\t\tif (!isExactType(type)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: renditions type ${JSON.stringify(type)} is not an exact content type`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The normalised `accept` of a kind: `['*']` for any type, else the exact\n * types, lower-cased. Throws on an empty list, a type that is not exact, and\n * (with `sniff: true`) a type nobody can sniff.\n */\nexport function checkAccept(\n\twhere: string,\n\taccept: readonly string[] | typeof ANY_TYPE,\n\tsniff: boolean | 'known',\n): string[] {\n\tif (accept === ANY_TYPE) return [ANY_TYPE];\n\tif (!Array.isArray(accept) || accept.length === 0) {\n\t\tthrow new TypeError(`${where}: accept lists no content type`);\n\t}\n\treturn accept.map((type) => {\n\t\tconst essence = essenceOf(type);\n\t\tif (!isExactType(type)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: ${JSON.stringify(type)} is not an exact content type (no wildcard, no parameters)`,\n\t\t\t);\n\t\t}\n\t\tif (sniff === true && !canSniff(essence)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: no signature is known for ${essence}; pass sniff: 'known' to check only the types that have one, or sniff: false to take it unverified`,\n\t\t\t);\n\t\t}\n\t\treturn essence;\n\t});\n}\n",
|
|
8
|
+
"/** `defineMediaKind`: what one kind of file is allowed, who may do what with it. */\n\nimport type { BaseContext, Empty } from '@softistx/alxia';\nimport { isMediaKindName, isMediaSize, type MediaKey } from './key';\nimport {\n\ttype ANY_TYPE,\n\tacceptsAny,\n\tcheckAccept,\n\tcheckRenditions,\n\tessenceOf,\n} from './kind-check';\nimport type { MediaVerdict } from './refusal';\nimport type { MediaRenditions } from './rendition';\n\nexport { essenceOf };\n\nimport type {\n\tMaybePromise,\n\tMediaQuota,\n\tMediaThrottle,\n\tMediaUploadIntent,\n\tThrottleDecision,\n} from './kind-callbacks';\n\nexport type { MediaUploadIntent, ThrottleDecision };\n\n/** What a kind's callbacks read: the request's context, and what the app's middlewares added before the routes. */\nexport type MediaContext<Requires extends object = Empty> = BaseContext &\n\tRequires;\n\ninterface KindBase<Requires extends object> {\n\t/**\n\t * The kind's name: a URL segment and the bucket's folder\n\t * (`<name>/<key>`). Lower-case words and digits joined by hyphens.\n\t */\n\treadonly name: string;\n\t/**\n\t * The content types an upload may have, exact (`image/png`), no partial\n\t * wildcard. `'*'` alone takes any type: a type with a known signature is\n\t * checked against it, any other is stored as declared (`application/octet-stream`\n\t * when the upload declares none), and a file whose type is not an\n\t * inline-safe one (image, audio, video, PDF, plain text) is served as\n\t * `application/octet-stream` with `Content-Disposition: attachment`.\n\t */\n\treadonly accept: readonly string[] | typeof ANY_TYPE;\n\t/** The most bytes an upload may have. */\n\treadonly maxBytes: number;\n\t/**\n\t * Whether the caller may upload this kind; `false` is a 403. It may\n\t * answer a `MediaDenial` instead (`{ code: 'quota', status: 402 }`).\n\t */\n\treadonly authorizeWrite: (\n\t\tctx: MediaContext<Requires>,\n\t) => MaybePromise<MediaVerdict>;\n\t/**\n\t * Whether the caller may delete a file of this kind. Declaring it mounts\n\t * `DELETE <prefix>/<kind>/<key>`; `false` is a 403. Without it, no DELETE.\n\t * It may answer a `MediaDenial` instead, a refusal of the app's own with\n\t * its status: `{ code: 'in_use', status: 409 }` when a record still\n\t * points at the file.\n\t */\n\treadonly authorizeDelete?: (\n\t\tctx: MediaContext<Requires>,\n\t\tkey: MediaKey,\n\t) => MaybePromise<MediaVerdict>;\n\t/**\n\t * Called once the upload is permitted, before a byte of the body is read:\n\t * count it against the account's limit here. See `ThrottleDecision`.\n\t */\n\treadonly throttle?: MediaThrottle<MediaContext<Requires>>;\n\t/**\n\t * Called after the type and declared-length checks, before a byte of the\n\t * body is read: refuse an upload over a storage quota here. See\n\t * `MediaQuota`; `false` is a 403, a `MediaDenial` is answered as it says.\n\t */\n\treadonly quota?: MediaQuota<MediaContext<Requires>>;\n\t/**\n\t * Named renditions stored beside the file (`<kind>/<key>/<size>`), served\n\t * by `GET <prefix>/<kind>/<key>/<size>`. A `GET` never makes one: the\n\t * upload does, through `renditions`, or the app writes them (names alone,\n\t * on any kind, `accept: '*'` included: a worker stores each at\n\t * `mediaPlace(kind, prefix)(key, size)`). A size not listed, or listed and\n\t * not written yet, is a 404; the stored object's own type and ETag are served.\n\t */\n\treadonly sizes?: readonly string[];\n\t/**\n\t * What each upload is made into, stored under its `sizes` before the\n\t * `PUT` answers. `withImageRendition` from `@softistx/alxia-media/image` gives one.\n\t */\n\treadonly renditions?: MediaRenditions;\n\t/**\n\t * Whether the uploaded file itself is stored (default `true`). `false`\n\t * stores the renditions alone: the body is held in memory (up to\n\t * `maxBytes`), handed to `renditions`, and never written, so its\n\t * metadata (EXIF, GPS) never reaches the bucket; `GET <kind>/<key>` is a\n\t * 404 and only the sizes are served. Needs `renditions`.\n\t *\n\t * A list of accepted types keeps the original of those types only, for\n\t * a kind that takes images and PDFs: `keepOriginal: ['application/pdf']`\n\t * stores the PDF's bytes and, for an image, only its renditions. See\n\t * `renditionTypes` for the types `renditions` is run on.\n\t */\n\treadonly keepOriginal?: boolean | readonly string[];\n\t/**\n\t * The accepted types `renditions` is made from; the others are not\n\t * handed to it. By default every accepted type, or, with a `keepOriginal`\n\t * list, the accepted types that list leaves out (a PDF kept as it is,\n\t * with no picture made of it). Every accepted type must be kept or listed\n\t * here, or an upload of it would store nothing.\n\t */\n\treadonly renditionTypes?: readonly string[];\n\t/**\n\t * Forces `Content-Disposition: attachment` on this kind's files and sizes,\n\t * so the browser downloads them instead of showing them: `true` for every\n\t * type, or a list of accepted types (`['application/pdf']`). Without it, a\n\t * PDF is served inline (under a sandbox CSP) and an image shows in the\n\t * page; a type this package does not serve inline is always an attachment.\n\t */\n\treadonly attachment?: boolean | readonly string[];\n\t/**\n\t * The `Cache-Control` of this kind's 200, 206 and 304 answers. By default\n\t * `private, max-age=31536000, immutable` (`public, …` for a public kind).\n\t * For content a reader may lose access to, `'private, no-cache'` makes the\n\t * browser revalidate on every use: `authorizeRead` runs each time, and the\n\t * ETag lets it answer a cheap 304. Refusals stay `no-store`.\n\t */\n\treadonly cacheControl?: string;\n\t/**\n\t * Whether an upload's first bytes must be those of its declared type\n\t * (default `true`, which refuses a kind accepting a type with no\n\t * signature). `'known'` checks the types this package has a signature\n\t * for and takes the others in `accept` as declared (docx, xlsx, ...).\n\t * `false` checks none.\n\t */\n\treadonly sniff?: boolean | 'known';\n}\n\n/** What `defineMediaKind` takes: a private kind names who may read; a public one says so. */\nexport type MediaKindInput<Requires extends object = Empty> =\n\tKindBase<Requires> &\n\t\t(\n\t\t\t| {\n\t\t\t\t\treadonly public?: false;\n\t\t\t\t\t/**\n\t\t\t\t\t * Whether the caller may read the file under `key`. `false` is a\n\t\t\t\t\t * 404, the answer for a file that is not there. A `MediaDenial` is\n\t\t\t\t\t * answered as it says.\n\t\t\t\t\t */\n\t\t\t\t\treadonly authorizeRead: (\n\t\t\t\t\t\tctx: MediaContext<Requires>,\n\t\t\t\t\t\tkey: MediaKey,\n\t\t\t\t\t) => MaybePromise<MediaVerdict>;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\t/** Anyone may read it, with no check: served `public`, readable cross-origin. */\n\t\t\t\t\treadonly public: true;\n\t\t\t\t\treadonly authorizeRead?: undefined;\n\t\t\t }\n\t\t);\n\n/** A kind, as `mediaRoutes` takes it. */\nexport interface MediaKind<Requires extends object = Empty> {\n\treadonly name: string;\n\t/** The accepted types, or `['*']` for a kind that takes any. */\n\treadonly accept: readonly string[];\n\treadonly maxBytes: number;\n\treadonly public: boolean;\n\treadonly sniff: boolean | 'known';\n\treadonly sizes: readonly string[];\n\treadonly renditions: MediaRenditions | undefined;\n\t/** Whether every file's original is stored (`false` for a `keepOriginal` list or `false`). */\n\treadonly keepOriginal: boolean;\n\t/** The types whose original is stored when `keepOriginal` is `false`. */\n\treadonly keepOriginalTypes: readonly string[];\n\t/** The types `renditions` is made from. */\n\treadonly renditionTypes: readonly string[];\n\t/** The types always served as an attachment, or `true` for all. */\n\treadonly attachment: boolean | readonly string[];\n\t/** The kind's own `Cache-Control`, or `undefined` for the default. */\n\treadonly cacheControl: string | undefined;\n\treadonly authorizeWrite: (\n\t\tctx: MediaContext<Requires>,\n\t) => MaybePromise<MediaVerdict>;\n\treadonly authorizeRead: (\n\t\tctx: MediaContext<Requires>,\n\t\tkey: MediaKey,\n\t) => MaybePromise<MediaVerdict>;\n\treadonly authorizeDelete:\n\t\t| ((\n\t\t\t\tctx: MediaContext<Requires>,\n\t\t\t\tkey: MediaKey,\n\t\t ) => MaybePromise<MediaVerdict>)\n\t\t| undefined;\n\treadonly throttle: MediaThrottle<MediaContext<Requires>> | undefined;\n\treadonly quota: MediaQuota<MediaContext<Requires>> | undefined;\n}\n\n/** The normalised `keepOriginal`, `renditionTypes` and `attachment` of a kind. */\nfunction storage(\n\twhere: string,\n\tinput: Pick<\n\t\tKindBase<never>,\n\t\t'keepOriginal' | 'renditionTypes' | 'attachment' | 'renditions'\n\t>,\n\taccept: readonly string[],\n): {\n\tkeepOriginal: boolean | string[];\n\trenditionTypes: string[];\n\tattachment: boolean | string[];\n} {\n\tconst listed = (option: string, value: unknown): string[] => {\n\t\tif (!Array.isArray(value)) {\n\t\t\tthrow new TypeError(`${where}: ${option} must be a list of types`);\n\t\t}\n\t\tconst types = value.map((type) => essenceOf(String(type)));\n\t\tfor (const type of types) {\n\t\t\tif (!accept.includes(type)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: ${option} lists ${type}, which accept does not take`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn [...new Set(types)];\n\t};\n\tconst {\n\t\tkeepOriginal: kept,\n\t\trenditionTypes: made,\n\t\tattachment: forced,\n\t} = input;\n\tlet keepOriginal: boolean | string[] = true;\n\tif (Array.isArray(kept)) {\n\t\tkeepOriginal = listed('keepOriginal', kept);\n\t\tif (keepOriginal.length === 0) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: keepOriginal lists no type; use false to store no original`,\n\t\t\t);\n\t\t}\n\t} else if (kept === false) {\n\t\tkeepOriginal = false;\n\t} else if (kept !== undefined && kept !== true) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: keepOriginal must be a boolean or a list of types`,\n\t\t);\n\t}\n\tconst every = acceptsAny(accept) ? [] : accept;\n\tconst renditionTypes =\n\t\tmade === undefined\n\t\t\t? every.filter(\n\t\t\t\t\t(type) =>\n\t\t\t\t\t\t!Array.isArray(keepOriginal) || !keepOriginal.includes(type),\n\t\t\t\t)\n\t\t\t: listed('renditionTypes', made);\n\tif (keepOriginal !== true && input.renditions === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: keepOriginal: false needs renditions, or nothing would be stored`,\n\t\t);\n\t}\n\tif (keepOriginal !== true) {\n\t\tconst kept = Array.isArray(keepOriginal) ? keepOriginal : [];\n\t\tfor (const type of every) {\n\t\t\tif (!kept.includes(type) && !renditionTypes.includes(type)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`${where}: an upload of ${type} would store nothing: keep it in keepOriginal or list it in renditionTypes`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tlet attachment: boolean | string[] = false;\n\tif (Array.isArray(forced)) attachment = listed('attachment', forced);\n\telse if (forced === true) attachment = true;\n\telse if (forced !== undefined && forced !== false) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: attachment must be a boolean or a list of types`,\n\t\t);\n\t}\n\treturn { keepOriginal, renditionTypes, attachment };\n}\n\n/** Whether an upload of `type` to `kind` stores its own bytes. */\nexport function keepsOriginal(kind: MediaKind<never>, type: string): boolean {\n\treturn kind.keepOriginal || kind.keepOriginalTypes.includes(type);\n}\n\n/**\n * A kind of file: its name, the types and size it takes, and who may\n * write, read and delete it. Throws at declaration on anything that would\n * make the routes unsafe: a bad name, an empty `accept`, a type this package\n * cannot sniff (unless `sniff: false` or `'known'`), a limit that is not a positive\n * integer.\n *\n * ```ts\n * const avatars = defineMediaKind<{ viewer: Viewer }>({\n * name: 'avatars',\n * accept: ['image/png', 'image/jpeg', 'image/webp'],\n * maxBytes: 2 * 1024 * 1024,\n * authorizeWrite: ({ viewer }) => viewer.canUpload,\n * authorizeRead: () => true,\n * });\n * ```\n */\nexport function defineMediaKind<Requires extends object = Empty>(\n\tinput: MediaKindInput<Requires>,\n): MediaKind<Requires> {\n\tif (!isMediaKindName(input.name)) {\n\t\tthrow new TypeError(\n\t\t\t`defineMediaKind(): the name ${JSON.stringify(input.name)} must be lower-case words and digits joined by hyphens, starting with a letter`,\n\t\t);\n\t}\n\tconst where = `defineMediaKind(${JSON.stringify(input.name)})`;\n\tif (!Number.isSafeInteger(input.maxBytes) || input.maxBytes < 1) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: maxBytes must be a whole number of bytes, 1 or more`,\n\t\t);\n\t}\n\tconst sniff = input.sniff ?? true;\n\tconst accept = checkAccept(where, input.accept, sniff);\n\tconst sizes = input.sizes ?? [];\n\tfor (const size of sizes) {\n\t\tif (!isMediaSize(size)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${where}: the size ${JSON.stringify(size)} is not a name`,\n\t\t\t);\n\t\t}\n\t}\n\tif (acceptsAny(accept) && input.renditions) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: accept: '*' takes no renditions, they need the types they are made from; sizes alone are fine, the app writes them`,\n\t\t);\n\t}\n\tcheckRenditions(where, sizes, input.renditions);\n\tconst { keepOriginal, renditionTypes, attachment } = storage(\n\t\twhere,\n\t\tinput,\n\t\taccept,\n\t);\n\tif (\n\t\tinput.cacheControl !== undefined &&\n\t\t(typeof input.cacheControl !== 'string' ||\n\t\t\tinput.cacheControl.trim() === '' ||\n\t\t\t/[\\r\\n]/.test(input.cacheControl))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`${where}: cacheControl must be a non-empty Cache-Control value on one line`,\n\t\t);\n\t}\n\tconst isPublic = input.public === true;\n\tif (!isPublic && typeof input.authorizeRead !== 'function') {\n\t\tthrow new TypeError(`${where}: give authorizeRead, or public: true`);\n\t}\n\treturn {\n\t\tname: input.name,\n\t\taccept: [...new Set(accept)],\n\t\tmaxBytes: input.maxBytes,\n\t\tpublic: isPublic,\n\t\tsniff,\n\t\tsizes: [...sizes],\n\t\trenditions: input.renditions,\n\t\tkeepOriginal: keepOriginal === true,\n\t\tkeepOriginalTypes: Array.isArray(keepOriginal) ? keepOriginal : [],\n\t\trenditionTypes,\n\t\tattachment,\n\t\tcacheControl: input.cacheControl,\n\t\tauthorizeWrite: input.authorizeWrite,\n\t\tauthorizeRead: input.authorizeRead ?? (() => true),\n\t\tauthorizeDelete: input.authorizeDelete,\n\t\tthrottle: input.throttle,\n\t\tquota: input.quota,\n\t};\n}\n",
|
|
9
|
+
"/** `mediaRoutes`: the routes that serve and accept the files of some kinds. */\n\nimport {\n\ttype AnyReply,\n\ttype BaseContext,\n\tdefinePlugin,\n\ttype Empty,\n\tmarkFactory,\n\ttype RoutePath,\n} from '@softistx/alxia';\nimport { type MediaBucket, refusalOfFailure } from './bucket';\nimport { checkedPrefix, type MediaPlace, mediaPlace } from './key';\nimport type { MediaContext, MediaKind } from './kind';\nimport { serve } from './read';\nimport { type MediaRefusal, refusalReply } from './refusal';\nimport { type MediaUploaded, remove, upload } from './write';\n\n/** What `mediaRoutes` takes beside the kinds. */\nexport interface MediaRoutesOptions<Requires extends object = Empty> {\n\t/** The private bucket the files live in. */\n\treadonly bucket: MediaBucket;\n\t/** Where the routes are mounted: `/media` by default. */\n\treadonly prefix?: RoutePath;\n\t/** How long the bucket may take to start answering a read, in ms: 10 000 by default. */\n\treadonly readTimeoutMs?: number;\n\t/**\n\t * The idle deadline of an upload, in ms: it starts over after each chunk,\n\t * so a slow upload that keeps moving is never cut. 60 000 by default.\n\t */\n\treadonly writeTimeoutMs?: number;\n\t/**\n\t * Answers a refusal in the app's own format. Return `undefined` to leave\n\t * it to the default (`{ error: code }`, or an RFC 9457 problem when the\n\t * app is configured for them).\n\t */\n\treadonly refusal?: (\n\t\trefusal: MediaRefusal,\n\t\tctx: BaseContext,\n\t) => AnyReply | undefined;\n\t/**\n\t * Folders every object of the request lives under, from the request\n\t * (`tenants/<id>`): the bucket key is `<prefix>/<kind>/<key>[/<size>]`\n\t * on writes, reads and deletes alike, so a request can only reach the\n\t * objects of its own prefix. Called once per request, before the kind's\n\t * `authorize*`; it may throw a `MediaRefusal` (a `forbidden` when the\n\t * request has no tenant). `undefined` or `''` means no prefix. Segments\n\t * are letters, digits and `. _ = -` joined by `/`, else a `TypeError`.\n\t */\n\treadonly keyPrefix?: (\n\t\tctx: MediaContext<Requires>,\n\t\tkind: string,\n\t) => string | undefined | Promise<string | undefined>;\n\t/**\n\t * Shapes the body of a successful upload (default: `{ key, contentType,\n\t * size }`). Called once the file and its renditions are stored; what it\n\t * returns is the 200's JSON body. If it throws, what was stored is\n\t * removed and the error is answered as any other.\n\t */\n\treadonly uploaded?: (\n\t\tuploaded: MediaUploaded,\n\t\tctx: MediaContext<Requires>,\n\t) => unknown;\n}\n\ntype Handler = (ctx: MediaContext<object>) => unknown;\ninterface Declaring {\n\tget(path: string, handler: Handler): unknown;\n\tput(path: string, handler: Handler): unknown;\n\tdelete(path: string, handler: Handler): unknown;\n}\n\n/**\n * The routes of some kinds, as a plugin:\n *\n * - `PUT <prefix>/<kind>` the raw body in, `{ key, contentType, size }` out (or what `uploaded` makes of it);\n * - `GET <prefix>/<kind>/<key>` the file, with Range, ETag and 304;\n * - `GET <prefix>/<kind>/<key>/<size>` a named rendition, for a kind that lists `sizes`;\n * - `DELETE <prefix>/<kind>/<key>` for a kind that declares `authorizeDelete`.\n *\n * Mount it after the middlewares that authenticate: the kinds' callbacks read\n * what they add. Keys are returned, never URLs.\n *\n * ```ts\n * const app = alxia()\n * .plugin(auth)\n * .plugin(mediaRoutes([avatars], { bucket }));\n * ```\n */\nexport function mediaRoutes<Requires extends object = Empty>(\n\tkinds: readonly MediaKind<Requires>[],\n\toptions: MediaRoutesOptions<Requires>,\n) {\n\tconst prefix = (options.prefix ?? '/media').replace(/\\/+$/, '');\n\tif (!prefix.startsWith('/')) {\n\t\tthrow new TypeError(`mediaRoutes(): prefix ${prefix} must start with \"/\"`);\n\t}\n\tconst names = new Set<string>();\n\tfor (const kind of kinds) {\n\t\tif (names.has(kind.name)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`mediaRoutes(): the kind ${kind.name} is given twice`,\n\t\t\t);\n\t\t}\n\t\tnames.add(kind.name);\n\t}\n\tconst context: RouteContext = {\n\t\tprefix,\n\t\tbucket: options.bucket,\n\t\treadTimeoutMs: options.readTimeoutMs ?? 10_000,\n\t\twriteTimeoutMs: options.writeTimeoutMs ?? 60_000,\n\t\trefusal: options.refusal,\n\t\t// The routes run on `MediaContext<object>`: `Requires` is only the app's typing of the hooks.\n\t\tkeyPrefix: options.keyPrefix as RouteContext['keyPrefix'],\n\t\tuploaded: options.uploaded as RouteContext['uploaded'],\n\t};\n\n\treturn definePlugin<Requires>()((app) => {\n\t\tconst routes = app as unknown as Declaring;\n\t\tfor (const kind of kinds) {\n\t\t\tdeclareKind(routes, kind as unknown as MediaKind<object>, context);\n\t\t}\n\t\treturn app;\n\t});\n}\n\nmarkFactory(mediaRoutes, 'plugin');\n\n/** What every route of every kind shares: data only. */\ninterface RouteContext {\n\treadonly prefix: string;\n\treadonly bucket: MediaBucket;\n\treadonly readTimeoutMs: number;\n\treadonly writeTimeoutMs: number;\n\treadonly refusal: MediaRoutesOptions['refusal'];\n\treadonly keyPrefix: MediaRoutesOptions<object>['keyPrefix'];\n\treadonly uploaded: MediaRoutesOptions<object>['uploaded'];\n}\n\n/** Where this request's objects of `kind` live. */\nasync function placeOf(\n\tcontext: RouteContext,\n\tkind: MediaKind<object>,\n\tctx: MediaContext<object>,\n): Promise<MediaPlace> {\n\tconst prefix = await context.keyPrefix?.(ctx, kind.name);\n\treturn mediaPlace(\n\t\tkind.name,\n\t\tcheckedPrefix(prefix),\n\t\tkind.renditions?.keyExtension,\n\t);\n}\n\n/** A handler whose refusals are answered, not thrown. */\nfunction guarded(\n\tcontext: RouteContext,\n\tkind: MediaKind<object>,\n\trun: (ctx: MediaContext<object>) => Promise<AnyReply>,\n): Handler {\n\treturn async (ctx) => {\n\t\ttry {\n\t\t\treturn await run(ctx);\n\t\t} catch (error) {\n\t\t\tconst refusal = refusalOfFailure(error, kind as MediaKind<never>);\n\t\t\tif (refusal === undefined) throw error;\n\t\t\treturn context.refusal?.(refusal, ctx) ?? refusalReply(ctx, refusal);\n\t\t}\n\t};\n}\n\n/** The routes of one kind. */\nfunction declareKind(\n\troutes: Declaring,\n\tkind: MediaKind<object>,\n\tcontext: RouteContext,\n): void {\n\tconst { prefix, bucket, readTimeoutMs, writeTimeoutMs } = context;\n\tconst base = `${prefix}/${kind.name}`;\n\tconst read = (size: boolean) =>\n\t\tguarded(context, kind, async (ctx) =>\n\t\t\tserve(\n\t\t\t\tctx,\n\t\t\t\tkind,\n\t\t\t\tbucket,\n\t\t\t\t{\n\t\t\t\t\tkey: ctx.pathParams['key'],\n\t\t\t\t\tsize: size ? ctx.pathParams['size'] : undefined,\n\t\t\t\t},\n\t\t\t\treadTimeoutMs,\n\t\t\t\tawait placeOf(context, kind, ctx),\n\t\t\t),\n\t\t);\n\troutes.put(\n\t\tbase,\n\t\tguarded(context, kind, async (ctx) => {\n\t\t\tconst place = await placeOf(context, kind, ctx);\n\t\t\tconst { uploaded } = context;\n\t\t\tconst body = await upload(\n\t\t\t\tctx,\n\t\t\t\tkind,\n\t\t\t\t{ bucket, timeoutMs: writeTimeoutMs, place },\n\t\t\t\tuploaded && ((result) => uploaded(result, ctx)),\n\t\t\t);\n\t\t\treturn ctx.reply(200, body);\n\t\t}),\n\t);\n\troutes.get(`${base}/:key`, read(false));\n\tif (kind.sizes.length > 0) routes.get(`${base}/:key/:size`, read(true));\n\tif (kind.authorizeDelete !== undefined) {\n\t\troutes.delete(\n\t\t\t`${base}/:key`,\n\t\t\tguarded(context, kind, async (ctx) =>\n\t\t\t\tremove(ctx, kind, ctx.pathParams['key'], {\n\t\t\t\t\tbucket,\n\t\t\t\t\ttimeoutMs: writeTimeoutMs,\n\t\t\t\t\tplace: await placeOf(context, kind, ctx),\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t}\n}\n",
|
|
10
|
+
"/** What the routes need of a bucket, and how its failures become refusals. */\n\nimport { type BoundBucket, isBucketUnavailable, S3Error } from '@softistx/s3';\nimport type { MediaKind } from './kind';\nimport { isMediaRefusal, MediaRefusal } from './refusal';\n\n/**\n * The bucket the files live in: an `@softistx/s3` store bound with a key\n * made of the `key` it is given. It stays private: nothing here signs a URL.\n *\n * ```ts\n * const bucket = bindBucket(\n * defineBucket({ bucket: 'media', key: (p: { key: string }) => p.key }),\n * options,\n * );\n * ```\n */\nexport type MediaBucket = Pick<\n\tBoundBucket<{ readonly key: string }>,\n\t'open' | 'put' | 'delete'\n>;\n\n/** A failure of the bucket, as the refusal it is; anything else comes back as it is. */\nexport function refusalOfFailure(\n\terror: unknown,\n\tkind: MediaKind<never>,\n): MediaRefusal | undefined {\n\tif (isMediaRefusal(error)) return error;\n\tif (error instanceof S3Error) {\n\t\tswitch (error.code) {\n\t\t\tcase 'RANGE_NOT_SATISFIABLE':\n\t\t\t\treturn new MediaRefusal(\n\t\t\t\t\t'range_not_satisfiable',\n\t\t\t\t\terror.objectSize === undefined ? {} : { size: error.objectSize },\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\tcase 'TOO_LARGE':\n\t\t\t\treturn new MediaRefusal(\n\t\t\t\t\t'too_large',\n\t\t\t\t\t{ limit: kind.maxBytes },\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\tcase 'SIZE_MISMATCH':\n\t\t\t\treturn new MediaRefusal('size_mismatch', {}, { cause: error });\n\t\t\tcase 'SOURCE_FAILED':\n\t\t\t\treturn new MediaRefusal('interrupted', {}, { cause: error });\n\t\t}\n\t}\n\tif (isBucketUnavailable(error)) {\n\t\treturn new MediaRefusal('unavailable', {}, { cause: error });\n\t}\n\treturn undefined;\n}\n",
|
|
11
|
+
"/** `GET`: a stored file streamed to the client, with Range, ETag and 304. */\n\nimport type { AnyReply } from '@softistx/alxia';\nimport { type OpenedObject, S3Error } from '@softistx/s3';\nimport type { MediaBucket } from './bucket';\nimport { mediaHeaders } from './headers';\nimport { isMediaKey, type MediaPlace } from './key';\nimport type { MediaContext, MediaKind } from './kind';\nimport { matchesEtag, parseRange, type RequestedRange } from './range';\nimport { MediaRefusal, refusalOfVerdict } from './refusal';\n\nconst notFound = () => new MediaRefusal('not_found');\n\nconst s3Range = (range: RequestedRange | undefined) => {\n\tif (range === undefined) return undefined;\n\tif ('suffix' in range) return { suffix: range.suffix };\n\treturn range.end === undefined\n\t\t? { start: range.start }\n\t\t: { start: range.start, end: range.end + 1 };\n};\n\n/** What serving one file needs once its key and its caller are checked. */\ninterface Serving {\n\treadonly ctx: MediaContext<object>;\n\treadonly kind: MediaKind<object>;\n\t/** Whether a size is read, not the file: its type may be one `renditions` make. */\n\treadonly sized: boolean;\n\treadonly open: (\n\t\twanted: RequestedRange | undefined,\n\t) => Promise<OpenedObject | undefined>;\n\treadonly ifNoneMatch: string | null;\n\treadonly ifRange: string | null;\n}\n\n/** A conditional request is answered from the headers alone: the body is never read. */\nasync function notModified(\n\t{ ctx, kind, sized, ifNoneMatch }: Serving,\n\tfound: OpenedObject,\n): Promise<AnyReply | undefined> {\n\tif (!matchesEtag(ifNoneMatch, found.eTag ?? '')) return undefined;\n\tawait found.stream.cancel();\n\tconst out = mediaHeaders(kind, found, sized);\n\tfor (const name of ['content-type', 'accept-ranges', 'content-disposition']) {\n\t\tout.delete(name);\n\t}\n\treturn ctx.reply(304, undefined, { headers: out });\n}\n\nconst mismatched = (ifRange: string | null, object: OpenedObject): boolean =>\n\tifRange !== null &&\n\t(object.eTag === undefined || ifRange.trim() !== object.eTag);\n\n/**\n * A Range the object cannot satisfy: the whole file decides. A matching\n * If-None-Match is a 304 (RFC 9110 13.2.2); an If-Range that is not the\n * file's ETag voids the Range, so the answer is the whole file, a 200 (13.1.5);\n * otherwise the Range stands and `unsatisfiable()` throws the 416.\n */\nasync function whole(\n\tserving: Serving,\n\tunsatisfiable: (size: number | undefined) => never,\n): Promise<{ readonly object: OpenedObject } | { readonly reply: AnyReply }> {\n\tconst all = await serving.open(undefined);\n\tif (all === undefined) throw notFound();\n\tconst same = await notModified(serving, all);\n\tif (same !== undefined) return { reply: same };\n\tif (mismatched(serving.ifRange, all)) return { object: all };\n\tawait all.stream.cancel();\n\treturn unsatisfiable(all.size);\n}\n\n/**\n * The object for `range`, or the reply that answers before it.\n * If-None-Match is evaluated before Range (RFC 9110 13.2.2): a matching\n * ETag with an unsatisfiable range is a 304, not a 416.\n */\nasync function opening(\n\tserving: Serving,\n\trange: RequestedRange | undefined,\n): Promise<{ readonly object: OpenedObject } | { readonly reply: AnyReply }> {\n\t// `bytes=-0` asks for no byte at all: unsatisfiable, and only the size says by how much.\n\tif (range !== undefined && 'suffix' in range && range.suffix === 0) {\n\t\treturn whole(serving, (size) => {\n\t\t\tthrow new MediaRefusal(\n\t\t\t\t'range_not_satisfiable',\n\t\t\t\tsize === undefined ? {} : { size },\n\t\t\t);\n\t\t});\n\t}\n\tlet object: OpenedObject | undefined;\n\ttry {\n\t\tobject = await serving.open(range);\n\t} catch (error) {\n\t\tif (\n\t\t\t(serving.ifNoneMatch !== null || serving.ifRange !== null) &&\n\t\t\terror instanceof S3Error &&\n\t\t\terror.code === 'RANGE_NOT_SATISFIABLE'\n\t\t) {\n\t\t\treturn whole(serving, () => {\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\tthrow error;\n\t}\n\tif (object === undefined) throw notFound();\n\tconst same = await notModified(serving, object);\n\treturn same === undefined ? { object } : { reply: same };\n}\n\n/** The file, whole (200) or a range of it (206). */\nfunction streamed(\n\t{ ctx, kind, sized }: Serving,\n\topened: OpenedObject,\n): AnyReply {\n\tconst out = mediaHeaders(kind, opened, sized);\n\tif (opened.contentRange !== undefined) {\n\t\tout.set('content-range', opened.contentRange);\n\t\tif (opened.contentLength !== undefined) {\n\t\t\tout.set('content-length', String(opened.contentLength));\n\t\t}\n\t\treturn ctx.reply(206, opened.stream, { headers: out });\n\t}\n\tconst length = opened.size ?? opened.contentLength;\n\tif (length !== undefined) out.set('content-length', String(length));\n\treturn ctx.reply(200, opened.stream, { headers: out });\n}\n\n/** Throws a refusal for anything that is not a file this caller may read. */\nexport async function serve(\n\tctx: MediaContext<object>,\n\tkind: MediaKind<object>,\n\tbucket: MediaBucket,\n\traw: { key: string | undefined; size: string | undefined },\n\ttimeoutMs: number,\n\tplace: MediaPlace,\n): Promise<AnyReply> {\n\tconst { key, size } = raw;\n\tif (!isMediaKey(key)) throw notFound();\n\tif (size !== undefined && !kind.sizes.includes(size)) throw notFound();\n\tif (!kind.public) {\n\t\tconst denied = refusalOfVerdict(\n\t\t\tawait kind.authorizeRead(ctx, key),\n\t\t\tnotFound(),\n\t\t);\n\t\tif (denied !== undefined) throw denied;\n\t}\n\n\tconst params = { key: place(key, size) };\n\tconst headers = ctx.request.headers;\n\tconst range = parseRange(headers.get('range'));\n\tconst serving: Serving = {\n\t\tctx,\n\t\tkind,\n\t\tsized: size !== undefined,\n\t\tifNoneMatch: headers.get('if-none-match'),\n\t\tifRange: headers.get('if-range'),\n\t\topen: (wanted) =>\n\t\t\tbucket.open(params, {\n\t\t\t\ttimeoutMs,\n\t\t\t\t...(wanted !== undefined && { range: s3Range(wanted) }),\n\t\t\t}),\n\t};\n\tconst first = await opening(serving, range);\n\tif ('reply' in first) return first.reply;\n\tlet opened = first.object;\n\n\t// If-Range: the range holds only for the version the client has; keys are\n\t// immutable, so a mismatch is a client holding something else: the whole file.\n\tif (\n\t\trange !== undefined &&\n\t\topened.contentRange !== undefined &&\n\t\tmismatched(serving.ifRange, opened)\n\t) {\n\t\tawait opened.stream.cancel();\n\t\tconst whole = await serving.open(undefined);\n\t\tif (whole === undefined) throw notFound();\n\t\topened = whole;\n\t}\n\treturn streamed(serving, opened);\n}\n",
|
|
12
|
+
"/** The headers of a served file. */\n\nimport type { OpenedObject } from '@softistx/s3';\nimport type { MediaKind } from './kind';\nimport { acceptsAny } from './kind-check';\nimport { canSniff } from './sniff';\n\n/** A year: a key is fresh per upload, so what is under it never changes. */\nconst YEAR = 31_536_000;\n\n/** What a bucket reports for an object put with no type. */\nconst UNTYPED = new Set(['application/octet-stream', 'binary/octet-stream']);\n\n/** The types a browser may show in the page itself; the others are downloaded. */\nconst INLINE = new Set(['application/pdf']);\n\n/**\n * What a kind that takes any type shows in the page: the types this package\n * knows a signature for (raster images, audio, video, PDF) and plain text,\n * by exact name. Any other, `+xml` and SVG types included, is a download.\n */\nconst isInlineSafe = (type: string) => canSniff(type) || type === 'text/plain';\n\n/**\n * The type a file is served as: the one stored if the kind accepts it (or,\n * for a size, if its `renditions` make it; a size the app wrote, with no `renditions`, keeps its stored type when it is inline-safe), else, for an object stored without a type,\n * the kind's only type, else bytes.\n */\nexport function servedType(\n\tkind: MediaKind<never>,\n\tstored: string | undefined,\n\tsized = false,\n): { type: string; known: boolean } {\n\tconst essence = (stored ?? '').split(';')[0]?.trim().toLowerCase() ?? '';\n\tconst made = sized ? (kind.renditions?.types ?? []) : [];\n\t// A size the app wrote itself (no `renditions`) is trusted for its stored type, as a wildcard kind's files are.\n\tconst appWritten = sized && kind.renditions === undefined;\n\tif (\n\t\tacceptsAny(kind.accept) ||\n\t\t(appWritten && essence !== '' && isInlineSafe(essence))\n\t) {\n\t\treturn essence !== '' && isInlineSafe(essence)\n\t\t\t? { type: essence, known: true }\n\t\t\t: { type: 'application/octet-stream', known: false };\n\t}\n\tif (\n\t\tessence !== '' &&\n\t\t(kind.accept.includes(essence) || made.includes(essence))\n\t) {\n\t\treturn { type: essence, known: true };\n\t}\n\t// Only an object stored without a type (a bucket gives none a generic\n\t// binary type) takes the kind's single type; one stored as another type\n\t// stays bytes to download.\n\tif (\n\t\t(essence === '' || UNTYPED.has(essence)) &&\n\t\tkind.accept.length === 1 &&\n\t\tkind.accept[0] !== undefined\n\t) {\n\t\treturn { type: kind.accept[0], known: true };\n\t}\n\treturn { type: 'application/octet-stream', known: false };\n}\n\n/**\n * The headers every answer about a file carries: how long it is kept, that\n * the browser must not guess its type, who may embed it, and a CSP that\n * leaves a document opened directly no script and no network.\n */\nexport function mediaHeaders(\n\tkind: MediaKind<never>,\n\topened: Pick<OpenedObject, 'eTag' | 'lastModified' | 'contentType'>,\n\tsized = false,\n): Headers {\n\tconst headers = new Headers();\n\tconst { type, known } = servedType(kind, opened.contentType, sized);\n\theaders.set('content-type', type);\n\theaders.set(\n\t\t'cache-control',\n\t\tkind.cacheControl ??\n\t\t\t(kind.public\n\t\t\t\t? `public, max-age=${YEAR}, immutable`\n\t\t\t\t: `private, max-age=${YEAR}, immutable`),\n\t);\n\theaders.set('x-content-type-options', 'nosniff');\n\theaders.set(\n\t\t'cross-origin-resource-policy',\n\t\tkind.public ? 'cross-origin' : 'same-origin',\n\t);\n\theaders.set('content-security-policy', \"sandbox; default-src 'none'\");\n\theaders.set('accept-ranges', 'bytes');\n\tconst forced =\n\t\tkind.attachment === true ||\n\t\t(Array.isArray(kind.attachment) && kind.attachment.includes(type));\n\tif (!known || forced) headers.set('content-disposition', 'attachment');\n\telse if (INLINE.has(type)) headers.set('content-disposition', 'inline');\n\tif (opened.eTag) headers.set('etag', opened.eTag);\n\tif (opened.lastModified) {\n\t\theaders.set('last-modified', opened.lastModified.toUTCString());\n\t}\n\treturn headers;\n}\n",
|
|
13
|
+
"/** `Range` request headers, one byte range of them. */\n\n/** A byte range as the header asked for it; `end` is inclusive, as written. */\nexport type RequestedRange =\n\t| { readonly start: number; readonly end?: number }\n\t| { readonly suffix: number };\n\n/**\n * The range `Range: bytes=…` asks for, or `undefined` to serve the whole\n * object: no header, another unit, several ranges and a malformed spec are\n * all ignored, which HTTP allows (RFC 9110 14.2), never refused.\n */\nexport function parseRange(header: string | null): RequestedRange | undefined {\n\tif (header === null) return undefined;\n\tconst match = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim());\n\tif (!match) return undefined;\n\tconst [, first = '', last = ''] = match;\n\tif (first === '') {\n\t\tif (last === '') return undefined;\n\t\tconst suffix = Number(last);\n\t\treturn Number.isSafeInteger(suffix) ? { suffix } : undefined;\n\t}\n\tconst start = Number(first);\n\tif (!Number.isSafeInteger(start)) return undefined;\n\tif (last === '') return { start };\n\tconst end = Number(last);\n\tif (!Number.isSafeInteger(end) || end < start) return undefined;\n\treturn { start, end };\n}\n\n/** `ETag` list matching for `If-None-Match`: weak comparison, `*` matches. */\nexport function matchesEtag(header: string | null, etag: string): boolean {\n\tif (header === null) return false;\n\tconst strip = (tag: string) => tag.trim().replace(/^W\\//, '');\n\tconst mine = strip(etag);\n\treturn header\n\t\t.split(',')\n\t\t.some((tag) => strip(tag) === '*' || strip(tag) === mine);\n}\n",
|
|
14
|
+
"/** `PUT` and `DELETE`: a body streamed into the bucket under a fresh key. */\n\nimport type { AnyReply } from '@softistx/alxia';\nimport { S3Error } from '@softistx/s3';\nimport { collected, joined, readHead, resumed } from './body';\nimport type { MediaBucket } from './bucket';\nimport { admitted } from './checks';\nimport { isMediaKey, type MediaPlace, newMediaKey } from './key';\nimport { keepsOriginal, type MediaContext, type MediaKind } from './kind';\nimport { acceptsAny } from './kind-check';\nimport { MediaRefusal, refusalOfVerdict } from './refusal';\nimport {\n\ttype MediaStoredRendition,\n\tremoveAll,\n\tstoreRenditions,\n} from './rendition';\nimport { canSniff, SNIFF_BYTES, sniffs } from './sniff';\n\n/** What a successful upload answers: the key to keep, never a URL. */\nexport interface MediaUpload {\n\treadonly key: string;\n\treadonly contentType: string;\n\treadonly size: number;\n}\n\n/** What a write needs beside the kind: the bucket, its deadline, and where this request's objects live. */\nexport interface Writing {\n\treadonly bucket: MediaBucket;\n\treadonly timeoutMs: number;\n\treadonly place: MediaPlace;\n}\n\n/** An upload as the response hook is given it: what the `PUT` answers by default, and the sizes stored. */\nexport interface MediaUploaded extends MediaUpload {\n\t/** The kind's name. */\n\treadonly kind: string;\n\t/** The sizes stored for this file, in the order they were made (none for a kind without `renditions`). */\n\treadonly sizes: readonly string[];\n\t/**\n\t * The same renditions with their type and, for a picture made by\n\t * `@softistx/alxia-media/image` (or a `make` that sets them), `width` and `height`\n\t * in pixels, in the order of `sizes`. Empty for a kind without `renditions`.\n\t */\n\treadonly renditions: readonly MediaStoredRendition[];\n}\n\n/**\n * Streams a body into the bucket. The bucket's idle deadline covers the\n * client too, since it waits on the body: a `TIMEOUT` that fell while the\n * body waited on the client is the client's stall, refused `stalled`.\n */\nasync function store(\n\tbucket: MediaBucket,\n\tparams: { readonly key: string },\n\tsource: ReturnType<typeof resumed>,\n\toptions: { type: string; size: number; timeoutMs: number },\n): Promise<void> {\n\ttry {\n\t\tawait bucket.put(params, source.body, options);\n\t} catch (error) {\n\t\tif (\n\t\t\tsource.stalled() &&\n\t\t\terror instanceof S3Error &&\n\t\t\terror.code === 'TIMEOUT'\n\t\t) {\n\t\t\tthrow new MediaRefusal('stalled', {}, { cause: error });\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Stores the request's body as a new file of `kind`, then, for a kind with\n * `renditions`, what it makes of it (see `storeRenditions`). For a kind with\n * `keepOriginal: false` the body is never stored, only what is made of it.\n * `answer` shapes the response from the finished upload; if it throws, what\n * was stored is removed.\n */\nexport async function upload(\n\tctx: MediaContext<object>,\n\tkind: MediaKind<object>,\n\twriting: Writing,\n\tanswer?: (uploaded: MediaUploaded) => unknown,\n): Promise<unknown> {\n\tconst { bucket, timeoutMs, place } = writing;\n\tconst stored = await storeBody(ctx, kind, writing);\n\tconst { bytes: held, ...result } = stored;\n\tconst { renditions } = kind;\n\tlet sizes: string[] = [];\n\tlet made: MediaStoredRendition[] = [];\n\tconst keeps = keepsOriginal(kind, result.contentType);\n\tlet objects = keeps ? [place(result.key)] : [];\n\tif (\n\t\trenditions !== undefined &&\n\t\tkind.renditionTypes.includes(result.contentType)\n\t) {\n\t\tconst done = await storeRenditions(\n\t\t\tbucket,\n\t\t\t{ ...kind, renditions },\n\t\t\tresult,\n\t\t\t{\n\t\t\t\ttimeoutMs,\n\t\t\t\tplace,\n\t\t\t\trequest: ctx.request,\n\t\t\t\t...(held !== undefined && { held }),\n\t\t\t},\n\t\t);\n\t\tsizes = done.sizes;\n\t\tmade = done.renditions;\n\t\tobjects = done.objects;\n\t}\n\tif (answer === undefined) return result;\n\ttry {\n\t\treturn await answer({\n\t\t\t...result,\n\t\t\tkind: kind.name,\n\t\t\tsizes,\n\t\t\trenditions: made,\n\t\t});\n\t} catch (error) {\n\t\tawait removeAll(bucket, objects, timeoutMs);\n\t\tthrow error;\n\t}\n}\n\n/** The whole body, held in memory: what `head` read plus the rest, refused past `maxBytes`. */\nasync function held(\n\thead: Awaited<ReturnType<typeof readHead>>,\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tkind: MediaKind<object>,\n\ttimeoutMs: number,\n): Promise<{ chunks: readonly Uint8Array[]; length: number }> {\n\tconst all = head.done\n\t\t? { chunks: head.chunks, length: head.length }\n\t\t: await collected(\n\t\t\t\thead.chunks,\n\t\t\t\thead.length,\n\t\t\t\treader,\n\t\t\t\tkind.maxBytes,\n\t\t\t\ttimeoutMs,\n\t\t\t);\n\tif (all.length > kind.maxBytes) {\n\t\tthrow new MediaRefusal('too_large', { limit: kind.maxBytes });\n\t}\n\treturn all;\n}\n\n/**\n * Stores the request's body as a new file of `kind`. In order: the caller\n * may write, the kind's throttle lets it through (before a byte is read),\n * the type is one the kind accepts, the declared length is within the\n * limit, the kind's quota (given that declared length, still before a byte\n * is read) lets it through, the first bytes are the type's. A body that declares its length\n * streams straight into the bucket; one that does not is held in memory up\n * to the kind's `maxBytes` (and refused past it), because the bucket needs\n * the length before the first byte; so is every body of a kind with\n * `keepOriginal: false`, which is never stored. Reading the body has an idle\n * deadline, `timeoutMs`, restarted at each chunk: a client that stalls is\n * refused `stalled` (408), and nothing is stored.\n */\nasync function storeBody(\n\tctx: MediaContext<object>,\n\tkind: MediaKind<object>,\n\t{ bucket, timeoutMs, place }: Writing,\n): Promise<MediaUpload & { readonly bytes?: Uint8Array }> {\n\tconst { type, declared } = await admitted(ctx, kind);\n\tif (ctx.request.body === null) throw new MediaRefusal('empty_body');\n\tconst reader = ctx.request.body.getReader();\n\ttry {\n\t\tconst head = await readHead(reader, SNIFF_BYTES, timeoutMs);\n\t\tif (head.length === 0) throw new MediaRefusal('empty_body');\n\t\tconst checked =\n\t\t\tkind.sniff === 'known' || acceptsAny(kind.accept)\n\t\t\t\t? kind.sniff !== false && canSniff(type)\n\t\t\t\t: kind.sniff;\n\t\tif (checked && !sniffs(type, joined(head.chunks, head.length))) {\n\t\t\tthrow new MediaRefusal('unsupported_type', { accept: kind.accept });\n\t\t}\n\t\tconst key = newMediaKey();\n\t\tconst params = { key: place(key) };\n\t\tconst result = (size: number) => ({ key, contentType: type, size });\n\t\tif (!keepsOriginal(kind, type)) {\n\t\t\t// Held in memory, never written: only what is made of it is.\n\t\t\tconst all = await held(head, reader, kind, timeoutMs);\n\t\t\tif (declared !== undefined && all.length !== declared) {\n\t\t\t\tthrow new MediaRefusal('size_mismatch');\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...result(all.length),\n\t\t\t\tbytes: joined(all.chunks, all.length),\n\t\t\t};\n\t\t}\n\t\tconst options = { type, timeoutMs };\n\t\tif (declared !== undefined) {\n\t\t\tconst source = resumed(head.chunks, reader);\n\t\t\tawait store(bucket, params, source, { ...options, size: declared });\n\t\t\treturn result(declared);\n\t\t}\n\t\t// The chunks go out as a stream of their own length: no joined copy,\n\t\t// so the peak is about `maxBytes`, once.\n\t\tconst all = await held(head, reader, kind, timeoutMs);\n\t\tawait store(bucket, params, resumed(all.chunks), {\n\t\t\t...options,\n\t\t\tsize: all.length,\n\t\t});\n\t\treturn result(all.length);\n\t} catch (error) {\n\t\tawait reader.cancel().catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\n/** Removes a file and its sizes. Deleting what is not there is a 204 too. */\nexport async function remove(\n\tctx: MediaContext<object>,\n\tkind: MediaKind<object>,\n\tkey: string | undefined,\n\t{ bucket, timeoutMs, place }: Writing,\n): Promise<AnyReply> {\n\tif (!isMediaKey(key)) throw new MediaRefusal('not_found');\n\tif (kind.authorizeDelete === undefined) throw new MediaRefusal('not_found');\n\tconst denied = refusalOfVerdict(\n\t\tawait kind.authorizeDelete(ctx, key),\n\t\tnew MediaRefusal('forbidden'),\n\t);\n\tif (denied !== undefined) throw denied;\n\tfor (const size of [undefined, ...kind.sizes]) {\n\t\tawait bucket.delete({ key: place(key, size) }, { timeoutMs });\n\t}\n\treturn ctx.reply(204);\n}\n",
|
|
15
|
+
"/** Reading an upload's body: an idle deadline on each read, and no copy of what is held. */\n\nimport { MediaRefusal } from './refusal';\n\n/** The bytes of `chunks` as one array. */\nexport function joined(\n\tchunks: readonly Uint8Array[],\n\tlength: number,\n): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tlet at = 0;\n\tfor (const chunk of chunks) {\n\t\tout.set(chunk, at);\n\t\tat += chunk.length;\n\t}\n\treturn out;\n}\n\n/**\n * One read of the body within an idle deadline: a client that sends nothing\n * for `ms` is refused `stalled`, and the deadline starts over at each chunk.\n */\nasync function readWithin(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tms: number,\n) {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst stalled = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(() => reject(new MediaRefusal('stalled')), ms);\n\t});\n\ttry {\n\t\treturn await Promise.race([reader.read(), stalled]);\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n/** Reads chunks until `bytes` are held, or the body ends. */\nexport async function readHead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbytes: number,\n\tidleMs: number,\n) {\n\tconst chunks: Uint8Array[] = [];\n\tlet length = 0;\n\tlet done = false;\n\twhile (length < bytes && !done) {\n\t\tconst step = await readWithin(reader, idleMs);\n\t\tif (step.done) done = true;\n\t\telse if (step.value.length > 0) {\n\t\t\tchunks.push(step.value);\n\t\t\tlength += step.value.length;\n\t\t}\n\t}\n\treturn { chunks, length, done };\n}\n\n/**\n * The chunks already read, then the rest of the body, as one stream.\n * `stalled()` says whether it was cancelled while it waited on the client:\n * the bucket's idle deadline then fell on the client's side, not its own.\n */\nexport function resumed(\n\tchunks: readonly Uint8Array[],\n\treader?: ReadableStreamDefaultReader<Uint8Array>,\n): { readonly body: ReadableStream<Uint8Array>; stalled(): boolean } {\n\tlet next = 0;\n\tlet reading = false;\n\tlet stalled = false;\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\tconst held = chunks[next];\n\t\t\tif (held !== undefined) {\n\t\t\t\tnext += 1;\n\t\t\t\tcontroller.enqueue(held);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reader === undefined) {\n\t\t\t\tcontroller.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treading = true;\n\t\t\ttry {\n\t\t\t\tconst step = await reader.read();\n\t\t\t\tif (step.done) controller.close();\n\t\t\t\telse controller.enqueue(step.value);\n\t\t\t} finally {\n\t\t\t\treading = false;\n\t\t\t}\n\t\t},\n\t\tcancel: (reason) => {\n\t\t\tstalled = reading;\n\t\t\treturn reader?.cancel(reason);\n\t\t},\n\t});\n\treturn { body, stalled: () => stalled };\n}\n\n/** Reads the rest of a body of unknown length, up to `limit` bytes in all. */\nexport async function collected(\n\theld: readonly Uint8Array[],\n\theldLength: number,\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tlimit: number,\n\tidleMs: number,\n) {\n\tconst chunks = [...held];\n\tlet length = heldLength;\n\tfor (;;) {\n\t\tconst step = await readWithin(reader, idleMs);\n\t\tif (step.done) break;\n\t\tlength += step.value.length;\n\t\tif (length > limit) {\n\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t\tthrow new MediaRefusal('too_large', { limit });\n\t\t}\n\t\tchunks.push(step.value);\n\t}\n\treturn { chunks, length };\n}\n",
|
|
16
|
+
"/** The checks an upload passes before a byte of its body is read. */\n\nimport type { MediaContext, MediaKind } from './kind';\nimport { essenceOf } from './kind';\nimport { acceptsAny, isWellFormedType } from './kind-check';\nimport { MediaRefusal, refusalOfVerdict } from './refusal';\n\n/**\n * The permission, throttle, type, declared length and quota checks, in that order,\n * before a byte of the body is read.\n */\nexport async function admitted(\n\tctx: MediaContext<object>,\n\tkind: MediaKind<object>,\n): Promise<{ type: string; declared: number | undefined }> {\n\tconst denied = refusalOfVerdict(\n\t\tawait kind.authorizeWrite(ctx),\n\t\tnew MediaRefusal('forbidden'),\n\t);\n\tif (denied !== undefined) throw denied;\n\tif (kind.throttle !== undefined) {\n\t\tconst decision = await kind.throttle(ctx);\n\t\tif (decision === false) throw new MediaRefusal('throttled');\n\t\tif (typeof decision === 'number') {\n\t\t\tthrow new MediaRefusal('throttled', { retryAfter: decision });\n\t\t}\n\t}\n\tconst { request } = ctx;\n\tconst declaredType = essenceOf(request.headers.get('content-type') ?? '');\n\tconst any = acceptsAny(kind.accept);\n\tconst type =\n\t\tany && declaredType === '' ? 'application/octet-stream' : declaredType;\n\tif (any ? !isWellFormedType(type) : !kind.accept.includes(type)) {\n\t\tthrow new MediaRefusal('unsupported_type', { accept: kind.accept });\n\t}\n\tconst header = request.headers.get('content-length');\n\tlet declared: number | undefined;\n\tif (header !== null) {\n\t\tif (!/^\\d+$/.test(header.trim())) throw new MediaRefusal('size_mismatch');\n\t\tdeclared = Number(header.trim());\n\t\tif (declared === 0) throw new MediaRefusal('empty_body');\n\t\tif (declared > kind.maxBytes) {\n\t\t\tthrow new MediaRefusal('too_large', { limit: kind.maxBytes });\n\t\t}\n\t}\n\tif (kind.quota !== undefined) {\n\t\tconst over = refusalOfVerdict(\n\t\t\tawait kind.quota(ctx, { declared, type }),\n\t\t\tnew MediaRefusal('forbidden'),\n\t\t);\n\t\tif (over !== undefined) throw over;\n\t}\n\treturn { type, declared };\n}\n",
|
|
17
|
+
"/**\n * Renditions made at upload: once a file of a kind with `renditions` is in\n * the bucket, its bytes are read back and handed to `make`, and what it\n * makes is stored under `<kind>/<key>/<size>` before the upload answers.\n * The routes stay read-only on `GET`: a size is served as it was stored.\n */\n\nimport type { MediaBucket } from './bucket';\nimport type { MediaKey, MediaPlace } from './key';\nimport { MediaRefusal } from './refusal';\nimport type { MediaUpload } from './write';\n\n/** A file just stored, as `make` is given it. */\nexport interface MediaFile {\n\treadonly key: MediaKey;\n\t/** The type it was stored as, one of the kind's `accept`. */\n\treadonly contentType: string;\n\treadonly bytes: Uint8Array;\n\t/**\n\t * The upload's request, for what the rendition depends on (a crop read\n\t * from its query, who sends it). Its body has been read.\n\t */\n\treadonly request: Request;\n}\n\n/** One rendition `make` gives: a size the kind lists, in a type `types` lists. */\nexport interface MediaRendition {\n\treadonly size: string;\n\treadonly contentType: string;\n\treadonly bytes: Uint8Array;\n\t/** The picture's width in pixels, when the rendition is one: set by `@softistx/alxia-media/image`, given to the `uploaded` hook. */\n\treadonly width?: number;\n\t/** The picture's height in pixels, like `width`. */\n\treadonly height?: number;\n}\n\n/** One stored rendition as the `uploaded` hook sees it: no bytes, its size, type and (for a picture) dimensions. */\nexport interface MediaStoredRendition {\n\treadonly size: string;\n\treadonly contentType: string;\n\treadonly width?: number;\n\treadonly height?: number;\n}\n\n/** What a kind makes of each upload. `@softistx/alxia-media/image` gives one for pictures. */\nexport interface MediaRenditions {\n\t/**\n\t * The content types `make` gives, exact. A size is served as the type it\n\t * was stored as when it is one of these or of `accept`.\n\t */\n\treadonly types: readonly string[];\n\t/**\n\t * A file extension (`'webp'`, no dot) that ends every rendition key:\n\t * `<kind>/<key>/<size>.<extension>` instead of `<kind>/<key>/<size>`, on\n\t * write, read and delete. For a bucket that already stores renditions that\n\t * way. The original's key is unchanged, and so is the URL (`/<size>`).\n\t * Not set (the default): no extension. Changing it moves every key, so\n\t * the renditions already stored under the other form answer 404.\n\t */\n\treadonly keyExtension?: string;\n\t/**\n\t * Makes the renditions of a file just stored. A `MediaRefusal` it throws\n\t * answers the upload (`unprocessable`, 422, for a picture that cannot be\n\t * read; an `unsupported_type` is given the kind's `accept`); any other\n\t * error is the app's (a 500). Either way, the file and whatever was\n\t * stored of its renditions are removed.\n\t *\n\t * It need not make every size the kind lists: a size it leaves out is\n\t * not stored, and answers 404 for that file, as a size added after the\n\t * upload does.\n\t */\n\treadonly make: (file: MediaFile) => Promise<readonly MediaRendition[]>;\n}\n\n/** What storing the renditions of one upload needs. */\ninterface Rendering {\n\treadonly name: string;\n\treadonly accept: readonly string[];\n\treadonly sizes: readonly string[];\n\treadonly renditions: MediaRenditions;\n}\n\n/** A refusal of `make` as the upload answers it: `unsupported_type` names `accept`. */\nfunction answered(kind: Rendering, error: unknown): unknown {\n\tif (\n\t\terror instanceof MediaRefusal &&\n\t\terror.code === 'unsupported_type' &&\n\t\terror.details.accept === undefined\n\t) {\n\t\treturn new MediaRefusal(\n\t\t\t'unsupported_type',\n\t\t\t{ ...error.details, accept: kind.accept },\n\t\t\t{ cause: error.cause ?? error },\n\t\t);\n\t}\n\treturn error;\n}\n\nasync function readBack(\n\tbucket: MediaBucket,\n\tkey: string,\n\ttimeoutMs: number,\n): Promise<Uint8Array> {\n\tconst opened = await bucket.open({ key }, { timeoutMs });\n\tif (opened === undefined) {\n\t\tthrow new Error(\n\t\t\t`@softistx/alxia-media: ${key} was gone right after its upload`,\n\t\t);\n\t}\n\treturn new Uint8Array(await new Response(opened.stream).arrayBuffer());\n}\n\nfunction checked(kind: Rendering, made: MediaRendition): MediaRendition {\n\tif (!kind.sizes.includes(made.size)) {\n\t\tthrow new TypeError(\n\t\t\t`${kind.name}: renditions made the size ${JSON.stringify(made.size)}, which sizes does not list`,\n\t\t);\n\t}\n\tif (!kind.renditions.types.includes(made.contentType)) {\n\t\tthrow new TypeError(\n\t\t\t`${kind.name}: renditions made a ${made.contentType}, which renditions.types does not list`,\n\t\t);\n\t}\n\treturn made;\n}\n\n/**\n * Makes and stores the renditions of `upload`, and gives the sizes it\n * stored. The file is read back from the bucket, unless it was never stored\n * (`held`, a kind with `keepOriginal: false`). On any failure, removes the\n * file and every rendition key it started to write, then throws again.\n */\nexport async function storeRenditions(\n\tbucket: MediaBucket,\n\tkind: Rendering,\n\tupload: MediaUpload,\n\toptions: {\n\t\treadonly timeoutMs: number;\n\t\treadonly place: MediaPlace;\n\t\treadonly request: Request;\n\t\treadonly held?: Uint8Array;\n\t},\n): Promise<{\n\treadonly sizes: string[];\n\treadonly renditions: MediaStoredRendition[];\n\treadonly objects: string[];\n}> {\n\tconst { timeoutMs, place, request, held } = options;\n\tconst written = held === undefined ? [place(upload.key)] : [];\n\tconst sizes: string[] = [];\n\tconst renditions: MediaStoredRendition[] = [];\n\ttry {\n\t\tconst bytes =\n\t\t\theld ?? (await readBack(bucket, place(upload.key), timeoutMs));\n\t\tconst made = await kind.renditions.make({\n\t\t\tkey: upload.key,\n\t\t\tcontentType: upload.contentType,\n\t\t\tbytes,\n\t\t\trequest,\n\t\t});\n\t\tfor (const rendition of made.map((one) => checked(kind, one))) {\n\t\t\tconst key = place(upload.key, rendition.size);\n\t\t\twritten.push(key);\n\t\t\tawait bucket.put({ key }, rendition.bytes, {\n\t\t\t\ttype: rendition.contentType,\n\t\t\t\ttimeoutMs,\n\t\t\t});\n\t\t\tsizes.push(rendition.size);\n\t\t\trenditions.push({\n\t\t\t\tsize: rendition.size,\n\t\t\t\tcontentType: rendition.contentType,\n\t\t\t\t...(rendition.width !== undefined && { width: rendition.width }),\n\t\t\t\t...(rendition.height !== undefined && { height: rendition.height }),\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tawait removeAll(bucket, written, timeoutMs);\n\t\tthrow answered(kind, error);\n\t}\n\treturn { sizes, renditions, objects: written };\n}\n\n/** Removes `keys`, each failure ignored: this is the cleanup of a failure already being thrown. */\nexport async function removeAll(\n\tbucket: MediaBucket,\n\tkeys: readonly string[],\n\ttimeoutMs: number,\n): Promise<void> {\n\tawait Promise.all(\n\t\tkeys.map((key) =>\n\t\t\tbucket.delete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M,QAAQ,SAAS,MAAM,GAAG,CACjC,CACD;AAAA,EACD,OAAO,IACN,MACA,QAAQ,SAAS,MAAM,OAAO,QAAQ;AAAA,IACrC,MAAM,QAAQ,MAAM,QAAQ,SAAS,MAAM,GAAG;AAAA,IAC9C,QAAQ,aAAa;AAAA,IACrB,MAAM,OAAO,MAAM,OAClB,KACA,MACA,EAAE,QAAQ,WAAW,gBAAgB,MAAM,GAC3C,aAAa,CAAC,WAAW,SAAS,QAAQ,GAAG,EAC9C;AAAA,IACA,OAAO,IAAI,MAAM,KAAK,IAAI;AAAA,GAC1B,CACF;AAAA,EACA,OAAO,IAAI,GAAG,aAAa,KAAK,KAAK,CAAC;AAAA,EACtC,IAAI,KAAK,MAAM,SAAS;AAAA,IAAG,OAAO,IAAI,GAAG,mBAAmB,KAAK,IAAI,CAAC;AAAA,EACtE,IAAI,KAAK,oBAAoB,WAAW;AAAA,IACvC,OAAO,OACN,GAAG,aACH,QAAQ,SAAS,MAAM,OAAO,QAC7B,OAAO,KAAK,MAAM,IAAI,WAAW,QAAQ;AAAA,MACxC;AAAA,MACA,WAAW;AAAA,MACX,OAAO,MAAM,QAAQ,SAAS,MAAM,GAAG;AAAA,IACxC,CAAC,CACF,CACD;AAAA,EACD;AAAA;",
|
|
20
|
+
"debugId": "CC809879571B9A0064756E2164756E21",
|
|
21
|
+
"names": []
|
|
22
|
+
}
|
package/dist/key.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media keys. A key is what an upload answers and a record keeps: a fresh
|
|
3
|
+
* lower-case UUID, never a URL. Anything else in a URL's key segment is a
|
|
4
|
+
* 404 before the bucket is asked.
|
|
5
|
+
*/
|
|
6
|
+
/** A key as the routes mint and read it: a lower-case UUID. */
|
|
7
|
+
export type MediaKey = string;
|
|
8
|
+
/** Whether `value` is a key `newMediaKey` could have made. */
|
|
9
|
+
export declare function isMediaKey(value: unknown): value is MediaKey;
|
|
10
|
+
/** A fresh key. */
|
|
11
|
+
export declare function newMediaKey(): MediaKey;
|
|
12
|
+
/** Whether `value` can name a kind (it is a path segment and the bucket's folder). */
|
|
13
|
+
export declare function isMediaKindName(value: unknown): value is string;
|
|
14
|
+
/** A named size of a stored file (`thumb`, `256`): lower-case words and digits, hyphens between. */
|
|
15
|
+
export declare function isMediaSize(value: unknown): value is string;
|
|
16
|
+
/**
|
|
17
|
+
* The bucket key of a stored file: `<kind>/<key>`, or `<kind>/<key>/<size>`.
|
|
18
|
+
* It never adds a `keyExtension`; `mediaPlace` does.
|
|
19
|
+
*/
|
|
20
|
+
export declare function mediaObjectKey(kind: string, key: MediaKey, size?: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Where the objects of one request live: `place(key)` or `place(key, size)`, a
|
|
23
|
+
* bucket key. The original is never given an extension.
|
|
24
|
+
*/
|
|
25
|
+
export type MediaPlace = (key: MediaKey, size?: string) => string;
|
|
26
|
+
/**
|
|
27
|
+
* The folders a `keyPrefix` hook puts a request's objects under: segments
|
|
28
|
+
* of letters, digits and `. _ = -` joined by `/`, no empty segment, no
|
|
29
|
+
* leading or trailing `/`, no `.` or `..`. Anything else is the app's bug
|
|
30
|
+
* and throws a `TypeError` (a 500): a prefix is never sanitised, since a
|
|
31
|
+
* silent change could move a tenant's objects into another's folder.
|
|
32
|
+
*/
|
|
33
|
+
export declare function checkedPrefix(value: unknown): string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* `mediaObjectKey` under an optional prefix (`<prefix>/<kind>/<key>[/<size>]`).
|
|
36
|
+
* With `extension` (`'webp'`), a size's key ends in it:
|
|
37
|
+
* `<prefix>/<kind>/<key>/<size>.<extension>`; the original's does not.
|
|
38
|
+
*/
|
|
39
|
+
export declare function mediaPlace(kind: string, prefix?: string, extension?: string): MediaPlace;
|
|
40
|
+
//# sourceMappingURL=key.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"key.d.ts","sourceRoot":"","sources":["../src/key.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,+DAA+D;AAC/D,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAE9B,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAE5D;AAED,mBAAmB;AACnB,wBAAgB,WAAW,IAAI,QAAQ,CAEtC;AAKD,sFAAsF;AACtF,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE/D;AAED,oGAAoG;AACpG,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE3D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,QAAQ,EACb,IAAI,CAAC,EAAE,MAAM,GACX,MAAM,CAER;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AAIlE;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAgBhE;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CACzB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,MAAM,GAChB,UAAU,CAKZ"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** The types a kind's callbacks take and answer. */
|
|
2
|
+
import type { MediaVerdict } from './refusal';
|
|
3
|
+
export type MaybePromise<T> = T | Promise<T>;
|
|
4
|
+
/** What an upload declares before its body is read: the `quota` hook is given it. */
|
|
5
|
+
export interface MediaUploadIntent {
|
|
6
|
+
/** The `Content-Length` the request declared, in bytes; `undefined` when it declared none. */
|
|
7
|
+
readonly declared: number | undefined;
|
|
8
|
+
/** The request's content type, without parameters (`image/png`). */
|
|
9
|
+
readonly type: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* What a kind's `throttle` answers: `true` (or nothing) lets the upload
|
|
13
|
+
* through; `false` refuses it 429; a number refuses it 429 with that many
|
|
14
|
+
* seconds in `Retry-After`.
|
|
15
|
+
*/
|
|
16
|
+
export type ThrottleDecision = boolean | number | undefined | void;
|
|
17
|
+
/**
|
|
18
|
+
* A kind's `quota`: given the context (`ctx.request` is the request) and
|
|
19
|
+
* what the upload declares (`declared` is the `Content-Length`, `undefined`
|
|
20
|
+
* when none), once the upload is permitted, throttled, of an accepted type
|
|
21
|
+
* and within `maxBytes`, still before a byte of the body is read. `true`
|
|
22
|
+
* lets it through, `false` is a 403, a `MediaDenial` is answered as it says
|
|
23
|
+
* (`{ code: 'quota_exceeded', status: 402 }`).
|
|
24
|
+
*/
|
|
25
|
+
export type MediaQuota<Ctx> = (ctx: Ctx, upload: MediaUploadIntent) => MaybePromise<MediaVerdict>;
|
|
26
|
+
/** A kind's `throttle`: given the context, before its body is read. */
|
|
27
|
+
export type MediaThrottle<Ctx> = (ctx: Ctx) => MaybePromise<ThrottleDecision>;
|
|
28
|
+
//# sourceMappingURL=kind-callbacks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kind-callbacks.d.ts","sourceRoot":"","sources":["../src/kind-callbacks.ts"],"names":[],"mappings":"AAAA,oDAAoD;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE9C,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7C,qFAAqF;AACrF,MAAM,WAAW,iBAAiB;IACjC,8FAA8F;IAC9F,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;AAEnE;;;;;;;GAOG;AACH,MAAM,MAAM,UAAU,CAAC,GAAG,IAAI,CAC7B,GAAG,EAAE,GAAG,EACR,MAAM,EAAE,iBAAiB,KACrB,YAAY,CAAC,YAAY,CAAC,CAAC;AAEhC,uEAAuE;AACvE,MAAM,MAAM,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,YAAY,CAAC,gBAAgB,CAAC,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** The checks `defineMediaKind` shares: content types and renditions. */
|
|
2
|
+
import type { MediaRenditions } from './rendition';
|
|
3
|
+
/** The content type of a header, as the kinds list it: no parameters, lower case. */
|
|
4
|
+
export declare function essenceOf(type: string): string;
|
|
5
|
+
/** Whether `type` is an exact content type: no wildcard, no parameters, lower case. */
|
|
6
|
+
export declare const isExactType: (type: string) => boolean;
|
|
7
|
+
/** The `accept` that takes every content type. */
|
|
8
|
+
export declare const ANY_TYPE = "*";
|
|
9
|
+
/** Whether a kind's `accept` takes every content type. */
|
|
10
|
+
export declare const acceptsAny: (accept: readonly string[]) => boolean;
|
|
11
|
+
/** Whether `type` is a well-formed content type, whatever it is. */
|
|
12
|
+
export declare const isWellFormedType: (type: string) => boolean;
|
|
13
|
+
export declare function checkRenditions(where: string, sizes: readonly string[], renditions: MediaRenditions | undefined): void;
|
|
14
|
+
/**
|
|
15
|
+
* The normalised `accept` of a kind: `['*']` for any type, else the exact
|
|
16
|
+
* types, lower-cased. Throws on an empty list, a type that is not exact, and
|
|
17
|
+
* (with `sniff: true`) a type nobody can sniff.
|
|
18
|
+
*/
|
|
19
|
+
export declare function checkAccept(where: string, accept: readonly string[] | typeof ANY_TYPE, sniff: boolean | 'known'): string[];
|
|
20
|
+
//# sourceMappingURL=kind-check.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kind-check.d.ts","sourceRoot":"","sources":["../src/kind-check.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGnD,qFAAqF;AACrF,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAID,uFAAuF;AACvF,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,YACe,CAAC;AAExD,kDAAkD;AAClD,eAAO,MAAM,QAAQ,MAAM,CAAC;AAE5B,0DAA0D;AAC1D,eAAO,MAAM,UAAU,GAAI,QAAQ,SAAS,MAAM,EAAE,YACN,CAAC;AAE/C,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,GAAI,MAAM,MAAM,YAAoB,CAAC;AAElE,wBAAgB,eAAe,CAC9B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,UAAU,EAAE,eAAe,GAAG,SAAS,GACrC,IAAI,CA0BN;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAC1B,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,QAAQ,EAC3C,KAAK,EAAE,OAAO,GAAG,OAAO,GACtB,MAAM,EAAE,CAmBV"}
|
package/dist/kind.d.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/** `defineMediaKind`: what one kind of file is allowed, who may do what with it. */
|
|
2
|
+
import type { BaseContext, Empty } from '@softistx/alxia';
|
|
3
|
+
import { type MediaKey } from './key';
|
|
4
|
+
import { type ANY_TYPE, essenceOf } from './kind-check';
|
|
5
|
+
import type { MediaVerdict } from './refusal';
|
|
6
|
+
import type { MediaRenditions } from './rendition';
|
|
7
|
+
export { essenceOf };
|
|
8
|
+
import type { MaybePromise, MediaQuota, MediaThrottle, MediaUploadIntent, ThrottleDecision } from './kind-callbacks';
|
|
9
|
+
export type { MediaUploadIntent, ThrottleDecision };
|
|
10
|
+
/** What a kind's callbacks read: the request's context, and what the app's middlewares added before the routes. */
|
|
11
|
+
export type MediaContext<Requires extends object = Empty> = BaseContext & Requires;
|
|
12
|
+
interface KindBase<Requires extends object> {
|
|
13
|
+
/**
|
|
14
|
+
* The kind's name: a URL segment and the bucket's folder
|
|
15
|
+
* (`<name>/<key>`). Lower-case words and digits joined by hyphens.
|
|
16
|
+
*/
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/**
|
|
19
|
+
* The content types an upload may have, exact (`image/png`), no partial
|
|
20
|
+
* wildcard. `'*'` alone takes any type: a type with a known signature is
|
|
21
|
+
* checked against it, any other is stored as declared (`application/octet-stream`
|
|
22
|
+
* when the upload declares none), and a file whose type is not an
|
|
23
|
+
* inline-safe one (image, audio, video, PDF, plain text) is served as
|
|
24
|
+
* `application/octet-stream` with `Content-Disposition: attachment`.
|
|
25
|
+
*/
|
|
26
|
+
readonly accept: readonly string[] | typeof ANY_TYPE;
|
|
27
|
+
/** The most bytes an upload may have. */
|
|
28
|
+
readonly maxBytes: number;
|
|
29
|
+
/**
|
|
30
|
+
* Whether the caller may upload this kind; `false` is a 403. It may
|
|
31
|
+
* answer a `MediaDenial` instead (`{ code: 'quota', status: 402 }`).
|
|
32
|
+
*/
|
|
33
|
+
readonly authorizeWrite: (ctx: MediaContext<Requires>) => MaybePromise<MediaVerdict>;
|
|
34
|
+
/**
|
|
35
|
+
* Whether the caller may delete a file of this kind. Declaring it mounts
|
|
36
|
+
* `DELETE <prefix>/<kind>/<key>`; `false` is a 403. Without it, no DELETE.
|
|
37
|
+
* It may answer a `MediaDenial` instead, a refusal of the app's own with
|
|
38
|
+
* its status: `{ code: 'in_use', status: 409 }` when a record still
|
|
39
|
+
* points at the file.
|
|
40
|
+
*/
|
|
41
|
+
readonly authorizeDelete?: (ctx: MediaContext<Requires>, key: MediaKey) => MaybePromise<MediaVerdict>;
|
|
42
|
+
/**
|
|
43
|
+
* Called once the upload is permitted, before a byte of the body is read:
|
|
44
|
+
* count it against the account's limit here. See `ThrottleDecision`.
|
|
45
|
+
*/
|
|
46
|
+
readonly throttle?: MediaThrottle<MediaContext<Requires>>;
|
|
47
|
+
/**
|
|
48
|
+
* Called after the type and declared-length checks, before a byte of the
|
|
49
|
+
* body is read: refuse an upload over a storage quota here. See
|
|
50
|
+
* `MediaQuota`; `false` is a 403, a `MediaDenial` is answered as it says.
|
|
51
|
+
*/
|
|
52
|
+
readonly quota?: MediaQuota<MediaContext<Requires>>;
|
|
53
|
+
/**
|
|
54
|
+
* Named renditions stored beside the file (`<kind>/<key>/<size>`), served
|
|
55
|
+
* by `GET <prefix>/<kind>/<key>/<size>`. A `GET` never makes one: the
|
|
56
|
+
* upload does, through `renditions`, or the app writes them (names alone,
|
|
57
|
+
* on any kind, `accept: '*'` included: a worker stores each at
|
|
58
|
+
* `mediaPlace(kind, prefix)(key, size)`). A size not listed, or listed and
|
|
59
|
+
* not written yet, is a 404; the stored object's own type and ETag are served.
|
|
60
|
+
*/
|
|
61
|
+
readonly sizes?: readonly string[];
|
|
62
|
+
/**
|
|
63
|
+
* What each upload is made into, stored under its `sizes` before the
|
|
64
|
+
* `PUT` answers. `withImageRendition` from `@softistx/alxia-media/image` gives one.
|
|
65
|
+
*/
|
|
66
|
+
readonly renditions?: MediaRenditions;
|
|
67
|
+
/**
|
|
68
|
+
* Whether the uploaded file itself is stored (default `true`). `false`
|
|
69
|
+
* stores the renditions alone: the body is held in memory (up to
|
|
70
|
+
* `maxBytes`), handed to `renditions`, and never written, so its
|
|
71
|
+
* metadata (EXIF, GPS) never reaches the bucket; `GET <kind>/<key>` is a
|
|
72
|
+
* 404 and only the sizes are served. Needs `renditions`.
|
|
73
|
+
*
|
|
74
|
+
* A list of accepted types keeps the original of those types only, for
|
|
75
|
+
* a kind that takes images and PDFs: `keepOriginal: ['application/pdf']`
|
|
76
|
+
* stores the PDF's bytes and, for an image, only its renditions. See
|
|
77
|
+
* `renditionTypes` for the types `renditions` is run on.
|
|
78
|
+
*/
|
|
79
|
+
readonly keepOriginal?: boolean | readonly string[];
|
|
80
|
+
/**
|
|
81
|
+
* The accepted types `renditions` is made from; the others are not
|
|
82
|
+
* handed to it. By default every accepted type, or, with a `keepOriginal`
|
|
83
|
+
* list, the accepted types that list leaves out (a PDF kept as it is,
|
|
84
|
+
* with no picture made of it). Every accepted type must be kept or listed
|
|
85
|
+
* here, or an upload of it would store nothing.
|
|
86
|
+
*/
|
|
87
|
+
readonly renditionTypes?: readonly string[];
|
|
88
|
+
/**
|
|
89
|
+
* Forces `Content-Disposition: attachment` on this kind's files and sizes,
|
|
90
|
+
* so the browser downloads them instead of showing them: `true` for every
|
|
91
|
+
* type, or a list of accepted types (`['application/pdf']`). Without it, a
|
|
92
|
+
* PDF is served inline (under a sandbox CSP) and an image shows in the
|
|
93
|
+
* page; a type this package does not serve inline is always an attachment.
|
|
94
|
+
*/
|
|
95
|
+
readonly attachment?: boolean | readonly string[];
|
|
96
|
+
/**
|
|
97
|
+
* The `Cache-Control` of this kind's 200, 206 and 304 answers. By default
|
|
98
|
+
* `private, max-age=31536000, immutable` (`public, …` for a public kind).
|
|
99
|
+
* For content a reader may lose access to, `'private, no-cache'` makes the
|
|
100
|
+
* browser revalidate on every use: `authorizeRead` runs each time, and the
|
|
101
|
+
* ETag lets it answer a cheap 304. Refusals stay `no-store`.
|
|
102
|
+
*/
|
|
103
|
+
readonly cacheControl?: string;
|
|
104
|
+
/**
|
|
105
|
+
* Whether an upload's first bytes must be those of its declared type
|
|
106
|
+
* (default `true`, which refuses a kind accepting a type with no
|
|
107
|
+
* signature). `'known'` checks the types this package has a signature
|
|
108
|
+
* for and takes the others in `accept` as declared (docx, xlsx, ...).
|
|
109
|
+
* `false` checks none.
|
|
110
|
+
*/
|
|
111
|
+
readonly sniff?: boolean | 'known';
|
|
112
|
+
}
|
|
113
|
+
/** What `defineMediaKind` takes: a private kind names who may read; a public one says so. */
|
|
114
|
+
export type MediaKindInput<Requires extends object = Empty> = KindBase<Requires> & ({
|
|
115
|
+
readonly public?: false;
|
|
116
|
+
/**
|
|
117
|
+
* Whether the caller may read the file under `key`. `false` is a
|
|
118
|
+
* 404, the answer for a file that is not there. A `MediaDenial` is
|
|
119
|
+
* answered as it says.
|
|
120
|
+
*/
|
|
121
|
+
readonly authorizeRead: (ctx: MediaContext<Requires>, key: MediaKey) => MaybePromise<MediaVerdict>;
|
|
122
|
+
} | {
|
|
123
|
+
/** Anyone may read it, with no check: served `public`, readable cross-origin. */
|
|
124
|
+
readonly public: true;
|
|
125
|
+
readonly authorizeRead?: undefined;
|
|
126
|
+
});
|
|
127
|
+
/** A kind, as `mediaRoutes` takes it. */
|
|
128
|
+
export interface MediaKind<Requires extends object = Empty> {
|
|
129
|
+
readonly name: string;
|
|
130
|
+
/** The accepted types, or `['*']` for a kind that takes any. */
|
|
131
|
+
readonly accept: readonly string[];
|
|
132
|
+
readonly maxBytes: number;
|
|
133
|
+
readonly public: boolean;
|
|
134
|
+
readonly sniff: boolean | 'known';
|
|
135
|
+
readonly sizes: readonly string[];
|
|
136
|
+
readonly renditions: MediaRenditions | undefined;
|
|
137
|
+
/** Whether every file's original is stored (`false` for a `keepOriginal` list or `false`). */
|
|
138
|
+
readonly keepOriginal: boolean;
|
|
139
|
+
/** The types whose original is stored when `keepOriginal` is `false`. */
|
|
140
|
+
readonly keepOriginalTypes: readonly string[];
|
|
141
|
+
/** The types `renditions` is made from. */
|
|
142
|
+
readonly renditionTypes: readonly string[];
|
|
143
|
+
/** The types always served as an attachment, or `true` for all. */
|
|
144
|
+
readonly attachment: boolean | readonly string[];
|
|
145
|
+
/** The kind's own `Cache-Control`, or `undefined` for the default. */
|
|
146
|
+
readonly cacheControl: string | undefined;
|
|
147
|
+
readonly authorizeWrite: (ctx: MediaContext<Requires>) => MaybePromise<MediaVerdict>;
|
|
148
|
+
readonly authorizeRead: (ctx: MediaContext<Requires>, key: MediaKey) => MaybePromise<MediaVerdict>;
|
|
149
|
+
readonly authorizeDelete: ((ctx: MediaContext<Requires>, key: MediaKey) => MaybePromise<MediaVerdict>) | undefined;
|
|
150
|
+
readonly throttle: MediaThrottle<MediaContext<Requires>> | undefined;
|
|
151
|
+
readonly quota: MediaQuota<MediaContext<Requires>> | undefined;
|
|
152
|
+
}
|
|
153
|
+
/** Whether an upload of `type` to `kind` stores its own bytes. */
|
|
154
|
+
export declare function keepsOriginal(kind: MediaKind<never>, type: string): boolean;
|
|
155
|
+
/**
|
|
156
|
+
* A kind of file: its name, the types and size it takes, and who may
|
|
157
|
+
* write, read and delete it. Throws at declaration on anything that would
|
|
158
|
+
* make the routes unsafe: a bad name, an empty `accept`, a type this package
|
|
159
|
+
* cannot sniff (unless `sniff: false` or `'known'`), a limit that is not a positive
|
|
160
|
+
* integer.
|
|
161
|
+
*
|
|
162
|
+
* ```ts
|
|
163
|
+
* const avatars = defineMediaKind<{ viewer: Viewer }>({
|
|
164
|
+
* name: 'avatars',
|
|
165
|
+
* accept: ['image/png', 'image/jpeg', 'image/webp'],
|
|
166
|
+
* maxBytes: 2 * 1024 * 1024,
|
|
167
|
+
* authorizeWrite: ({ viewer }) => viewer.canUpload,
|
|
168
|
+
* authorizeRead: () => true,
|
|
169
|
+
* });
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
export declare function defineMediaKind<Requires extends object = Empty>(input: MediaKindInput<Requires>): MediaKind<Requires>;
|
|
173
|
+
//# sourceMappingURL=kind.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kind.d.ts","sourceRoot":"","sources":["../src/kind.ts"],"names":[],"mappings":"AAAA,oFAAoF;AAEpF,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAgC,KAAK,QAAQ,EAAE,MAAM,OAAO,CAAC;AACpE,OAAO,EACN,KAAK,QAAQ,EAIb,SAAS,EACT,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAA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cAAc,CAAC,QAAQ,CAAC,GAC7B,SAAS,CAAC,QAAQ,CAAC,CAkErB"}
|
package/dist/range.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** `Range` request headers, one byte range of them. */
|
|
2
|
+
/** A byte range as the header asked for it; `end` is inclusive, as written. */
|
|
3
|
+
export type RequestedRange = {
|
|
4
|
+
readonly start: number;
|
|
5
|
+
readonly end?: number;
|
|
6
|
+
} | {
|
|
7
|
+
readonly suffix: number;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The range `Range: bytes=…` asks for, or `undefined` to serve the whole
|
|
11
|
+
* object: no header, another unit, several ranges and a malformed spec are
|
|
12
|
+
* all ignored, which HTTP allows (RFC 9110 14.2), never refused.
|
|
13
|
+
*/
|
|
14
|
+
export declare function parseRange(header: string | null): RequestedRange | undefined;
|
|
15
|
+
/** `ETag` list matching for `If-None-Match`: weak comparison, `*` matches. */
|
|
16
|
+
export declare function matchesEtag(header: string | null, etag: string): boolean;
|
|
17
|
+
//# sourceMappingURL=range.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"range.d.ts","sourceRoot":"","sources":["../src/range.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD,+EAA+E;AAC/E,MAAM,MAAM,cAAc,GACvB;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/B;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,cAAc,GAAG,SAAS,CAgB5E;AAED,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAOxE"}
|
package/dist/read.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** `GET`: a stored file streamed to the client, with Range, ETag and 304. */
|
|
2
|
+
import type { AnyReply } from '@softistx/alxia';
|
|
3
|
+
import type { MediaBucket } from './bucket';
|
|
4
|
+
import { type MediaPlace } from './key';
|
|
5
|
+
import type { MediaContext, MediaKind } from './kind';
|
|
6
|
+
/** Throws a refusal for anything that is not a file this caller may read. */
|
|
7
|
+
export declare function serve(ctx: MediaContext<object>, kind: MediaKind<object>, bucket: MediaBucket, raw: {
|
|
8
|
+
key: string | undefined;
|
|
9
|
+
size: string | undefined;
|
|
10
|
+
}, timeoutMs: number, place: MediaPlace): Promise<AnyReply>;
|
|
11
|
+
//# sourceMappingURL=read.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../src/read.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAE7E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAc,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAwHtD,6EAA6E;AAC7E,wBAAsB,KAAK,CAC1B,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,EACzB,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE;IAAE,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,EAC1D,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,UAAU,GACf,OAAO,CAAC,QAAQ,CAAC,CA4CnB"}
|