pixel-serve-server 0.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Hiprax
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,207 @@
1
+ # Image Server Middleware
2
+
3
+ A powerful and customizable middleware for processing, resizing, and serving images in Node.js applications. Built with **TypeScript** and powered by **Sharp**, this package allows you to handle local and network images with robust error handling, fallback images, and customizable options.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - πŸ–ΌοΈ **Dynamic Image Resizing and Formatting**
10
+
11
+ - Supports various formats: `jpeg`, `png`, `webp`, `gif`, `tiff`, `avif`, and `svg`.
12
+ - Adjustable dimensions with constraints for safety.
13
+
14
+ - 🌐 **Network and Local File Handling**
15
+
16
+ - Fetches images from allowed network domains.
17
+ - Processes images stored locally with safe path validation.
18
+
19
+ - πŸ”’ **Fallback Images**
20
+
21
+ - Provides fallback images for invalid or missing sources.
22
+
23
+ - πŸ”§ **Highly Configurable**
24
+
25
+ - Flexible option to set base directories, private folders, and user-specific paths.
26
+ - Supports user-defined ID handlers and folder logic.
27
+
28
+ - πŸš€ **Efficient and Scalable**
29
+ - Built on **Sharp** for high-performance image processing.
30
+ - Handles concurrent requests with ease.
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ Install the package using npm or yarn:
37
+
38
+ ```bash
39
+ npm install pixel-serve-server
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Usage
45
+
46
+ ### Basic Setup
47
+
48
+ Here’s how to integrate the middleware with an Express application:
49
+
50
+ ```typescript
51
+ import express from "express";
52
+ import serveImage from "pixel-serve-server";
53
+
54
+ const app = express();
55
+
56
+ const options = {
57
+ baseDir: "/path/to/images", // Base directory for local images
58
+ idHandler: (id: string) => `user-${id}`, // Custom handler for user IDs
59
+ getUserFolder: async (id: string) => `/private/users/${id}`, // Logic for user-specific folder paths
60
+ websiteURL: "example.com", // Your website's base URL
61
+ apiRegex: /^\/api\/v1\//, // Regex for removing API prefixes
62
+ allowedNetworkList: ["trusted.com"], // List of allowed network domains
63
+ };
64
+
65
+ app.get("/api/v1/pixel/serve", (req, res, next) =>
66
+ serveImage(req, res, next, options)
67
+ );
68
+
69
+ app.listen(3000, () => {
70
+ console.log("Server is running on http://localhost:3000");
71
+ });
72
+ ```
73
+
74
+ ---
75
+
76
+ ### Options
77
+
78
+ The `serveImage` middleware accepts the following options:
79
+
80
+ | Option | Type | Description |
81
+ | -------------------- | ---------- | ----------------------------------------------------------- |
82
+ | `baseDir` | `string` | Base directory for local image files. |
83
+ | `idHandler` | `Function` | Function to handle and format user IDs. |
84
+ | `getUserFolder` | `Function` | Async function to resolve a user-specific folder path. |
85
+ | `websiteURL` | `string` | Your website's base URL for identifying internal resources. |
86
+ | `apiRegex` | `RegExp` | Regex to strip API prefixes from internal paths. |
87
+ | `allowedNetworkList` | `string[]` | List of allowed domains for network images. |
88
+
89
+ ---
90
+
91
+ ### Example Requests
92
+
93
+ #### Fetching a Local Image
94
+
95
+ ```bash
96
+ GET http://localhost:3000/images?src=/uploads/image1.jpg&width=300&height=300
97
+ ```
98
+
99
+ #### Fetching a Network Image
100
+
101
+ ```bash
102
+ GET http://localhost:3000/images?src=https://trusted.com/image2.jpg&format=webp
103
+ ```
104
+
105
+ #### Handling Private User Folders
106
+
107
+ ```bash
108
+ GET http://localhost:3000/images?src=/avatar.jpg&folder=private&userId=12345
109
+ ```
110
+
111
+ ---
112
+
113
+ ### User Data Parameters
114
+
115
+ The middleware uses the following `UserData` query parameters:
116
+
117
+ | Parameter | Type | Description |
118
+ | --------- | ----------------------- | ---------------------------------------------------- |
119
+ | `src` | `string` | Path or URL to the image source. |
120
+ | `format` | `ImageFormat` | Desired output format (e.g., `jpeg`, `png`, `webp`). |
121
+ | `width` | `number` | Desired width of the output image. |
122
+ | `height` | `number` | Desired height of the output image. |
123
+ | `quality` | `number` | Image quality (1-100, default: 80). |
124
+ | `folder` | `'public' \| 'private'` | Image folder type (default: `public`). |
125
+ | `userId` | `string \| null` | User ID for private folder access. |
126
+ | `type` | `'normal' \| 'avatar'` | Image type (default: `normal`). |
127
+
128
+ ---
129
+
130
+ ### Image Formats
131
+
132
+ The following image formats are supported:
133
+
134
+ - `jpeg`
135
+ - `jpg`
136
+ - `png`
137
+ - `webp`
138
+ - `gif`
139
+ - `tiff`
140
+ - `avif`
141
+ - `svg`
142
+
143
+ Each format is processed with the specified quality settings.
144
+
145
+ ---
146
+
147
+ ### Advanced Configuration
148
+
149
+ #### Custom ID Handler
150
+
151
+ Use the `idHandler` option to customize how user IDs are formatted.
152
+
153
+ ```typescript
154
+ const options = {
155
+ idHandler: (id) => `user-${id.toUpperCase()}`, // Converts ID to uppercase with "user-" prefix
156
+ };
157
+ ```
158
+
159
+ #### Resolving User Folders
160
+
161
+ The `getUserFolder` function dynamically resolves private folder paths for users.
162
+
163
+ ```typescript
164
+ const options = {
165
+ getUserFolder: async (id) => `/private/data/users/${id}`, // Returns a private directory path
166
+ };
167
+ ```
168
+
169
+ #### Allowed Network Domains
170
+
171
+ Whitelist trusted domains for fetching network images.
172
+
173
+ ```typescript
174
+ const options = {
175
+ allowedNetworkList: ["example.com", "cdn.example.com"], // Only allows images from these domains
176
+ };
177
+ ```
178
+
179
+ ---
180
+
181
+ ### Error Handling
182
+
183
+ The middleware automatically falls back to pre-defined images for errors:
184
+
185
+ | Error Condition | Fallback Behavior |
186
+ | ----------------------------- | ------------------------------- |
187
+ | Invalid local path | Returns a fallback image. |
188
+ | Unsupported network domain | Returns a fallback image. |
189
+ | Invalid or missing parameters | Defaults to placeholder values. |
190
+
191
+ ### Dependencies
192
+
193
+ This package uses the following dependencies:
194
+
195
+ - **Express**: HTTP server framework.
196
+ - **Sharp**: High-performance image processing.
197
+ - **Axios**: HTTP client for fetching network images.
198
+
199
+ ---
200
+
201
+ ### License
202
+
203
+ This package is licensed under the [MIT License](LICENSE).
204
+
205
+ ### Feedback
206
+
207
+ If you encounter issues or have suggestions, feel free to open an [issue](https://github.com/Hiprax/pixel-serve-server/issues).
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,49 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ type ImageType = "avatar" | "normal";
4
+ type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
5
+ type Options = {
6
+ baseDir: string;
7
+ idHandler: (id: string) => string;
8
+ getUserFolder: (id: string, req: Request) => Promise<string>;
9
+ websiteURL: string;
10
+ apiRegex: RegExp;
11
+ allowedNetworkList: string[];
12
+ };
13
+ type UserData = {
14
+ quality: number | string;
15
+ format: ImageFormat;
16
+ src?: string;
17
+ folder?: string;
18
+ type?: ImageType;
19
+ userId?: string;
20
+ width?: number | string;
21
+ height?: number | string;
22
+ };
23
+
24
+ /**
25
+ * @typedef {Object} Options
26
+ * @property {string} baseDir - The base directory for public image files.
27
+ * @property {function(string): string} idHandler - A function to handle user IDs.
28
+ * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.
29
+ * @property {string} websiteURL - The base URL of the website for internal link resolution.
30
+ * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.
31
+ * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.
32
+ */
33
+ /**
34
+ * @function serveImage
35
+ * @description Processes and serves an image based on user data and options.
36
+ * @param {Request} req - The Express request object.
37
+ * @param {Response} res - The Express response object.
38
+ * @param {NextFunction} next - The Express next middleware function.
39
+ * @param {Options} options - The options object for image processing.
40
+ * @returns {Promise<void>}
41
+ */
42
+ declare const serveImage: (req: Request, res: Response, next: NextFunction, options: Options) => Promise<void>;
43
+
44
+ /**
45
+ * @module ImageService
46
+ * @description A module to serve, process, and manage image delivery for web applications.
47
+ */
48
+
49
+ export { type ImageFormat, type ImageType, type Options, type UserData, serveImage as default };
@@ -0,0 +1,49 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ type ImageType = "avatar" | "normal";
4
+ type ImageFormat = "jpeg" | "jpg" | "png" | "webp" | "gif" | "tiff" | "avif" | "svg";
5
+ type Options = {
6
+ baseDir: string;
7
+ idHandler: (id: string) => string;
8
+ getUserFolder: (id: string, req: Request) => Promise<string>;
9
+ websiteURL: string;
10
+ apiRegex: RegExp;
11
+ allowedNetworkList: string[];
12
+ };
13
+ type UserData = {
14
+ quality: number | string;
15
+ format: ImageFormat;
16
+ src?: string;
17
+ folder?: string;
18
+ type?: ImageType;
19
+ userId?: string;
20
+ width?: number | string;
21
+ height?: number | string;
22
+ };
23
+
24
+ /**
25
+ * @typedef {Object} Options
26
+ * @property {string} baseDir - The base directory for public image files.
27
+ * @property {function(string): string} idHandler - A function to handle user IDs.
28
+ * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.
29
+ * @property {string} websiteURL - The base URL of the website for internal link resolution.
30
+ * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.
31
+ * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.
32
+ */
33
+ /**
34
+ * @function serveImage
35
+ * @description Processes and serves an image based on user data and options.
36
+ * @param {Request} req - The Express request object.
37
+ * @param {Response} res - The Express response object.
38
+ * @param {NextFunction} next - The Express next middleware function.
39
+ * @param {Options} options - The options object for image processing.
40
+ * @returns {Promise<void>}
41
+ */
42
+ declare const serveImage: (req: Request, res: Response, next: NextFunction, options: Options) => Promise<void>;
43
+
44
+ /**
45
+ * @module ImageService
46
+ * @description A module to serve, process, and manage image delivery for web applications.
47
+ */
48
+
49
+ export { type ImageFormat, type ImageType, type Options, type UserData, serveImage as default };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var D=Object.create;var d=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty;var B=(e,r)=>{for(var i in r)d(e,i,{get:r[i],enumerable:!0})},U=(e,r,i,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of _(r))!S.call(e,t)&&t!==i&&d(e,t,{get:()=>r[t],enumerable:!(a=M(r,t))||a.enumerable});return e};var g=(e,r,i)=>(i=e!=null?D(C(e)):{},U(r||!e||!e.__esModule?d(i,"default",{value:e,enumerable:!0}):i,e)),P=e=>U(d({},"__esModule",{value:!0}),e);var V={};B(V,{default:()=>K});module.exports=P(V);var G=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,s=G();var R=g(require("path")),F=g(require("sharp"));var I=require("fs/promises"),H=new URL("./assets/noimage.jpg",s).href,$=new URL("./assets/noavatar.png",s).href,p={normal:async()=>(0,I.readFile)(H),avatar:async()=>(0,I.readFile)($)},c=/^\/api\/v1\//,b=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],u={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};var y=g(require("path")),v=require("fs"),O=g(require("fs/promises")),T=g(require("axios"));var k=(e,r)=>{if(!e||!r)return!1;let i=y.default.resolve(e),a=y.default.resolve(i,r);return a.startsWith(i)&&(0,v.existsSync)(a)},z=async(e,r="normal")=>{try{let i=await T.default.get(e,{responseType:"arraybuffer",timeout:5e3}),a=i.headers["content-type"]?.toLowerCase();return Object.values(u).includes(a??"")?Buffer.from(i.data):await p[r]()}catch{return await p[r]()}},x=async(e,r,i="normal")=>{if(!k(r,e))return await p[i]();try{return await O.readFile(y.default.resolve(r,e))}catch{return await p[i]()}},L=(e,r,i,a="normal",t=c,o=[])=>{let n=new URL(e);if([i,`www.${i}`].includes(n.host)){let m=n.pathname.replace(t,"");return x(m,r,a)}else return o.includes(n.host)?z(e,a):p[a]()};var j=e=>({...{baseDir:"",idHandler:i=>i,getUserFolder:async()=>"",websiteURL:"",apiRegex:c,allowedNetworkList:[]},...e}),E=e=>({...{quality:80,format:"jpeg",src:"/placeholder/noimage.jpg",folder:"public",type:"normal",width:void 0,height:void 0,userId:void 0},...e,quality:e.quality?Math.min(Math.max(Number(e.quality)||80,1),100):100,width:e.width?Math.min(Math.max(Number(e.width),50),2e3):void 0,height:e.height?Math.min(Math.max(Number(e.height),50),2e3):void 0});var X=async(e,r,i,a)=>{try{let t=E(e.query),o=j(a),n,f=o.baseDir,m;if(t.userId){let l=typeof t.userId=="object"?String(Object.values(t.userId)[0]):String(t.userId);o.idHandler?m=o.idHandler(l):m=l}t.folder==="private"&&m&&(f=await o.getUserFolder(m,e));let h=b.includes(t.format.toLowerCase())?t.format.toLowerCase():"jpeg";t?.src?.startsWith("http")?n=await L(t.src,f,o.websiteURL,t.type,o.apiRegex):n=await x(t?.src??"",f,t.type);let w=(0,F.default)(n);if(t?.width||t?.height){let l={width:t?.width??void 0,height:t?.height??void 0,fit:F.default.fit.cover};w=w.resize(l)}let q=await w.toFormat(h,{quality:t?.quality?Number(t.quality):80}).toBuffer(),A=`${R.default.basename(t.src??"",R.default.extname(t.src??""))}.${h}`;r.type(u[h]),r.setHeader("Content-Disposition",`inline; filename="${A}"`),r.send(q)}catch(t){i(t)}},N=X;var K=N;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../node_modules/tsup/assets/cjs_shims.js","../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts"],"sourcesContent":["/**\n * @module ImageService\n * @description A module to serve, process, and manage image delivery for web applications.\n */\n\nimport serveImage from \"./pixel\";\nexport * from \"./types\";\n\nexport default serveImage;\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","import path from \"node:path\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next middleware function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\" && parsedUserId) {\n baseDir = await parsedOptions.getUserFolder(parsedUserId, req);\n }\n\n const outputFormat = allowedFormats.includes(\n userData.format.toLowerCase() as ImageFormat\n )\n ? userData.format.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData.src,\n baseDir,\n parsedOptions.websiteURL,\n userData.type as ImageType,\n parsedOptions.apiRegex\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData.src ?? \"\",\n path.extname(userData.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\nexport default serveImage;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url).href;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url).href;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCKA,IAAMI,EAAmB,IACvB,OAAO,SAAa,IAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,KAC7B,SAAS,eAAiB,SAAS,cAAc,KAClD,IAAI,IAAI,UAAW,SAAS,OAAO,EAAE,KAE9BC,EAAgCD,EAAiB,ECX9D,IAAAE,EAAiB,mBACjBC,EAAiD,oBCAjD,IAAAC,EAAyB,uBAEnBC,EAAkB,IAAI,IAAI,uBAAwBC,CAAe,EAAE,KAEnEC,EAAmB,IAAI,IAAI,wBAAyBD,CAAe,EAAE,KAE9DE,EAAiB,CAC5B,OAAQ,YAAY,YAASH,CAAe,EAC5C,OAAQ,YAAY,YAASE,CAAgB,CAC/C,EAEaE,EAAoB,eAEpBC,EAAgC,CAC3C,OACA,MACA,MACA,OACA,MACA,OACA,OACA,KACF,EAEaC,EAA8C,CACzD,KAAM,aACN,IAAK,aACL,IAAK,YACL,KAAM,aACN,IAAK,YACL,KAAM,aACN,KAAM,aACN,IAAK,eACP,EClCA,IAAAC,EAAiB,mBACjBC,EAA2B,cAC3BC,EAAoB,0BACpBC,EAAkB,oBAgBlB,IAAMC,EAAc,CAACC,EAAkBC,IAAmC,CACxE,GAAI,CAACD,GAAY,CAACC,EAAe,MAAO,GACxC,IAAMC,EAAe,EAAAC,QAAK,QAAQH,CAAQ,EACpCI,EAAe,EAAAD,QAAK,QAAQD,EAAcD,CAAa,EAC7D,OAAOG,EAAa,WAAWF,CAAY,MAAK,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AQ,CACvC,IAAMc,EAAgB,CACpB,MAAOd,GAAU,OAAS,OAC1B,OAAQA,GAAU,QAAU,OAC5B,IAAK,EAAAa,QAAM,IAAI,KACjB,EACAD,EAAQA,EAAM,OAAOE,CAA8B,CACrD,CAEA,IAAMC,EAAiB,MAAMH,EAC1B,SAASJ,EAAkC,CAC1C,QAASR,GAAU,QAAU,OAAOA,EAAS,OAAO,EAAI,EAC1D,CAAC,EACA,SAAS,EAENgB,EAAoB,GAAG,EAAAC,QAAK,SAChCjB,EAAS,KAAO,GAChB,EAAAiB,QAAK,QAAQjB,EAAS,KAAO,EAAE,CACjC,CAAC,IAAIQ,CAAY,GAEjBX,EAAI,KAAKqB,EAAUV,CAAY,CAAC,EAChCX,EAAI,UACF,sBACA,qBAAqBmB,CAAiB,GACxC,EACAnB,EAAI,KAAKkB,CAAc,CACzB,OAASI,EAAO,CACdrB,EAAKqB,CAAK,CACZ,CACF,EAEOC,EAAQzB,EFxGf,IAAO0B,EAAQC","names":["index_exports","__export","index_default","__toCommonJS","getImportMetaUrl","importMetaUrl","import_node_path","import_sharp","import_promises","NOT_FOUND_IMAGE","importMetaUrl","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","import_node_path","import_node_fs","fs","import_axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","fetchFromNetwork","src","type","response","axios","contentType","mimeTypes","FALLBACKIMAGES","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","API_REGEX","allowedNetworkList","url","localPath","renderOptions","options","id","API_REGEX","renderUserData","userData","serveImage","req","res","next","options","userData","renderUserData","parsedOptions","renderOptions","imageBuffer","baseDir","parsedUserId","userIdStr","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","pixel_default","index_default","pixel_default"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import U from"node:path";import O from"sharp";import{readFile as I}from"node:fs/promises";var E=new URL("./assets/noimage.jpg",import.meta.url).href,N=new URL("./assets/noavatar.png",import.meta.url).href,m={normal:async()=>I(E),avatar:async()=>I(N)},d=/^\/api\/v1\//,x=["jpeg","jpg","png","webp","gif","tiff","avif","svg"],c={jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",tiff:"image/tiff",avif:"image/avif",svg:"image/svg+xml"};import h from"node:path";import{existsSync as q}from"node:fs";import*as F from"node:fs/promises";import A from"axios";var D=(t,r)=>{if(!t||!r)return!1;let i=h.resolve(t),a=h.resolve(i,r);return a.startsWith(i)&&q(a)},M=async(t,r="normal")=>{try{let i=await A.get(t,{responseType:"arraybuffer",timeout:5e3}),a=i.headers["content-type"]?.toLowerCase();return Object.values(c).includes(a??"")?Buffer.from(i.data):await m[r]()}catch{return await m[r]()}},w=async(t,r,i="normal")=>{if(!D(r,t))return await m[i]();try{return await F.readFile(h.resolve(r,t))}catch{return await m[i]()}},R=(t,r,i,a="normal",e=d,s=[])=>{let o=new URL(t);if([i,`www.${i}`].includes(o.host)){let n=o.pathname.replace(e,"");return w(n,r,a)}else return s.includes(o.host)?M(t,a):m[a]()};var v=t=>({...{baseDir:"",idHandler:i=>i,getUserFolder:async()=>"",websiteURL:"",apiRegex:d,allowedNetworkList:[]},...t}),b=t=>({...{quality:80,format:"jpeg",src:"/placeholder/noimage.jpg",folder:"public",type:"normal",width:void 0,height:void 0,userId:void 0},...t,quality:t.quality?Math.min(Math.max(Number(t.quality)||80,1),100):100,width:t.width?Math.min(Math.max(Number(t.width),50),2e3):void 0,height:t.height?Math.min(Math.max(Number(t.height),50),2e3):void 0});var C=async(t,r,i,a)=>{try{let e=b(t.query),s=v(a),o,l=s.baseDir,n;if(e.userId){let f=typeof e.userId=="object"?String(Object.values(e.userId)[0]):String(e.userId);s.idHandler?n=s.idHandler(f):n=f}e.folder==="private"&&n&&(l=await s.getUserFolder(n,t));let u=x.includes(e.format.toLowerCase())?e.format.toLowerCase():"jpeg";e?.src?.startsWith("http")?o=await R(e.src,l,s.websiteURL,e.type,s.apiRegex):o=await w(e?.src??"",l,e.type);let y=O(o);if(e?.width||e?.height){let f={width:e?.width??void 0,height:e?.height??void 0,fit:O.fit.cover};y=y.resize(f)}let L=await y.toFormat(u,{quality:e?.quality?Number(e.quality):80}).toBuffer(),j=`${U.basename(e.src??"",U.extname(e.src??""))}.${u}`;r.type(c[u]),r.setHeader("Content-Disposition",`inline; filename="${j}"`),r.send(L)}catch(e){i(e)}},T=C;var oe=T;export{oe as default};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pixel.ts","../src/variables.ts","../src/functions.ts","../src/renders.ts","../src/index.ts"],"sourcesContent":["import path from \"node:path\";\nimport sharp, { FormatEnum, ResizeOptions } from \"sharp\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport type { Options, UserData, ImageFormat, ImageType } from \"./types\";\nimport { allowedFormats, mimeTypes } from \"./variables\";\nimport { fetchImage, readLocalImage } from \"./functions\";\nimport { renderOptions, renderUserData } from \"./renders\";\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @function serveImage\n * @description Processes and serves an image based on user data and options.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The Express next middleware function.\n * @param {Options} options - The options object for image processing.\n * @returns {Promise<void>}\n */\nconst serveImage = async (\n req: Request,\n res: Response,\n next: NextFunction,\n options: Options\n) => {\n try {\n const userData = renderUserData(req.query as UserData);\n const parsedOptions = renderOptions(options);\n\n let imageBuffer;\n let baseDir = parsedOptions.baseDir;\n let parsedUserId;\n\n if (userData.userId) {\n const userIdStr =\n typeof userData.userId === \"object\"\n ? String(Object.values(userData.userId)[0])\n : String(userData.userId);\n if (parsedOptions.idHandler) {\n parsedUserId = parsedOptions.idHandler(userIdStr);\n } else {\n parsedUserId = userIdStr;\n }\n }\n\n if (userData.folder === \"private\" && parsedUserId) {\n baseDir = await parsedOptions.getUserFolder(parsedUserId, req);\n }\n\n const outputFormat = allowedFormats.includes(\n userData.format.toLowerCase() as ImageFormat\n )\n ? userData.format.toLowerCase()\n : \"jpeg\";\n\n if (userData?.src?.startsWith(\"http\")) {\n imageBuffer = await fetchImage(\n userData.src,\n baseDir,\n parsedOptions.websiteURL,\n userData.type as ImageType,\n parsedOptions.apiRegex\n );\n } else {\n imageBuffer = await readLocalImage(\n userData?.src ?? \"\",\n baseDir,\n userData.type as ImageType\n );\n }\n\n let image = sharp(imageBuffer);\n\n if (userData?.width || userData?.height) {\n const resizeOptions = {\n width: userData?.width ?? undefined,\n height: userData?.height ?? undefined,\n fit: sharp.fit.cover,\n };\n image = image.resize(resizeOptions as ResizeOptions);\n }\n\n const processedImage = await image\n .toFormat(outputFormat as keyof FormatEnum, {\n quality: userData?.quality ? Number(userData.quality) : 80,\n })\n .toBuffer();\n\n const processedFileName = `${path.basename(\n userData.src ?? \"\",\n path.extname(userData.src ?? \"\")\n )}.${outputFormat}`;\n\n res.type(mimeTypes[outputFormat]);\n res.setHeader(\n \"Content-Disposition\",\n `inline; filename=\"${processedFileName}\"`\n );\n res.send(processedImage);\n } catch (error) {\n next(error);\n }\n};\n\nexport default serveImage;\n","import type { ImageFormat } from \"./types\";\nimport { readFile } from \"node:fs/promises\";\n\nconst NOT_FOUND_IMAGE = new URL(\"./assets/noimage.jpg\", import.meta.url).href;\n\nconst NOT_FOUND_AVATAR = new URL(\"./assets/noavatar.png\", import.meta.url).href;\n\nexport const FALLBACKIMAGES = {\n normal: async () => readFile(NOT_FOUND_IMAGE),\n avatar: async () => readFile(NOT_FOUND_AVATAR),\n};\n\nexport const API_REGEX: RegExp = /^\\/api\\/v1\\//;\n\nexport const allowedFormats: ImageFormat[] = [\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"webp\",\n \"gif\",\n \"tiff\",\n \"avif\",\n \"svg\",\n];\n\nexport const mimeTypes: Readonly<Record<string, string>> = {\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n tiff: \"image/tiff\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n","import path from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport axios from \"axios\";\nimport { mimeTypes, API_REGEX, FALLBACKIMAGES } from \"./variables\";\nimport type { ImageType } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * Checks if a specified path is valid within a base path.\n *\n * @param {string} basePath - The base directory to resolve paths.\n * @param {string} specifiedPath - The path to check.\n * @returns {boolean} True if the path is valid, false otherwise.\n */\nconst isValidPath = (basePath: string, specifiedPath: string): boolean => {\n if (!basePath || !specifiedPath) return false;\n const resolvedBase = path.resolve(basePath);\n const resolvedPath = path.resolve(resolvedBase, specifiedPath);\n return resolvedPath.startsWith(resolvedBase) && existsSync(resolvedPath);\n};\n\n/**\n * Fetches an image from a network source.\n *\n * @param {string} src - The URL of the image.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image in case of an error.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nconst fetchFromNetwork = async (\n src: string,\n type: ImageType = \"normal\"\n): Promise<Buffer> => {\n try {\n const response = await axios.get(src, {\n responseType: \"arraybuffer\",\n timeout: 5000,\n });\n\n const contentType = response.headers[\"content-type\"]?.toLowerCase();\n const allowedMimeTypes = Object.values(mimeTypes);\n\n if (allowedMimeTypes.includes(contentType ?? \"\")) {\n return Buffer.from(response.data);\n }\n return await FALLBACKIMAGES[type]();\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Reads an image from the local file system.\n *\n * @param {string} filePath - Path to the image file.\n * @param {string} baseDir - Base directory to resolve paths.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @returns {Promise<Buffer>} A buffer containing the image data.\n */\nexport const readLocalImage = async (\n filePath: string,\n baseDir: string,\n type: ImageType = \"normal\"\n) => {\n if (!isValidPath(baseDir, filePath)) {\n return await FALLBACKIMAGES[type]();\n }\n try {\n return await fs.readFile(path.resolve(baseDir, filePath));\n } catch (error) {\n return await FALLBACKIMAGES[type]();\n }\n};\n\n/**\n * Fetches an image from either a local file or a network source.\n *\n * @param {string} src - The URL or local path of the image.\n * @param {string} baseDir - Base directory to resolve local paths.\n * @param {string} websiteURL - The URL of the website.\n * @param {ImageType} [type=\"normal\"] - Type of fallback image if the path is invalid.\n * @param {RegExp} [apiRegex=API_REGEX] - Regular expression to match API routes.\n * @param {string[]} [allowedNetworkList=[]] - List of allowed network hosts.\n * @returns {Promise<Buffer>} A buffer containing the image data or a fallback image.\n */\nexport const fetchImage = (\n src: string,\n baseDir: string,\n websiteURL: string,\n type: ImageType = \"normal\",\n apiRegex: RegExp = API_REGEX,\n allowedNetworkList: string[] = []\n) => {\n const url = new URL(src);\n const isInternal = [websiteURL, `www.${websiteURL}`].includes(url.host);\n if (isInternal) {\n const localPath = url.pathname.replace(apiRegex, \"\");\n return readLocalImage(localPath, baseDir, type);\n } else {\n const allowedCondition = allowedNetworkList.includes(url.host);\n if (!allowedCondition) {\n return FALLBACKIMAGES[type]();\n }\n return fetchFromNetwork(src, type);\n }\n};\n","import { API_REGEX } from \"./variables\";\nimport type { Options, UserData } from \"./types\";\n\n/**\n * @typedef {(\"avatar\" | \"normal\")} ImageType\n * @description Defines the type of image being processed.\n */\n\n/**\n * @typedef {(\"jpeg\" | \"jpg\" | \"png\" | \"webp\" | \"gif\" | \"tiff\" | \"avif\" | \"svg\")} ImageFormat\n * @description Supported formats for image processing.\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} baseDir - The base directory for public image files.\n * @property {function(string): string} idHandler - A function to handle user IDs.\n * @property {function(string, Request): Promise<string>} getUserFolder - Asynchronous function to retrieve user-specific folders.\n * @property {string} websiteURL - The base URL of the website for internal link resolution.\n * @property {RegExp} apiRegex - Regex to parse API endpoints from URLs.\n * @property {string[]} allowedNetworkList - List of allowed network domains for external image fetching.\n */\n\n/**\n * @typedef {Object} UserData\n * @property {number|string} quality - Quality of the image (1–100).\n * @property {ImageFormat} format - Desired format of the image.\n * @property {string} [src] - Source path or URL for the image.\n * @property {string} [folder] - The folder type (\"public\" or \"private\").\n * @property {ImageType} [type] - Type of the image (\"avatar\" or \"normal\").\n * @property {string|null} [userId] - Optional user identifier.\n * @property {number|string} [width] - Desired image width.\n * @property {number|string} [height] - Desired image height.\n */\n\n/**\n * Renders the options object with default values and user-provided values.\n *\n * @param {Partial<Options>} options - The user-provided options.\n * @returns {Options} The rendered options object.\n */\nexport const renderOptions = (options: Partial<Options>): Options => {\n const initialOptions: Options = {\n baseDir: \"\",\n idHandler: (id: string) => id,\n getUserFolder: async () => \"\",\n websiteURL: \"\",\n apiRegex: API_REGEX,\n allowedNetworkList: [],\n };\n return {\n ...initialOptions,\n ...options,\n };\n};\n\n/**\n * Renders the user data object with default values and user-provided values.\n *\n * @param {Partial<UserData>} userData - The user-provided data.\n * @returns {UserData} The rendered user data object.\n */\nexport const renderUserData = (userData: Partial<UserData>): UserData => {\n const initialUserData: UserData = {\n quality: 80,\n format: \"jpeg\",\n src: \"/placeholder/noimage.jpg\",\n folder: \"public\",\n type: \"normal\",\n width: undefined,\n height: undefined,\n userId: undefined,\n };\n return {\n ...initialUserData,\n ...userData,\n quality: userData.quality\n ? Math.min(Math.max(Number(userData.quality) || 80, 1), 100)\n : 100,\n width: userData.width\n ? Math.min(Math.max(Number(userData.width), 50), 2000)\n : undefined,\n height: userData.height\n ? Math.min(Math.max(Number(userData.height), 50), 2000)\n : undefined,\n };\n};\n","/**\n * @module ImageService\n * @description A module to serve, process, and manage image delivery for web applications.\n */\n\nimport serveImage from \"./pixel\";\nexport * from \"./types\";\n\nexport default serveImage;\n"],"mappings":"AAAA,OAAOA,MAAU,YACjB,OAAOC,MAA0C,QCAjD,OAAS,YAAAC,MAAgB,mBAEzB,IAAMC,EAAkB,IAAI,IAAI,uBAAwB,YAAY,GAAG,EAAE,KAEnEC,EAAmB,IAAI,IAAI,wBAAyB,YAAY,GAAG,EAAE,KAE9DC,EAAiB,CAC5B,OAAQ,SAAYH,EAASC,CAAe,EAC5C,OAAQ,SAAYD,EAASE,CAAgB,CAC/C,EAEaE,EAAoB,eAEpBC,EAAgC,CAC3C,OACA,MACA,MACA,OACA,MACA,OACA,OACA,KACF,EAEaC,EAA8C,CACzD,KAAM,aACN,IAAK,aACL,IAAK,YACL,KAAM,aACN,IAAK,YACL,KAAM,aACN,KAAM,aACN,IAAK,eACP,EClCA,OAAOC,MAAU,YACjB,OAAS,cAAAC,MAAkB,UAC3B,UAAYC,MAAQ,mBACpB,OAAOC,MAAW,QAgBlB,IAAMC,EAAc,CAACC,EAAkBC,IAAmC,CACxE,GAAI,CAACD,GAAY,CAACC,EAAe,MAAO,GACxC,IAAMC,EAAeC,EAAK,QAAQH,CAAQ,EACpCI,EAAeD,EAAK,QAAQD,EAAcD,CAAa,EAC7D,OAAOG,EAAa,WAAWF,CAAY,GAAKG,EAAWD,CAAY,CACzE,EASME,EAAmB,MACvBC,EACAC,EAAkB,WACE,CACpB,GAAI,CACF,IAAMC,EAAW,MAAMC,EAAM,IAAIH,EAAK,CACpC,aAAc,cACd,QAAS,GACX,CAAC,EAEKI,EAAcF,EAAS,QAAQ,cAAc,GAAG,YAAY,EAGlE,OAFyB,OAAO,OAAOG,CAAS,EAE3B,SAASD,GAAe,EAAE,EACtC,OAAO,KAAKF,EAAS,IAAI,EAE3B,MAAMI,EAAeL,CAAI,EAAE,CACpC,MAAgB,CACd,OAAO,MAAM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CAAC,IAAIQ,CAAY,GAEjBX,EAAI,KAAKqB,EAAUV,CAAY,CAAC,EAChCX,EAAI,UACF,sBACA,qBAAqBmB,CAAiB,GACxC,EACAnB,EAAI,KAAKkB,CAAc,CACzB,OAASI,EAAO,CACdrB,EAAKqB,CAAK,CACZ,CACF,EAEOC,EAAQzB,EIxGf,IAAO0B,GAAQC","names":["path","sharp","readFile","NOT_FOUND_IMAGE","NOT_FOUND_AVATAR","FALLBACKIMAGES","API_REGEX","allowedFormats","mimeTypes","path","existsSync","fs","axios","isValidPath","basePath","specifiedPath","resolvedBase","path","resolvedPath","existsSync","fetchFromNetwork","src","type","response","axios","contentType","mimeTypes","FALLBACKIMAGES","readLocalImage","filePath","baseDir","fetchImage","websiteURL","apiRegex","API_REGEX","allowedNetworkList","url","localPath","renderOptions","options","id","API_REGEX","renderUserData","userData","serveImage","req","res","next","options","userData","renderUserData","parsedOptions","renderOptions","imageBuffer","baseDir","parsedUserId","userIdStr","outputFormat","allowedFormats","fetchImage","readLocalImage","image","sharp","resizeOptions","processedImage","processedFileName","path","mimeTypes","error","pixel_default","index_default","pixel_default"]}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "pixel-serve-server",
3
+ "version": "0.0.1",
4
+ "description": "A robust Node.js utility for handling and processing images. This package provides features like resizing, format conversion and etc.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsup"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "dist/assets"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Hiprax/pixel-serve-server.git"
18
+ },
19
+ "keywords": [
20
+ "Pixel Serve",
21
+ "Image",
22
+ "Image Serving",
23
+ "Image Optimization",
24
+ "Image Resizing",
25
+ "Image Formatting",
26
+ "Image Transformation"
27
+ ],
28
+ "author": "Hiprax",
29
+ "license": "MIT",
30
+ "bugs": {
31
+ "url": "https://github.com/Hiprax/pixel-serve-server/issues"
32
+ },
33
+ "homepage": "https://github.com/Hiprax/pixel-serve-server#readme",
34
+ "devDependencies": {
35
+ "@types/express": "^5.0.0",
36
+ "@types/node": "^22.10.5",
37
+ "tsup": "^8.3.5",
38
+ "typescript": "^5.7.3"
39
+ },
40
+ "engines": {
41
+ "node": ">=8.x"
42
+ },
43
+ "dependencies": {
44
+ "axios": "^1.7.9",
45
+ "express": "^4.21.2",
46
+ "sharp": "^0.33.5"
47
+ }
48
+ }