UNPKG

@netlify/content-engine

Version:
56 lines 2.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformImage = transformImage; const path_1 = __importDefault(require("path")); const fs_extra_1 = require("fs-extra"); const create_content_digest_1 = require("../../core-utils/create-content-digest"); const cache_1 = require("./utils/cache"); // Lots of work to get the sharp instance // type Pipeline = ReturnType<Awaited<ReturnType<typeof getSharpInstance>>>; // queue is used inside transformImage to batch multiple transforms together // more info inside the transformImage function const queue = new Map(); async function transformImage({ outputDir, args: { url, filename, contentDigest, httpHeaders, ...args }, }) { const cache = (0, cache_1.getCache)(); const digest = (0, create_content_digest_1.createContentDigest)({ url, filename, contentDigest, args }); const cacheKey = `image-cdn:` + digest + `:transform`; const cachedValue = (await cache.get(cacheKey)); if (cachedValue && (await (0, fs_extra_1.pathExists)(cachedValue))) { return cachedValue; } const outputPath = path_1.default.join(outputDir, filename); await (0, fs_extra_1.mkdirp)(path_1.default.dirname(outputPath)); // if the queue already contains the url, we're going to add it to queue so, we can batch the transforms together. // We use setImmediate to not block the event loop so the queue can fill up. if (queue.has(url)) { const queued = queue.get(url); queued.transforms.push({ ...args, outputPath }); return queued.promise.then(() => { cache.set(cacheKey, outputPath); return outputPath; }); } else { const defer = new Promise((resolve, reject) => { setImmediate(async () => { queue.delete(url); try { await cache.set(cacheKey, outputPath); resolve(outputPath); } catch (err) { reject(err); } }); }); queue.set(url, { promise: defer, transforms: [{ ...args, outputPath }], }); return defer; } } //# sourceMappingURL=transform-images.js.map