@imageconvertit/mcp-server 0.0.0-stage → 0.3.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.
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Shared local batch runner — path-only I/O, authorize meter, concurrency ≤3.
3
+ */
4
+
5
+ import fs from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { authorizeBatch } from '../authorize.js';
8
+
9
+ export const MAX_BATCH = 50;
10
+ export const MAX_CONCURRENCY = 3;
11
+
12
+ const IMAGE_EXTS = new Set([
13
+ '.jpg', '.jpeg', '.png', '.webp', '.tif', '.tiff', '.avif', '.gif', '.bmp',
14
+ '.heic', '.heif',
15
+ ]);
16
+
17
+ /**
18
+ * @param {string[]} items
19
+ * @param {number} limit
20
+ * @param {(item: any, idx: number) => Promise<any>} fn
21
+ */
22
+ export async function mapPool(items, limit, fn) {
23
+ const results = new Array(items.length);
24
+ let i = 0;
25
+ async function worker() {
26
+ while (i < items.length) {
27
+ const idx = i++;
28
+ results[idx] = await fn(items[idx], idx);
29
+ }
30
+ }
31
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
32
+ return results;
33
+ }
34
+
35
+ /**
36
+ * @param {string} dir
37
+ * @param {{ exts?: Set<string> }} [opts]
38
+ */
39
+ export async function listFiles(dir, opts = {}) {
40
+ const exts = opts.exts || IMAGE_EXTS;
41
+ const entries = await fs.readdir(dir, { withFileTypes: true });
42
+ return entries
43
+ .filter((e) => e.isFile() && exts.has(path.extname(e.name).toLowerCase()))
44
+ .map((e) => path.join(dir, e.name))
45
+ .sort();
46
+ }
47
+
48
+ /**
49
+ * @param {object} env
50
+ * @param {{
51
+ * inputDir: string,
52
+ * outputDir: string,
53
+ * processOne: (file: string, outDir: string) => Promise<{ out: string } | { error: string }>,
54
+ * exts?: Set<string>,
55
+ * skipAuthorize?: boolean,
56
+ * }} opts
57
+ */
58
+ export async function runFolderBatch(env, opts) {
59
+ const inputDir = path.resolve(opts.inputDir);
60
+ const outputDir = path.resolve(opts.outputDir);
61
+ const files = await listFiles(inputDir, { exts: opts.exts });
62
+ if (files.length === 0) {
63
+ return { ok: false, error: 'No matching files in inputDir.', processed: 0 };
64
+ }
65
+ if (files.length > MAX_BATCH) {
66
+ return {
67
+ ok: false,
68
+ error: `Batch too large (${files.length}). Max ${MAX_BATCH} files per call — split the folder.`,
69
+ processed: 0,
70
+ };
71
+ }
72
+
73
+ let auth = { allowed: true, remaining: null, limit: null, plan: null };
74
+ if (!opts.skipAuthorize) {
75
+ auth = await authorizeBatch({
76
+ licenseKey: env.ICI_LICENSE_KEY,
77
+ fileCount: files.length,
78
+ apiBase: env.ICI_API_BASE,
79
+ });
80
+ if (!auth.allowed) {
81
+ return {
82
+ ok: false,
83
+ error: auth.error,
84
+ remaining: auth.remaining,
85
+ limit: auth.limit,
86
+ processed: 0,
87
+ paywall: true,
88
+ };
89
+ }
90
+ }
91
+
92
+ await fs.mkdir(outputDir, { recursive: true });
93
+
94
+ const results = await mapPool(files, MAX_CONCURRENCY, async (file) => {
95
+ try {
96
+ return await opts.processOne(file, outputDir);
97
+ } catch (e) {
98
+ return { error: e?.message ?? String(e), in: file };
99
+ }
100
+ });
101
+
102
+ const ok = results.filter((r) => r && r.out);
103
+ const failed = results.filter((r) => r && r.error);
104
+
105
+ // Refund meter for files that failed after charge-first authorize
106
+ let remaining = auth.remaining;
107
+ if (!opts.skipAuthorize && failed.length > 0) {
108
+ try {
109
+ const refund = await authorizeBatch({
110
+ licenseKey: env.ICI_LICENSE_KEY,
111
+ fileCount: failed.length,
112
+ apiBase: env.ICI_API_BASE,
113
+ action: 'refund',
114
+ });
115
+ if (refund.allowed && typeof refund.remaining === 'number') {
116
+ remaining = refund.remaining;
117
+ }
118
+ } catch { /* non-fatal */ }
119
+ }
120
+
121
+ return {
122
+ ok: failed.length === 0,
123
+ processed: ok.length,
124
+ failed: failed.length,
125
+ remaining,
126
+ limit: auth.limit,
127
+ plan: auth.plan,
128
+ outputs: ok.map((r) => r.out),
129
+ errors: failed.length ? failed.map((r) => ({ file: r.in, error: r.error })) : undefined,
130
+ };
131
+ }
132
+
133
+ export function outPath(file, outputDir, ext) {
134
+ const base = path.parse(file).name;
135
+ const e = ext.startsWith('.') ? ext : `.${ext}`;
136
+ return path.join(outputDir, `${base}${e}`);
137
+ }
138
+
139
+ export function parseHexColor(hex, fallback = { r: 255, g: 255, b: 255, alpha: 1 }) {
140
+ if (!hex || typeof hex !== 'string') return fallback;
141
+ let h = hex.trim().replace('#', '');
142
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
143
+ if (!/^[0-9a-fA-F]{6}$/.test(h)) return fallback;
144
+ return {
145
+ r: parseInt(h.slice(0, 2), 16),
146
+ g: parseInt(h.slice(2, 4), 16),
147
+ b: parseInt(h.slice(4, 6), 16),
148
+ alpha: 1,
149
+ };
150
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Mint + cache api_token for Cloud AI MCP tools.
3
+ * Uses the same /api/auth/token path as the website.
4
+ * Never touches FAL / FASHN / GROQ keys — those stay server-side only.
5
+ *
6
+ * Cache is keyed by license fingerprint so switching ICI_LICENSE_KEY
7
+ * does not keep charging the previous account.
8
+ */
9
+
10
+ import crypto from 'node:crypto';
11
+ import fs from 'node:fs/promises';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+
15
+ const DEFAULT_BASE = 'https://imageconvertit.com';
16
+ const CACHE_DIR = path.join(os.homedir(), '.imageconvertit');
17
+ const DEVICE_FILE = path.join(CACHE_DIR, 'device_id');
18
+
19
+ /** In-process cache (per MCP process). */
20
+ let memToken = null; // { api_token, exp, credits, plan, license_fp, api_base }
21
+
22
+ function licenseFingerprint(licenseKey) {
23
+ return crypto.createHash('sha256').update(String(licenseKey || '')).digest('hex').slice(0, 24);
24
+ }
25
+
26
+ function tokenCachePath(licenseKey, apiBase) {
27
+ const fp = licenseFingerprint(licenseKey);
28
+ const baseFp = crypto.createHash('sha256').update(String(apiBase || DEFAULT_BASE)).digest('hex').slice(0, 8);
29
+ return path.join(CACHE_DIR, `api_token_${fp}_${baseFp}.json`);
30
+ }
31
+
32
+ function decodeJwtExp(token) {
33
+ try {
34
+ const part = String(token).split('.')[1];
35
+ if (!part) return 0;
36
+ const json = Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
37
+ const payload = JSON.parse(json);
38
+ return typeof payload.exp === 'number' ? payload.exp : 0;
39
+ } catch {
40
+ return 0;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Stable alphanumeric device id for seat binding (8–128 chars).
46
+ * Prefer ICI_DEVICE_ID; else persist a generated id under ~/.imageconvertit/.
47
+ */
48
+ export async function resolveDeviceId(env = {}) {
49
+ const fromEnv = typeof env.ICI_DEVICE_ID === 'string' ? env.ICI_DEVICE_ID.trim() : '';
50
+ if (/^[a-zA-Z0-9_-]{8,128}$/.test(fromEnv)) return fromEnv;
51
+
52
+ try {
53
+ const existing = (await fs.readFile(DEVICE_FILE, 'utf8')).trim();
54
+ if (/^[a-zA-Z0-9_-]{8,128}$/.test(existing)) return existing;
55
+ } catch { /* create below */ }
56
+
57
+ const seed = `${os.hostname()}|${os.userInfo()?.username || 'user'}|${os.platform()}|${os.arch()}`;
58
+ const hash = crypto.createHash('sha256').update(seed).digest('hex').slice(0, 32);
59
+ const id = `mcp_${hash}`;
60
+ try {
61
+ await fs.mkdir(CACHE_DIR, { recursive: true });
62
+ await fs.writeFile(DEVICE_FILE, id, { encoding: 'utf8', mode: 0o600 });
63
+ } catch { /* non-fatal — still return id */ }
64
+ return id;
65
+ }
66
+
67
+ async function readDiskToken(licenseKey, apiBase) {
68
+ try {
69
+ const raw = await fs.readFile(tokenCachePath(licenseKey, apiBase), 'utf8');
70
+ const json = JSON.parse(raw);
71
+ if (typeof json?.api_token === 'string' && json.api_token.length > 20) return json;
72
+ } catch { /* miss */ }
73
+ return null;
74
+ }
75
+
76
+ async function writeDiskToken(licenseKey, apiBase, entry) {
77
+ try {
78
+ await fs.mkdir(CACHE_DIR, { recursive: true });
79
+ await fs.writeFile(
80
+ tokenCachePath(licenseKey, apiBase),
81
+ JSON.stringify(entry),
82
+ { encoding: 'utf8', mode: 0o600 },
83
+ );
84
+ } catch { /* non-fatal */ }
85
+ }
86
+
87
+ function tokenStillValid(entry) {
88
+ if (!entry?.api_token) return false;
89
+ const exp = entry.exp || decodeJwtExp(entry.api_token);
90
+ // Refresh 5 minutes early
91
+ return exp > Math.floor(Date.now() / 1000) + 300;
92
+ }
93
+
94
+ /**
95
+ * Obtain a Bearer api_token for /api/run-ai.
96
+ * @param {{ ICI_LICENSE_KEY?: string, ICI_API_BASE?: string, ICI_DEVICE_ID?: string, ICI_API_TOKEN?: string }} env
97
+ */
98
+ export async function ensureApiToken(env = {}) {
99
+ const direct = typeof env.ICI_API_TOKEN === 'string' ? env.ICI_API_TOKEN.trim() : '';
100
+ if (direct.startsWith('eyJ') && tokenStillValid({ api_token: direct })) {
101
+ return { api_token: direct, device_id: await resolveDeviceId(env), credits: null, plan: null };
102
+ }
103
+
104
+ const licenseKey = typeof env.ICI_LICENSE_KEY === 'string' ? env.ICI_LICENSE_KEY.trim() : '';
105
+ const base = (env.ICI_API_BASE || DEFAULT_BASE).replace(/\/$/, '');
106
+ const fp = licenseFingerprint(licenseKey);
107
+
108
+ if (memToken && memToken.license_fp === fp && memToken.api_base === base && tokenStillValid(memToken)) {
109
+ return { ...memToken, device_id: await resolveDeviceId(env) };
110
+ }
111
+
112
+ if (licenseKey && !licenseKey.startsWith('eyJ')) {
113
+ const disk = await readDiskToken(licenseKey, base);
114
+ if (disk && disk.license_fp === fp && tokenStillValid(disk)) {
115
+ memToken = disk;
116
+ return { ...disk, device_id: await resolveDeviceId(env) };
117
+ }
118
+ }
119
+
120
+ if (!licenseKey || licenseKey.startsWith('eyJ')) {
121
+ return {
122
+ error:
123
+ 'ICI_LICENSE_KEY is required for Cloud AI (LemonSqueezy key with credits, or MCP Pro’s included AI).',
124
+ };
125
+ }
126
+
127
+ const device_id = await resolveDeviceId(env);
128
+
129
+ let res;
130
+ try {
131
+ res = await fetch(`${base}/api/auth/token`, {
132
+ method: 'POST',
133
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
134
+ body: JSON.stringify({ license_key: licenseKey, device_id }),
135
+ });
136
+ } catch (e) {
137
+ return { error: `Network error minting API token: ${e?.message ?? e}` };
138
+ }
139
+
140
+ let json = null;
141
+ try {
142
+ json = await res.json();
143
+ } catch {
144
+ return { error: `Token endpoint failed (${res.status}).` };
145
+ }
146
+
147
+ if (!res.ok || typeof json?.api_token !== 'string') {
148
+ return {
149
+ error: json?.error || `Could not obtain API token (${res.status}). Activate your license on imageconvertit.com first if needed.`,
150
+ };
151
+ }
152
+
153
+ const entry = {
154
+ api_token: json.api_token,
155
+ exp: decodeJwtExp(json.api_token),
156
+ credits: typeof json.credits === 'number' ? json.credits : null,
157
+ plan: typeof json.plan === 'string' ? json.plan : null,
158
+ minted_at: Date.now(),
159
+ license_fp: fp,
160
+ api_base: base,
161
+ };
162
+ memToken = entry;
163
+ await writeDiskToken(licenseKey, base, entry);
164
+ return { ...entry, device_id };
165
+ }
166
+
167
+ /** Drop cached token after 401 so next call re-mints. */
168
+ export async function clearApiTokenCache(env = {}) {
169
+ memToken = null;
170
+ const licenseKey = typeof env.ICI_LICENSE_KEY === 'string' ? env.ICI_LICENSE_KEY.trim() : '';
171
+ const base = (env.ICI_API_BASE || DEFAULT_BASE).replace(/\/$/, '');
172
+ if (licenseKey) {
173
+ try { await fs.unlink(tokenCachePath(licenseKey, base)); } catch { /* ignore */ }
174
+ }
175
+ // Also remove legacy unkeyed cache if present
176
+ try { await fs.unlink(path.join(CACHE_DIR, 'api_token_cache.json')); } catch { /* ignore */ }
177
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Production image helpers for MCP — sharp-based ports of website canvasOps
3
+ * (align bbox, BCS adjust, pad-to-square, encode, watermark image support).
4
+ */
5
+
6
+ import fs from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import sharp from 'sharp';
9
+
10
+ export function parseHex(hex, fallback = { r: 255, g: 255, b: 255, alpha: 1 }) {
11
+ if (!hex || typeof hex !== 'string') return fallback;
12
+ let h = hex.trim().replace('#', '');
13
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
14
+ if (h.length === 8) {
15
+ return {
16
+ r: parseInt(h.slice(0, 2), 16),
17
+ g: parseInt(h.slice(2, 4), 16),
18
+ b: parseInt(h.slice(4, 6), 16),
19
+ alpha: parseInt(h.slice(6, 8), 16) / 255,
20
+ };
21
+ }
22
+ if (!/^[0-9a-fA-F]{6}$/.test(h)) return fallback;
23
+ return {
24
+ r: parseInt(h.slice(0, 2), 16),
25
+ g: parseInt(h.slice(2, 4), 16),
26
+ b: parseInt(h.slice(4, 6), 16),
27
+ alpha: 1,
28
+ };
29
+ }
30
+
31
+ export function normalizeFormat(fmt) {
32
+ const f = String(fmt || 'jpeg').toLowerCase();
33
+ if (f === 'jpg') return 'jpeg';
34
+ if (['jpeg', 'png', 'webp', 'tiff', 'avif'].includes(f)) return f;
35
+ return 'jpeg';
36
+ }
37
+
38
+ export function extFor(fmt) {
39
+ const f = normalizeFormat(fmt);
40
+ return f === 'jpeg' ? '.jpg' : `.${f}`;
41
+ }
42
+
43
+ export async function encodeToFile(pipeline, outPath, format, quality) {
44
+ const f = normalizeFormat(format);
45
+ const q = Math.min(100, Math.max(40, Number(quality) || 90));
46
+ if (f === 'png') await pipeline.png().toFile(outPath);
47
+ else if (f === 'webp') await pipeline.webp({ quality: q }).toFile(outPath);
48
+ else if (f === 'tiff') await pipeline.tiff().toFile(outPath);
49
+ else if (f === 'avif') await pipeline.avif({ quality: q }).toFile(outPath);
50
+ else await pipeline.jpeg({ quality: q, mozjpeg: true }).toFile(outPath);
51
+ }
52
+
53
+ export async function encodeToBuffer(pipeline, format, quality) {
54
+ const f = normalizeFormat(format);
55
+ const q = Math.min(100, Math.max(40, Number(quality) || 90));
56
+ if (f === 'png') return pipeline.png().toBuffer();
57
+ if (f === 'webp') return pipeline.webp({ quality: q }).toBuffer();
58
+ if (f === 'tiff') return pipeline.tiff().toBuffer();
59
+ if (f === 'avif') return pipeline.avif({ quality: q }).toBuffer();
60
+ return pipeline.jpeg({ quality: q, mozjpeg: true }).toBuffer();
61
+ }
62
+
63
+ /**
64
+ * Alpha bounding box (website canvas_align_centre logic).
65
+ * @param {Buffer} pngBuf transparent PNG
66
+ * @returns {Promise<{minX:number,minY:number,maxX:number,maxY:number,width:number,height:number}|null>}
67
+ */
68
+ export async function alphaBBox(pngBuf, alphaThreshold = 10) {
69
+ const { data, info } = await sharp(pngBuf)
70
+ .ensureAlpha()
71
+ .raw()
72
+ .toBuffer({ resolveWithObject: true });
73
+ const W = info.width;
74
+ const H = info.height;
75
+ let minX = W; let maxX = -1; let minY = H; let maxY = -1;
76
+ for (let y = 0; y < H; y++) {
77
+ for (let x = 0; x < W; x++) {
78
+ const a = data[(y * W + x) * 4 + 3];
79
+ if (a > alphaThreshold) {
80
+ if (x < minX) minX = x;
81
+ if (x > maxX) maxX = x;
82
+ if (y < minY) minY = y;
83
+ if (y > maxY) maxY = y;
84
+ }
85
+ }
86
+ }
87
+ if (maxX < minX || maxY < minY) return null;
88
+ return {
89
+ minX, minY, maxX, maxY,
90
+ width: maxX - minX + 1,
91
+ height: maxY - minY + 1,
92
+ srcW: W,
93
+ srcH: H,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Crop cutout to content bbox, scale into square canvas with padding + alignment.
99
+ * Parity with canvas_align_centre.
100
+ */
101
+ export async function alignCutoutOnCanvas(cutoutPng, {
102
+ targetSize = 1000,
103
+ padding = 0.05,
104
+ padColor = '#FFFFFF',
105
+ alignment = 'center',
106
+ format = 'png',
107
+ quality = 90,
108
+ } = {}) {
109
+ const size = Math.min(4000, Math.max(256, Number(targetSize) || 1000));
110
+ const bg = parseHex(padColor);
111
+ const bbox = await alphaBBox(cutoutPng);
112
+ if (!bbox) {
113
+ const empty = sharp({
114
+ create: {
115
+ width: size, height: size, channels: 3,
116
+ background: { r: bg.r, g: bg.g, b: bg.b },
117
+ },
118
+ });
119
+ return encodeToBuffer(empty, format, quality);
120
+ }
121
+
122
+ const cropped = await sharp(cutoutPng)
123
+ .extract({
124
+ left: bbox.minX,
125
+ top: bbox.minY,
126
+ width: bbox.width,
127
+ height: bbox.height,
128
+ })
129
+ .png()
130
+ .toBuffer();
131
+
132
+ const padPx = Math.round(Math.max(1, size * Math.min(0.4, Math.max(0, Number(padding) || 0.05))));
133
+ const available = size - padPx * 2;
134
+ const scale = Math.min(available / bbox.width, available / bbox.height);
135
+ const drawW = Math.max(1, Math.round(bbox.width * scale));
136
+ const drawH = Math.max(1, Math.round(bbox.height * scale));
137
+ const resized = await sharp(cropped)
138
+ .resize({ width: drawW, height: drawH, fit: 'fill' })
139
+ .png()
140
+ .toBuffer();
141
+
142
+ const a = String(alignment || 'center');
143
+ const leftish = a.includes('left');
144
+ const rightish = a.includes('right');
145
+ const topish = a.startsWith('top');
146
+ const bottomish = a.startsWith('bottom');
147
+ const drawX = leftish ? padPx : rightish ? (size - drawW - padPx) : Math.round((size - drawW) / 2);
148
+ const drawY = topish ? padPx : bottomish ? (size - drawH - padPx) : Math.round((size - drawH) / 2);
149
+
150
+ const composed = sharp({
151
+ create: {
152
+ width: size, height: size, channels: 3,
153
+ background: { r: bg.r, g: bg.g, b: bg.b },
154
+ },
155
+ }).composite([{ input: resized, left: Math.max(0, drawX), top: Math.max(0, drawY) }]);
156
+
157
+ return encodeToBuffer(composed, format === 'jpeg' ? 'jpeg' : format, quality);
158
+ }
159
+
160
+ /**
161
+ * BCS adjust matching website canvas_adjust_bcs scales:
162
+ * brightness -50..50, contrast -50..50, saturation -100..100
163
+ */
164
+ export async function adjustBcs(inputBufOrPath, {
165
+ brightness = 0,
166
+ contrast = 0,
167
+ saturation = 0,
168
+ } = {}) {
169
+ const { data, info } = await sharp(inputBufOrPath)
170
+ .ensureAlpha()
171
+ .raw()
172
+ .toBuffer({ resolveWithObject: true });
173
+
174
+ const bv = Number(brightness) * 2.54;
175
+ const cf = Number(contrast) > 0
176
+ ? 1 + (Number(contrast) / 50) * 2
177
+ : 1 + Number(contrast) / 50;
178
+ const sv = 1 + Number(saturation) / 100;
179
+
180
+ if (bv === 0 && cf === 1 && sv === 1) {
181
+ return sharp(inputBufOrPath).png().toBuffer();
182
+ }
183
+
184
+ const d = data;
185
+ for (let i = 0; i < d.length; i += 4) {
186
+ let r = d[i]; let g = d[i + 1]; let b = d[i + 2];
187
+ r += bv; g += bv; b += bv;
188
+ r = (r - 128) * cf + 128;
189
+ g = (g - 128) * cf + 128;
190
+ b = (b - 128) * cf + 128;
191
+ const grey = 0.299 * r + 0.587 * g + 0.114 * b;
192
+ r = grey + sv * (r - grey);
193
+ g = grey + sv * (g - grey);
194
+ b = grey + sv * (b - grey);
195
+ d[i] = Math.max(0, Math.min(255, r + 0.5) | 0);
196
+ d[i + 1] = Math.max(0, Math.min(255, g + 0.5) | 0);
197
+ d[i + 2] = Math.max(0, Math.min(255, b + 0.5) | 0);
198
+ }
199
+
200
+ return sharp(d, {
201
+ raw: { width: info.width, height: info.height, channels: 4 },
202
+ }).png().toBuffer();
203
+ }
204
+
205
+ /** 9-point grid position */
206
+ export function gridPosition(position, W, H, bw, bh, padding = 16) {
207
+ const pad = Math.max(0, Number(padding) || 0);
208
+ const cx = Math.round((W - bw) / 2);
209
+ const cy = Math.round((H - bh) / 2);
210
+ const POS = {
211
+ 'top-left': [pad, pad],
212
+ 'top-center': [cx, pad],
213
+ 'top': [cx, pad],
214
+ 'top-right': [W - bw - pad, pad],
215
+ 'middle-left': [pad, cy],
216
+ 'center': [cx, cy],
217
+ 'middle-center': [cx, cy],
218
+ 'middle-right': [W - bw - pad, cy],
219
+ 'bottom-left': [pad, H - bh - pad],
220
+ 'bottom-center': [cx, H - bh - pad],
221
+ 'bottom': [cx, H - bh - pad],
222
+ 'bottom-right': [W - bw - pad, H - bh - pad],
223
+ };
224
+ const [x, y] = POS[String(position || 'bottom-right')] || POS['bottom-right'];
225
+ return { left: Math.max(0, x), top: Math.max(0, y) };
226
+ }
227
+
228
+ export function escapeXml(s) {
229
+ return String(s)
230
+ .replace(/&/g, '&amp;')
231
+ .replace(/</g, '&lt;')
232
+ .replace(/>/g, '&gt;')
233
+ .replace(/"/g, '&quot;');
234
+ }
235
+
236
+ /** Content bottom scan for reflections (website canvas_add_reflection) */
237
+ export async function findContentBottom(pngOrPath) {
238
+ const meta = await sharp(pngOrPath).metadata();
239
+ const srcW = meta.width || 1;
240
+ const srcH = meta.height || 1;
241
+ const scanH = Math.min(srcH, 600);
242
+ const scanW = Math.max(1, Math.round(srcW * scanH / srcH));
243
+ const { data, info } = await sharp(pngOrPath)
244
+ .resize({ width: scanW, height: scanH, fit: 'fill' })
245
+ .ensureAlpha()
246
+ .raw()
247
+ .toBuffer({ resolveWithObject: true });
248
+
249
+ let scanBottom = info.height - 1;
250
+ outer:
251
+ for (let y = info.height - 1; y >= 0; y--) {
252
+ let n = 0;
253
+ for (let x = 0; x < info.width; x += 2) {
254
+ const i = (y * info.width + x) * 4;
255
+ const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; const a = data[i + 3];
256
+ if (a > 25 && (r < 245 || g < 245 || b < 245)) {
257
+ if (++n >= 3) { scanBottom = y; break outer; }
258
+ }
259
+ }
260
+ }
261
+ return Math.min(
262
+ srcH - 1,
263
+ scanH > 1 ? Math.round(scanBottom * (srcH - 1) / (scanH - 1)) : scanBottom,
264
+ );
265
+ }
266
+
267
+ export async function readOptionalFile(p) {
268
+ if (!p) return null;
269
+ const abs = path.resolve(String(p));
270
+ await fs.access(abs);
271
+ return abs;
272
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Lazy Node rembg (@imgly/background-removal-node) — same family as website WASM cutout.
3
+ * First call downloads ONNX models (cached after).
4
+ */
5
+
6
+ import fs from 'node:fs/promises';
7
+
8
+ let removeBackgroundFn = null;
9
+ let loadError = null;
10
+
11
+ async function loadRembg() {
12
+ if (removeBackgroundFn) return removeBackgroundFn;
13
+ if (loadError) throw loadError;
14
+ try {
15
+ const mod = await import('@imgly/background-removal-node');
16
+ removeBackgroundFn = mod.removeBackground;
17
+ return removeBackgroundFn;
18
+ } catch (e) {
19
+ loadError = new Error(
20
+ `Background removal unavailable: ${e?.message ?? e}. Install @imgly/background-removal-node (bundled with this package).`,
21
+ );
22
+ throw loadError;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @param {string} filePath
28
+ * @returns {Promise<Buffer>} PNG with alpha
29
+ */
30
+ export async function cutoutPngBuffer(filePath) {
31
+ const removeBackground = await loadRembg();
32
+ const input = await fs.readFile(filePath);
33
+ const blob = await removeBackground(input, {
34
+ output: { format: 'image/png', quality: 0.9 },
35
+ });
36
+ const ab = await blob.arrayBuffer();
37
+ return Buffer.from(ab);
38
+ }