openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
266 lines (265 loc) • 9.68 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { n as estimateBase64DecodedBytes, t as canonicalizeBase64 } from "./base64-CnKpkbff.mjs";
import { d as normalizeMimeType, n as detectMime } from "./mime-D2wVBzpa.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import "./http-body-B9w7rzPz.mjs";
import { i as readResponseWithLimit, t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import "./media-services-DAzmF7yi.mjs";
import { r as convertHeicToJpeg } from "./image-ops-zeupBxnN.mjs";
import { n as classifyAttachmentBytes } from "./attachment-classify-DFSZjMac.mjs";
import { t as parseMediaContentLength } from "./content-length-CEI2r5C4.mjs";
import { t as extractPdfContent } from "./pdf-extract-HrzfkxiI.mjs";
import { MIMEType } from "node:util";
//#region src/media/input-files.ts
const DEFAULT_INPUT_IMAGE_MIMES = [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/heic",
"image/heif"
];
const DEFAULT_INPUT_FILE_MIMES = [
"text/plain",
"text/markdown",
"text/html",
"text/csv",
"application/json",
"application/pdf"
];
const DEFAULT_INPUT_IMAGE_MAX_BYTES = 10485760;
const DEFAULT_INPUT_FILE_MAX_BYTES = 5242880;
const DEFAULT_INPUT_FILE_MAX_CHARS = 6e4;
const DEFAULT_INPUT_MAX_REDIRECTS = 3;
const DEFAULT_INPUT_TIMEOUT_MS = 1e4;
const DEFAULT_INPUT_PDF_MAX_PAGES = 4;
const DEFAULT_INPUT_PDF_MAX_PIXELS = 4e6;
/** Default text threshold before PDF extraction keeps text-only output. */
const DEFAULT_INPUT_PDF_MIN_TEXT_CHARS = 200;
const NORMALIZED_INPUT_IMAGE_MIME = "image/jpeg";
const HEIC_INPUT_IMAGE_MIMES = /* @__PURE__ */ new Set(["image/heic", "image/heif"]);
function parseContentType(e) {
if (!e) return {};
const t = normalizeMimeType(e);
try {
return {
mimeType: t,
charset: new MIMEType(e).params.get("charset") ?? void 0
};
} catch {
return { mimeType: t };
}
}
/** Converts configured MIME lists into a normalized allowlist, using fallback defaults when empty. */
function normalizeMimeList(e, t) {
const n = e && e.length > 0 ? e : t;
return new Set(n.flatMap((e) => normalizeMimeType(e) ?? []));
}
function resolveInputFileLimits(e) {
return {
allowUrl: e?.allowUrl ?? true,
allowedMimes: normalizeMimeList(e?.allowedMimes, DEFAULT_INPUT_FILE_MIMES),
maxBytes: e?.maxBytes ?? DEFAULT_INPUT_FILE_MAX_BYTES,
maxChars: e?.maxChars ?? DEFAULT_INPUT_FILE_MAX_CHARS,
maxRedirects: e?.maxRedirects ?? 3,
timeoutMs: e?.timeoutMs ?? 1e4,
pdf: {
maxPages: e?.pdf?.maxPages ?? DEFAULT_INPUT_PDF_MAX_PAGES,
maxPixels: e?.pdf?.maxPixels ?? DEFAULT_INPUT_PDF_MAX_PIXELS,
minTextChars: e?.pdf?.minTextChars ?? DEFAULT_INPUT_PDF_MIN_TEXT_CHARS
}
};
}
async function readInputSource(e, t, n, r) {
if (e.type === "base64") {
const r = estimateBase64DecodedBytes(e.data);
if (r > t.maxBytes) throw new Error(`${n === "input_image" ? "Image" : "File"} too large: ${r} bytes (limit: ${t.maxBytes} bytes)`);
const i = canonicalizeBase64(e.data);
if (!i) throw new Error(`${n} base64 source has invalid 'data' field`);
return {
buffer: Buffer.from(i, "base64"),
contentType: e.mediaType,
canonicalData: i
};
}
if (n === "input_image" && e.type !== "url") throw new Error(`Unsupported input_image source type: ${e.type}`);
if (!t.allowUrl) throw new Error(`${n} URL sources are disabled by config`);
const { response: i, release: a } = await fetchWithSsrFGuard({
url: e.url,
maxRedirects: t.maxRedirects,
timeoutMs: t.timeoutMs,
signal: r,
policy: {
allowPrivateNetwork: false,
hostnameAllowlist: t.urlAllowlist
},
auditContext: `openresponses.${n}`,
init: { headers: { "User-Agent": "OpenClaw-Gateway/1.0" } }
});
let o;
try {
if (!i.ok) {
await cancelUnreadResponseBody(i);
throw new Error(`Failed to fetch: ${i.status} ${i.statusText}`);
}
let e;
try {
e = parseMediaContentLength(i.headers.get("content-length"));
} catch (e) {
await cancelUnreadResponseBody(i);
throw e;
}
if (e !== null && e > t.maxBytes) {
await cancelUnreadResponseBody(i);
throw new Error(`Content too large: ${e} bytes (limit: ${t.maxBytes} bytes)`);
}
o = {
buffer: await readResponseWithLimit(i, t.maxBytes),
contentType: i.headers.get("content-type") ?? void 0
};
} finally {
await a();
}
r?.throwIfAborted();
return o;
}
function decodeTextContent(e, t, n) {
const r = normalizeOptionalLowercaseString(t) || "utf-8";
const i = Math.max(0, Math.floor(n));
const decode = (t) => {
const n = new TextDecoder(t);
let r = "";
for (let t = 0; t < e.length && r.length <= i; t += 16384) {
const i = Math.min(t + 16384, e.length);
r += n.decode(e.subarray(t, i), { stream: i < e.length });
}
const a = truncateUtf16Safe(r, i);
return {
text: a,
...a.length < r.length ? { metadata: {
textTruncated: true,
imagesTruncated: false
} } : {}
};
};
try {
return decode(r);
} catch {
return decode("utf-8");
}
}
/** Validates image bytes and converts HEIC/HEIF to JPEG, keeping the original Buffer otherwise. */
async function normalizeInputImageBuffer(e) {
if (e.buffer.byteLength > e.limits.maxBytes) throw new Error(`Image too large: ${e.buffer.byteLength} bytes (limit: ${e.limits.maxBytes} bytes)`);
const t = normalizeMimeType(e.mimeType) ?? "application/octet-stream";
const n = normalizeMimeType(await detectMime({
buffer: e.buffer,
headerMime: e.mimeType
}));
if (t.startsWith("image/") && n && !n.startsWith("image/")) throw new Error(`Unsupported image MIME type: ${n}`);
const r = (n?.startsWith("image/") ? n : t).replace(/^(image\/hei[cf])-sequence$/, "$1");
if (!e.limits.allowedMimes.has(r)) throw new Error(`Unsupported image MIME type: ${r}`);
if (!HEIC_INPUT_IMAGE_MIMES.has(r)) return {
buffer: e.buffer,
mimeType: r
};
const i = await convertHeicToJpeg(e.buffer);
if (i.byteLength > e.limits.maxBytes) throw new Error(`Image too large after HEIC conversion: ${i.byteLength} bytes (limit: ${e.limits.maxBytes} bytes)`);
return {
buffer: i,
mimeType: NORMALIZED_INPUT_IMAGE_MIME
};
}
async function extractImageContentFromSource(e, t, n) {
n?.throwIfAborted();
const { buffer: r, contentType: i, canonicalData: a } = await readInputSource(e, t, "input_image", n);
const o = await normalizeInputImageBuffer({
buffer: r,
mimeType: e.type === "base64" ? normalizeMimeType(i) ?? "image/png" : parseContentType(i).mimeType,
limits: t
});
n?.throwIfAborted();
return {
type: "image",
data: o.buffer === r && a ? a : o.buffer.toString("base64"),
mimeType: o.mimeType
};
}
async function extractFileContentFromSource(e) {
const { source: t, limits: n, signal: r } = e;
r?.throwIfAborted();
const i = t.filename || "file";
const { buffer: a, contentType: o } = await readInputSource(t, n, "input_file", r);
const s = await extractFileContentFromBuffer({
buffer: a,
filename: i,
mimeType: o,
limits: n,
...r ? { signal: r } : {}
});
r?.throwIfAborted();
return s;
}
/** Extracts text from borrowed bytes or PDFs from owned bytes after shared size and MIME checks. */
async function extractFileContentFromBuffer(e) {
const { buffer: t, limits: n } = e;
e.signal?.throwIfAborted();
const r = e.filename || "file";
if (t.byteLength > n.maxBytes) throw new Error(`File too large: ${t.byteLength} bytes (limit: ${n.maxBytes} bytes)`);
const i = e.classification ?? await classifyAttachmentBytes({
buffer: t,
declaredMime: e.mimeType
});
e.signal?.throwIfAborted();
const a = i.mime;
const o = i.charset ?? e.charset ?? parseContentType(e.mimeType).charset;
if (!a) throw new Error("input_file missing media type");
if (!n.allowedMimes.has(a)) throw new Error(`Unsupported file MIME type: ${a}`);
if (a === "application/pdf") {
const i = resolveTimerTimeoutMs(n.timeoutMs, 1);
const a = new AbortController();
const o = e.signal ? AbortSignal.any([e.signal, a.signal]) : a.signal;
o.throwIfAborted();
const s = setTimeout(() => a.abort(/* @__PURE__ */ new Error(`PDF extraction timed out after ${i}ms`)), i);
let c;
try {
c = await racePromiseWithAbortSignal(() => extractPdfContent({
buffer: t,
signal: o,
maxPages: n.pdf.maxPages,
maxPixels: n.pdf.maxPixels,
minTextChars: n.pdf.minTextChars,
...e.config ? { config: e.config } : {},
onImageExtractionError: (e) => {
logWarn(`media: PDF image extraction skipped, ${String(e)}`);
}
}), o, (e) => toErrorObject(e.reason, "Input file extraction aborted"));
} finally {
clearTimeout(s);
}
const l = truncateUtf16Safe(c.text, n.maxChars);
const u = {
...c.metadata,
textTruncated: c.metadata?.textTruncated === true || l.length < c.text.length,
imagesTruncated: c.metadata?.imagesTruncated === true
};
return {
filename: r,
text: l,
images: c.images.length > 0 ? c.images : void 0,
metadata: u
};
}
return {
filename: r,
...decodeTextContent(t, o, n.maxChars)
};
}
//#endregion
export { extractFileContentFromSource as a, normalizeMimeList as c, extractFileContentFromBuffer as i, resolveInputFileLimits as l, DEFAULT_INPUT_IMAGE_MIMES as n, extractImageContentFromSource as o, DEFAULT_INPUT_TIMEOUT_MS as r, normalizeInputImageBuffer as s, DEFAULT_INPUT_IMAGE_MAX_BYTES as t };