@prodbirdy/mockup-generator
Version:
Serverless-optimized TypeScript SDK for generating high-quality product mockups from PSD templates
71 lines (62 loc) • 1.53 kB
text/typescript
import { printInfo, printWarning } from "./formatting";
import fs from "node:fs/promises"
/**
* Checks if a string is a valid URL
*/
function isUrl(path: string): boolean {
try {
new URL(path);
return path.startsWith("http://") || path.startsWith("https://");
} catch {
return false;
}
}
/**
* Downloads a file from a URL and returns it as an ArrayBuffer
*/
async function downloadFile(
url: string,
verbose: boolean = false
): Promise<ArrayBuffer> {
if (verbose) {
printInfo(`Downloading file from: ${url}`);
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to download file: ${response.status} ${response.statusText}`
);
}
const arrayBuffer = await response.arrayBuffer();
if (verbose) {
printInfo(
`Downloaded ${(arrayBuffer.byteLength / 1024 / 1024).toFixed(2)} MB`
);
}
return arrayBuffer;
}
/**
* Gets file data as ArrayBuffer from either a local path or URL
*/
export async function getFileData(
path: string,
verbose: boolean = false
): Promise<ArrayBuffer> {
if (isUrl(path)) {
return downloadFile(path, verbose);
} else {
// Local file
const file = await fs.readFile(path);
return file.buffer as ArrayBuffer;
}
}
/**
* Gets file data as Buffer from either a local path or URL
*/
export async function getFileBuffer(
path: string,
verbose: boolean = false
): Promise<Buffer> {
const arrayBuffer = await getFileData(path, verbose);
return Buffer.from(arrayBuffer);
}