@antzsoft/filekit-core
v1.0.0
Published
FileKit core — isomorphic wire-protocol types, upload policy (MIME/size) defaults and validation, and error codes shared by all FileKit SDKs. Zero dependencies.
Readme
@antzsoft/filekit-core
The shared, dependency-free core of the FileKit SDK family. It runs anywhere — Node, browsers, React Native — and holds what every FileKit package agrees on:
- the wire protocol (the JSON a FileKit server and its clients exchange),
- the policy engine (allowed file types and sizes),
- error codes,
- small helpers for sizes, MIME types and storage keys.
Server apps normally use it through
@antzsoft/filekit-server, which re-exports everything
here. Use this package directly in front ends and client SDKs (e.g. to
validate a file before uploading it).
npm install @antzsoft/filekit-coreESM + CommonJS · no dependencies · .npmrc points @antzsoft at the local
Verdaccio registry (http://localhost:4873); remove that line for npmjs.
Quick example — check a file in the browser before uploading
import { validateFile, isFileKitError, formatBytes } from '@antzsoft/filekit-core';
// the server's policy is plain JSON, e.g. from the prebuilt API: GET /filekit/info
const { policy } = await fetch('/filekit/info').then((r) => r.json());
try {
const { category, maxSize } = validateFile(policy, { mimeType: file.type, size: file.size, filename: file.name });
console.log(`OK: ${category}, limit ${formatBytes(maxSize)}`);
} catch (err) {
if (isFileKitError(err)) showError(err.code, err.message); // FILE_TOO_LARGE, FILE_TYPE_NOT_ALLOWED, …
}Everything this package exports
| Group | Exports |
|---|---|
| Policy | DEFAULT_POLICY, resolvePolicy, validateFile, categorize, maxSizeFor · types PolicyInput, CategoryInput, MultipartInput, ResolvedPolicy, CategoryRule, FileDescriptor, ValidationResult |
| Errors | FileKitError, FileKitErrorCode, isFileKitError, statusForCode · type FileKitErrorBody |
| Sizes | parseSize, formatBytes · type Size |
| MIME | mimeFromFilename, extensionFromMime, extensionOf, normalizeMime, mimeMatches, isActiveContent |
| Keys | assertValidKey, keyProblem, normalizeFolder, slugify, MAX_KEY_LENGTH |
| Protocol | FILEKIT_ROUTES, FILEKIT_API_ROUTES · types UploadRequest, CreateUploadResult, CreateUploadsResult, SingleUploadInstruction, MultipartUploadInstruction, PartInstruction, CompletedPart, StoredObject, FileUrl (alias SignedUrl), ObjectInfo, ListResult, BatchError, HttpMethod, UploadStrategy, TransferMode, AccessMode |
1. Policy
DEFAULT_POLICY
The built-in rules (a frozen ResolvedPolicy):
| Category | Max size | MIME types |
|---|---|---|
| image | 5 MB | jpeg, png, gif, webp, avif, svg+xml, heic, heif |
| video | 25 MB | mp4, webm, quicktime |
| audio | 10 MB | mpeg, wav, ogg, webm, mp4, m4a, x-m4a, aac |
| document | 10 MB | pdf, doc, docx, xls, xlsx, ppt, pptx, plain, csv, markdown, rtf, json, xml, zip |
Plus maxSize 50 MB, minSize 0, multipart { enabled: true, threshold: 10 MB, partSize: 10 MB }, maxBatchSize 10.
resolvePolicy(base?, ...layers)
Applies policy layers on top of a base, in order. Pure — never changes its inputs.
- Parameters:
base: ResolvedPolicy(defaultDEFAULT_POLICY);...layers: (PolicyInput | undefined)[]. - Returns:
ResolvedPolicy(plain JSON). - Throws:
FileKitError('CONFIG_ERROR')— invalid size string, a category left with no MIME types,maxBatchSizenot a positive integer,partSize < 1,minSize > maxSize.
PolicyInput:
{
mode?: 'extend' | 'replace', // 'replace' drops the categories of the layer below
types?: {
[category: string]: false // remove the category
| { mime?: string[]; maxSize?: Size; mode?: 'extend' | 'replace' }, // mime merged unless mode 'replace'
},
only?: string[], // keep only these categories
maxSize?: Size, // overall ceiling
minSize?: Size,
multipart?: false | { threshold?: Size; partSize?: Size },
maxBatchSize?: number,
}const policy = resolvePolicy(
DEFAULT_POLICY,
{ types: { video: { maxSize: '200MB' } }, maxSize: '200MB' }, // global
{ only: ['image'], types: { image: { maxSize: '2MB' } } }, // e.g. an "avatar" profile
);validateFile(policy, file)
Checks one file against a policy.
- Parameters:
policy: ResolvedPolicy;file: { mimeType: string; size: number; filename?: string }. - Returns:
{ category: string; maxSize: number }— the matched category and the limit that applies (smaller of category and overall max). - Throws
FileKitError:
| Code | When |
|---|---|
| INVALID_REQUEST | mimeType empty, or size not a non-negative integer |
| FILE_TYPE_NOT_ALLOWED | no category matches the MIME type (details.mimeType) |
| FILE_TOO_LARGE | size > maxSize (details: { category, maxSize, size }) |
| FILE_TOO_SMALL | size < minSize (details: { minSize, size }) |
categorize(policy, mimeType)
- Returns: the category name, or
undefinedwhen not allowed. - Behaviour: MIME parameters are ignored and case doesn't matter (
IMAGE/PNG; x=y→image/png). An exact match anywhere wins over a wildcard (image/*,*/*).
maxSizeFor(policy, category)
- Returns: the effective byte limit — the category's
maxSizecapped by the overallmaxSize(or the overall max when the category has none).
2. Errors
FileKitError
class FileKitError extends Error {
name: 'FileKitError';
code: FileKitErrorCode;
status: number; // HTTP status for the code
details?: Record<string, unknown>;
constructor(code, message, details?, { cause? }?);
toJSON(): { error: { code, message, details? } }; // what FileKit HTTP routes return
static fromBody(body, fallbackStatus?): FileKitError; // rebuild from such a response body
}FileKitErrorCode
An object of all codes (FileKitErrorCode.FILE_TOO_LARGE === 'FILE_TOO_LARGE'), also usable as a type.
| Code | HTTP | Code | HTTP |
|---|---|---|---|
| INVALID_REQUEST | 400 | PAYLOAD_TOO_LARGE | 413 |
| FILE_TYPE_NOT_ALLOWED | 415 | UNSUPPORTED_MEDIA_TYPE | 415 |
| FILE_TOO_LARGE | 413 | UPLOAD_NOT_FOUND | 409 |
| FILE_TOO_SMALL | 400 | VERIFICATION_FAILED | 422 |
| BATCH_TOO_LARGE | 400 | NOT_FOUND | 404 |
| INVALID_KEY | 400 | PROVIDER_NOT_FOUND | 400 |
| INVALID_TICKET | 400 | NOT_SUPPORTED | 501 |
| TICKET_EXPIRED | 410 | REJECTED | 403 |
| SUBJECT_MISMATCH | 403 | FORBIDDEN | 403 |
| INVALID_TOKEN | 403 | CONFIG_ERROR | 500 |
| TOKEN_EXPIRED | 403 | PROVIDER_ERROR | 502 |
isFileKitError(value)
- Returns:
truewhenvalueis a FileKit error. Duck-typed (name+code), so it works even when two copies of the package end up in one bundle — prefer it overinstanceof.
statusForCode(code)
- Returns: the HTTP status for a code (500 for unknown codes).
const res = await fetch('/api/uploads', { … });
if (!res.ok) throw FileKitError.fromBody(await res.json(), res.status);3. Sizes
| Function | Returns | Notes |
|---|---|---|
| parseSize(value: number \| string) | bytes (integer) | Accepts bytes or '512KB', '25MB', '1.5GB', '2TB' (1 KB = 1024 B, case-insensitive). Throws CONFIG_ERROR on anything else or a negative number. |
| formatBytes(bytes: number) | string | 532 B, 1.5 KB, 25 MB… |
4. MIME types
| Function | Returns | Example |
|---|---|---|
| mimeFromFilename(name) | MIME or undefined | 'Photo.JPG' → 'image/jpeg' |
| extensionFromMime(mime) | extension (no dot) or undefined | 'image/jpeg' → 'jpg' |
| extensionOf(name) | lower-case extension or '' | 'a/b/Report.PDF' → 'pdf'; '.env' → '' |
| normalizeMime(mime) | lower-case, parameters removed | 'Text/Plain; charset=utf-8' → 'text/plain' |
| mimeMatches(pattern, mime) | boolean | mimeMatches('image/*', 'image/png') → true; '*' and '*/*' match all |
| isActiveContent(mime) | boolean | true for HTML, SVG, XML, JavaScript — types a browser could execute; FileKit serves them with a sandboxing CSP |
5. Storage keys
| Export | Returns / does | Notes |
|---|---|---|
| keyProblem(key) | reason string, or null if valid | Rules: non-empty string, ≤ MAX_KEY_LENGTH, no control characters, no \, no leading /, no empty / . / .. segments. |
| assertValidKey(key) | nothing; throws INVALID_KEY | Same rules. |
| normalizeFolder(folder?) | folder without surrounding slashes, '' for none | Throws INVALID_KEY for unsafe folders ('/reports/2026/' → 'reports/2026'). |
| slugify(name, maxLength = 60) | URL- and file-safe lower-case name | Strips accents; 'Résumé Final (v2)' → 'resume-final-v2'; 'file' if nothing is left. |
| MAX_KEY_LENGTH | 1024 | |
6. Protocol
Route constants
FILEKIT_ROUTES = { upload: '/upload', part: '/part', serve: '/serve', public: '/public' };
FILEKIT_API_ROUTES = { info: '/info', createUpload: '/uploads', createUploads: '/uploads/batch',
partUrls: '/uploads/parts', complete: '/uploads/complete', completeBatch: '/uploads/complete/batch',
abort: '/uploads/abort', url: '/files/url', urls: '/files/urls', head: '/files/head',
delete: '/files/delete', list: '/files/list', upload: '/files/upload', content: '/files/content',
copy: '/files/copy', move: '/files/move' };Relative to where the FileKit handler is mounted (e.g. https://api.example.com/filekit).
Types
type HttpMethod = 'PUT' | 'POST';
type UploadStrategy = 'single' | 'multipart';
type TransferMode = 'direct' | 'proxy'; // bytes straight to storage, or through the FileKit handler
type AccessMode = 'public' | 'signed'; // permanent unsigned link, or expiring signed link
// Client → server: start an upload
interface UploadRequest {
filename: string; mimeType: string; size: number; // size = exact bytes
folder?: string; metadata?: Record<string, string>; clientIndex?: number;
}
// Server → client: how to send the bytes
interface CreateUploadResult {
ticket: string; // opaque; send back to complete / abort / refresh parts
key: string; provider: string;
strategy: UploadStrategy; transfer?: TransferMode;
single?: SingleUploadInstruction; // when strategy = 'single'
multipart?: MultipartUploadInstruction; // when strategy = 'multipart'
expiresAt: string; // ISO 8601
clientIndex?: number;
}
interface SingleUploadInstruction {
url: string; method: HttpMethod;
headers: Record<string, string>; // send these
fields?: Record<string, string>; // POST: form fields, appended BEFORE the file
fileField?: string; // POST: form field name for the file
}
interface MultipartUploadInstruction { uploadId: string; partSize: number; totalParts: number; parts: PartInstruction[] }
interface PartInstruction { partNumber: number; url: string; method: HttpMethod; headers: Record<string, string>; expiresAt: string }
interface CompletedPart { partNumber: number; etag?: string } // etag = the part response's ETag
interface CreateUploadsResult { uploads: CreateUploadResult[]; errors: BatchError[] }
interface BatchError { clientIndex: number; filename?: string; code: string; message: string }
// What was stored — apps keep this in their database
interface StoredObject {
key: string; provider: string; bucket?: string;
size: number; mimeType: string; category: string; originalName: string;
etag?: string; metadata?: Record<string, string>;
access?: AccessMode;
uploadedAt: string; // ISO 8601
}
interface FileUrl { url: string; access: AccessMode; expiresAt?: string } // no expiresAt for public links
type SignedUrl = FileUrl; // deprecated alias
interface ObjectInfo { key: string; size: number; mimeType?: string; etag?: string; lastModified?: string; metadata?: Record<string, string> }
interface ListResult { items: ObjectInfo[]; cursor?: string } // cursor absent on the last pageHow a client uses CreateUploadResult (single PUT/POST, parallel parts, then
complete) is shown in the server package's
INTEGRATION.md §17.
