Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: added jsdocs to exported functions and types #222

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 62 additions & 1 deletion src/ipx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,37 @@ import type { IPXStorage } from "./types";
import { HandlerName, applyHandler, getHandler } from "./handlers";
import { cachedPromise, getEnv } from "./utils";

type IPXSourceMeta = { mtime?: Date; maxAge?: number };
type IPXSourceMeta = {
/**
* The modification time of the source. Used for cache validation.
* @optional
*/
mtime?: Date;

/**
* The maximum age (in seconds) that the source should be considered fresh.
* @optional
*/
maxAge?: number;
};

/**
* A function type that defines an IPX image processing instance.
*
* This function takes an image identifier and optional modifiers and request options, then provides methods to retrieve
* image metadata and process the image according to the specified modifiers.
*
* @param {string} id - The identifier for the image. This can be a URL or a path, depending on the storage implementation.
* @param {partial<Record<HandlerName | "f" | "format" | "a" | "animated", string>>} [modifiers] - Modifiers to be applied to the image,
* such as resizing, cropping or format conversion. This record contains predefined keys such as 'f' or 'format' to specify the output to
* specify the output image format, and 'a' or 'animated' to specify whether the image should be processed as an animation. See
* {@link HandlerName}.
* @param {any} [requestOptions] - Additional options that may be needed for request handling, specific to the storage backend.
* Returns an object with methods:
* - `getSourceMeta`: A method that returns a promise resolving to the source image metadata (`IPXSourceMeta`).
* - `process`: A method that returns a promise resolving to an object containing the processed image data, metadata,
* and format. The image data can be in the form of a `buffer` or a string, depending on the format and processing.
*/
export type IPX = (
id: string,
modifiers?: Partial<
Expand All @@ -26,13 +55,39 @@ export type IPX = (
};

export type IPXOptions = {
/**
* Default cache duration in seconds. If not specified, a default of 1 minute is used.
* @optional
*/
maxAge?: number;

/**
* A mapping of URL aliases to their corresponding URLs, used to simplify resource identifiers.
* @optional
*/
alias?: Record<string, string>;

/**
* Configuration options for the Sharp image processing library.
* @optional
*/
sharpOptions?: SharpOptions;

/**
* Primary storage backend for handling image assets.
*/
storage: IPXStorage;

/**
* An optional secondary storage backend used when images are fetched via HTTP.
* @optional
*/
httpStorage?: IPXStorage;

/**
* Configuration for the SVGO library used when processing SVG images.
* @optional
*/
svgo?: false | SVGOConfig;
};

Expand All @@ -49,6 +104,12 @@ const SUPPORTED_FORMATS = new Set([
"heic",
]);

/**
* Creates an IPX image processing instance with the specified options.
* @param {IPXOptions} userOptions - Configuration options for the IPX instance. See {@link IPXOptions}.
* @returns {IPX} An IPX processing function configured with the given options. See {@link IPX}.
* @throws {Error} If critical options such as storage are missing or incorrectly configured.
*/
export function createIPX(userOptions: IPXOptions): IPX {
const options: IPXOptions = defu(userOptions, {
alias: getEnv<Record<string, string>>("IPX_ALIAS") || {},
Expand Down
27 changes: 27 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ import { IPX } from "./ipx";
const MODIFIER_SEP = /[&,]/g;
const MODIFIER_VAL_SEP = /[:=_]/;

/**
* Creates an H3 handler to handle images using IPX.
* @param {IPX} ipx - An IPX instance to handle image requests.
* @returns {H3Event} An H3 event handler that processes image requests, applies modifiers, handles caching,
* and returns the processed image data. See {@link H3Event}.
* @throws {H3Error} If there are problems with the request parameters or processing the image. See {@link H3Error}.
*/
export function createIPXH3Handler(ipx: IPX) {
const _handler = async (event: H3Event) => {
// Parse URL
Expand Down Expand Up @@ -153,20 +160,40 @@ export function createIPXH3Handler(ipx: IPX) {
});
}

/**
* Creates an H3 application configured to handle image processing using a supplied IPX instance.
* @param {IPX} ipx - An IPX instance to handle image handling requests.
* @returns {any} An H3 application configured to use the IPX image handler.
*/
export function createIPXH3App(ipx: IPX) {
const app = createApp({ debug: true });
app.use(createIPXH3Handler(ipx));
return app;
}

/**
* Creates a web server that can handle IPX image processing requests using an H3 application.
* @param {IPX} ipx - An IPX instance configured for the server. See {@link IPX}.
* @returns {any} A web handler suitable for use with web server environments that support the H3 library.
*/
export function createIPXWebServer(ipx: IPX) {
return toWebHandler(createIPXH3App(ipx));
}

/**
* Creates a web server that can handle IPX image processing requests using an H3 application.
* @param {IPX} ipx - An IPX instance configured for the server. See {@link IPX}.
* @returns {any} A web handler suitable for use with web server environments that support the H3 library.
*/
export function createIPXNodeServer(ipx: IPX) {
return toNodeListener(createIPXH3App(ipx));
}

/**
* Creates a simple server that can handle IPX image processing requests using an H3 application.
* @param {IPX} ipx - An IPX instance configured for the server.
* @returns {any} A handler suitable for plain HTTP server environments that support the H3 library.
*/
export function createIPXPlainServer(ipx: IPX) {
return toPlainHandler(createIPXH3App(ipx));
}
Expand Down
32 changes: 32 additions & 0 deletions src/storage/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,47 @@ import { getEnv } from "../utils";
import type { IPXStorage } from "../types";

export type HTTPStorageOptions = {
/**
* Custom options for fetch operations, such as headers or method overrides.
* @optional
*/
fetchOptions?: RequestInit;

/**
* Default maximum age (in seconds) for cache control. If not specified, defaults to the environment setting or 300 seconds.
* @optional
*/
maxAge?: number;

/**
* Whitelist of domains from which resource fetching is allowed. Can be a single string or an array of strings.
* @optional
*/
domains?: string | string[];

/**
* If set to true, allows retrieval from any domain. Overrides the domain whitelist.
* @optional
*/
allowAllDomains?: boolean;

/**
* If set to true, ignore the cache control header in responses and use the default or specified maxAge.
* @optional
*/
ignoreCacheControl?: boolean;
};

const HTTP_RE = /^https?:\/\//;

/**
* Creates an HTTP storage handler for IPX that fetches image data from external URLs.
* This handler allows configuration to specify allowed domains, caching behaviour and custom fetch options.
*
* @param {HTTPStorageOptions} [_options={}] - Configuration options for HTTP storage, with defaults possibly taken from environment variables. See {@link HTTPStorageOptions}.
* @returns {IPXStorage} An IPXStorage interface implementation for retrieving images over HTTP. See {@link IPXStorage}.
* @throws {H3Error} If validation of the requested URL fails due to a missing hostname or denied host access. See {@link H3Error}.
*/
export function ipxHttpStorage(_options: HTTPStorageOptions = {}): IPXStorage {
const allowAllDomains =
_options.allowAllDomains ?? getEnv("IPX_HTTP_ALLOW_ALL_DOMAINS") ?? false;
Expand Down
17 changes: 17 additions & 0 deletions src/storage/node-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,27 @@ import { cachedPromise, getEnv } from "../utils";
import type { IPXStorage } from "../types";

export type NodeFSSOptions = {
/**
* The directory or list of directories from which to serve files. If not specified, the current directory is used by default.
* @optional
*/
dir?: string | string[];

/**
* The directory or list of directories from which to serve files. If not specified, the current directory is used by default.
* @optional
*/
maxAge?: number;
};

/**
* Creates a file system storage handler for IPX that allows images to be served from local directories specified in the options.
* This handler resolves directories and handles file access, ensuring that files are served safely.
*
* @param {NodeFSSOptions} [_options={}] - File system storage configuration options, with optional directory paths and caching configuration. See {@link NodeFSSOptions}.
* @returns {IPXStorage} An implementation of the IPXStorage interface for accessing images stored on the local file system. See {@link IPXStorage}.
* @throws {H3Error} If there is a problem accessing the file system module or resolving/reading files. See {@link H3Error}.
*/
export function ipxFSStorage(_options: NodeFSSOptions = {}): IPXStorage {
const dirs = resolveDirs(_options.dir);
const maxAge = _options.maxAge || getEnv("IPX_FS_MAX_AGE");
Expand Down
13 changes: 13 additions & 0 deletions src/storage/unstorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,22 @@ import { createError } from "h3";
import type { IPXStorage, IPXStorageMeta } from "../types";

export type UnstorageIPXStorageOptions = {
/**
* Optional prefix to be placed in front of each storage key, which can help to name or categorise stored items.
* @optional
*/
prefix?: string;
};

/**
* Adapts an Unstorage driver or storage system to comply with the IPXStorage interface required by IPX.
* This allows various Unstorage-compatible storage systems to be used to manage image data with IPX.
*
* @param {Storage | Driver} storage - The Unstorage driver or storage instance to adapt. See {@link Storage} and {@link Driver}.
* @param {UnstorageIPXStorageOptions | string} [_options={}] - Configuration options for the adapter, which can be a simple string prefix or an options object. See {@link UnstorageIPXStorageOptions}.
* @returns {IPXStorage}. An IPXStorage compliant object that implements the necessary methods to interact with the provided unstorage driver or storage system. See {@link IPXStorage}.
* @throws {H3Error} If there is a problem retrieving or converting the storage data, detailed error information is thrown. See {@link H3Error}.
*/
export function unstorageToIPXStorage(
storage: Storage | Driver,
_options: UnstorageIPXStorageOptions | string = {},
Expand Down
75 changes: 75 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,115 @@ import type { Sharp, Color, KernelEnum } from "sharp";
// ---- Handlers ----

export interface HandlerContext {
/**
* Optional quality setting for the output image, affects compression in certain formats.
* @optional
*/
quality?: number;

/**
* Specifies the method to fit the image to the dimensions provided, e.g., 'contain', 'cover'.
* @optional
*/
fit?: "contain" | "cover" | "fill" | "inside" | "outside";

/**
* The position used for cropping or positioning, specified as a number or string.
* @optional
*/
position?: number | string;

/**
* Background colour to be used if necessary, provided as a colour object. See {@link Color}.
* @optional
*/
background?: Color;

/**
* Specifies whether to enlarge the image if it is smaller than the desired size.
* @optional
*/
enlarge?: boolean;

/**
* The type of kernel to use for image operations such as resizing. See {@link KernelEnum}.
* @optional
*/
kernel?: keyof KernelEnum;

/**
* Metadata about the image being processed.
*/
meta: ImageMeta;
}

export interface Handler {
/**
* An array of functions that convert the given string arguments into usable forms.
*/
args: ((argument: string) => any)[];

/**
* Defines the order in which this handler should be applied relative to other handlers.
* @optional
*/
order?: number;

/**
* Function to apply the effects of this handler to the image pipeline.
* @param {HandlerContext} context - The current image processing context. See {@link HandlerContext}.
* @param {Sharp} pipe - The Sharp instance to use for image processing. See {@link Sharp}.
* @param {...any} arguments_ - Transformed arguments to use in the handler.
*/
apply: (context: HandlerContext, pipe: Sharp, ...arguments_: any[]) => any;
}

// ---- Storage ----

export type IPXStorageMeta = {
/**
* The modification time of the stored item.
* @optional
*/
mtime?: Date | number | string;

/**
* The maximum age (in seconds) at which the stored item should be considered fresh.
* @optional
*/
maxAge?: number | string;
};

/**
* Options specific to image saving operations.
*/
export type IPXStorageOptions = Record<string, unknown>;

type MaybePromise<T> = T | Promise<T>;

export interface IPXStorage {
/**
* A descriptive name for the storage type.
*/
name: string;

/**
* Retrieves metadata for an image identified by 'id'.
* @param {string} id - The identifier for the image.
* @param {IPXStorageOptions} [opts] - Optional metadata retrieval options. See {@link IPXStorageOptions}.
* @returns {MaybePromise<IPXStorageMeta | undefined>} A promise or direct return of the metadata, or undefined if not found. See {@link IPXStorageMeta}.
*/
getMeta: (
id: string,
opts?: IPXStorageOptions,
) => MaybePromise<IPXStorageMeta | undefined>;

/**
* Get the actual data for an image identified by 'id'.
* @param {string} id - The identifier for the image.
* @param {IPXStorageOptions} [opts] - Optional options for the data retrieval. See {@link IPXStorageOptions}.
* @returns {MaybePromise<ArrayBuffer | undefined>} A promise or direct return of the image data as an ArrayBuffer, or undefined if not found. See {@link ArrayBuffer}.
*/
getData: (
id: string,
opts?: IPXStorageOptions,
Expand Down