@stacksjs/image 0.75.735 → 0.75.755
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/README.md +23 -0
- package/dist/index.js +1 -1
- package/dist/social.js +1 -1
- package/dist/upload.d.ts +24 -3
- package/dist/upload.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -86,3 +86,26 @@ contains no source EXIF, XMP or comments. Defaults are 12 MiB and 40 million pix
|
|
|
86
86
|
the encoded result must fit the byte budget too. Store the returned bytes and use
|
|
87
87
|
its dimensions, since orientation can swap width and height. Authorization and
|
|
88
88
|
retention remain the application's responsibility.
|
|
89
|
+
|
|
90
|
+
To compress as well, pass any of:
|
|
91
|
+
|
|
92
|
+
- `maxDimension`: scale down so the longest side is at most that many pixels. It
|
|
93
|
+
never scales up.
|
|
94
|
+
- `format` (`'jpeg'`, `'png'` or `'webp'`) and `quality` (1 to 100): the encoding
|
|
95
|
+
to return. The default is unchanged: the source's format at 90.
|
|
96
|
+
- `keepIfSmaller`: when the requested encoding is not smaller than the source's
|
|
97
|
+
format at 90 at the same size, return that instead. Metadata is stripped either
|
|
98
|
+
way; the upload itself is never returned.
|
|
99
|
+
- `thumbnail: { maxDimension, format?, quality? }`: also return
|
|
100
|
+
`thumbnail: { bytes, width, height, format }`, cut from the same decoded pixels.
|
|
101
|
+
Format and quality default to the main result's.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const photo = await sanitizeImageUpload(bytes, {
|
|
105
|
+
maxDimension: 1600,
|
|
106
|
+
format: 'webp',
|
|
107
|
+
quality: 75,
|
|
108
|
+
keepIfSmaller: true,
|
|
109
|
+
thumbnail: { maxDimension: 400, quality: 70 },
|
|
110
|
+
})
|
|
111
|
+
```
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHash,createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{mkdir,readFile,rename,stat,writeFile}from"node:fs/promises";import{readFileSync}from"node:fs";import{basename,dirname,extname,isAbsolute,relative,resolve}from"node:path";import{decode,encode,imageToSplatHash,resize}from"ts-images";export*from"./app-icons";export*from"./app-store";export*from"./fonts";export*from"./generate";export*from"./social";export*from"./splash";export*from"./theme";export*from"./upload";const mime={avif:"image/avif",webp:"image/webp",jpeg:"image/jpeg",png:"image/png"};function integer(name,value,min,max){if(!Number.isInteger(value)||value<min||value>max)throw new TypeError(`${name} must be between ${min} and ${max}`)}let codecs;function codecFingerprint(){if(codecs!==undefined)return codecs;const version=(name,from)=>{try{return JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,from),"utf8")).version??"?"}catch{return"?"}};let imagesDir=import.meta.dir;try{imagesDir=dirname(Bun.resolveSync("ts-images/package.json",import.meta.dir))}catch{}codecs=[`ts-images@${version("ts-images",import.meta.dir)}`,`ts-webp@${version("@stacksjs/ts-webp",imagesDir)}`,`ts-avif@${version("@stacksjs/ts-avif",imagesDir)}`].join(",");return codecs}export function resolveImageSource(source,root=process.cwd()){const allowed=resolve(root);const candidate=isAbsolute(source)?resolve(source):resolve(allowed,source);const relation=relative(allowed,candidate);if(source.includes("\x00")||relation===".."||relation.startsWith("../")||isAbsolute(relation))throw new Error("Image source must stay inside the configured root");return candidate}export class ImageBuilder{source;targetWidths=[480,768,1280,1920];targetFormats=["avif","webp","jpeg"];targetFit="inside";targetHeight;targetAspectRatio;targetPosition="center";includeOriginal=true;targetStorage;targetQuality=82;options;constructor(source,options={}){this.source=source;const root=options.root??process.cwd();this.options={...options,root,outputDir:options.outputDir??resolve(root,"public/media/images"),publicPath:options.publicPath??"/media/images",concurrency:options.concurrency??4,upscale:options.upscale??false}}widths(widths){if(!widths.length)throw new TypeError("Image widths are required");widths.forEach((value)=>integer("Image width",value,1,16384));this.targetWidths=[...new Set(widths)].sort((a,b)=>a-b);return this}formats(formats){if(!formats.length)throw new TypeError("Image formats are required");this.targetFormats=[...new Set(formats)];return this}fit(fit){this.targetFit=fit;return this}height(value){integer("Image height",value,1,16384);this.targetHeight=value;this.targetAspectRatio=undefined;return this}aspectRatio(value){if(!Number.isFinite(value)||value<=0||value>100)throw new TypeError("Image aspect ratio must be between 0 and 100");this.targetAspectRatio=value;this.targetHeight=undefined;return this}position(value){this.targetPosition=value;return this}preset(value){const presets={avatar:{widths:[64,128,256,512],ratio:1,fit:"cover",original:false},content:{widths:[320,640,960,1280,1920],fit:"inside",original:true},hero:{widths:[640,1280,1920,2560],ratio:16/9,fit:"cover",original:true},thumbnail:{widths:[160,320,640],ratio:16/9,fit:"cover",original:false}};const preset=presets[value];this.targetWidths=[...preset.widths];this.targetFit=preset.fit;this.targetAspectRatio="ratio"in preset?preset.ratio:undefined;this.targetHeight=undefined;this.includeOriginal=preset.original;return this}quality(value){integer("Image quality",value,1,100);this.targetQuality=value;return this}original(include){this.includeOriginal=include;return this}output(dir,publicPath="/media/images"){this.options.outputDir=resolve(dir);this.options.publicPath=`/${publicPath.replace(/^\/+|\/+$/g,"")}`;return this}storage(adapter,prefix="media/images"){this.targetStorage={adapter,prefix:prefix.replace(/^\/+|\/+$/g,"")};return this}async generate(){integer("Image concurrency",this.options.concurrency,1,32);const sourcePath=resolveImageSource(this.source,this.options.root);if(this.options.authorize&&!await this.options.authorize(sourcePath,this.options.authorizationContext))throw new Error("Image delivery is not authorized");const bytes=new Uint8Array(await readFile(sourcePath));const hash=createHash("sha256").update(bytes).digest("hex");const decoded=await decode(bytes);const widths=this.targetWidths.filter((width)=>this.options.upscale||width<=decoded.width);if(this.includeOriginal&&!widths.includes(decoded.width))widths.push(decoded.width);const tasks=[...new Set(widths)].sort((a,b)=>a-b).flatMap((width)=>this.targetFormats.map((format)=>({width,format})));const variants=[];let cursor=0;await Promise.all(Array.from({length:Math.min(tasks.length,this.options.concurrency)},async()=>{while(cursor<tasks.length){const task=tasks[cursor++];variants.push(await this.variant(decoded,hash,sourcePath,task.width,task.format))}}));variants.sort((a,b)=>a.width-b.width||this.targetFormats.indexOf(a.format)-this.targetFormats.indexOf(b.format));return{source:{width:decoded.width,height:decoded.height,hash},variants,placeholder:Buffer.from(imageToSplatHash(decoded)).toString("base64url")}}async variant(source,hash,sourcePath,width,format){const height=this.targetHeight??(this.targetAspectRatio?Math.max(1,Math.round(width/this.targetAspectRatio)):undefined);const output=width===source.width&&height===undefined?source:resize(source,{width,height,fit:this.targetFit,position:this.targetPosition});if(!this.options.upscale&&(output.width>source.width||output.height>source.height))throw new TypeError(`Image variant ${output.width}x${output.height} would upscale the source`);const cacheKey=createHash("sha256").update(`${hash}:${width}:${height??"auto"}:${format}:${this.targetFit}:${this.targetPosition}:${this.targetQuality}:${codecFingerprint()}`).digest("hex");const stem=basename(sourcePath,extname(sourcePath)).replace(/[^a-zA-Z0-9_-]/g,"-")||"image";const filename=`${stem}-${output.width}x${output.height}-${cacheKey.slice(0,16)}.${format==="jpeg"?"jpg":format}`;const path=resolve(this.options.outputDir,filename);if(this.targetStorage){const key=this.targetStorage.prefix?`${this.targetStorage.prefix}/${filename}`:filename;if(await this.targetStorage.adapter.fileExists(key)){const existing=await this.targetStorage.adapter.stat(key);return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});const written=await this.targetStorage.adapter.write(key,encoded);return{width:output.width,height:output.height,bytes:written.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const existing=await stat(path).catch(()=>null);if(existing)return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey};const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});await mkdir(this.options.outputDir,{recursive:true});const temporary=`${path}.${process.pid}.${randomUUID()}.tmp`;await writeFile(temporary,encoded);await rename(temporary,path);return{width:output.width,height:output.height,bytes:encoded.byteLength,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey}}}export function image(source,options={}){return new ImageBuilder(source,options)}function accepted(accept,mimeType){const[type,subtype]=mimeType.split("/");let best=0;for(const item of accept.split(",")){const[range="*/*",...params]=item.trim().toLowerCase().split(";").map((value)=>value.trim());const[acceptedType,acceptedSubtype]=range.split("/");if(acceptedType!=="*"&&acceptedType!==type||acceptedSubtype!=="*"&&acceptedSubtype!==subtype)continue;const raw=params.find((param)=>param.startsWith("q="));best=Math.max(best,raw?Number.parseFloat(raw.slice(2))||0:1)}return best}export function negotiateImageVariant(variants,accept="*/*",width){const widths=[...new Set(variants.map((item)=>item.width))].sort((a,b)=>a-b);const target=width===undefined?widths.at(-1):widths.find((value)=>value>=width)??widths.at(-1);return variants.filter((item)=>item.width===target).map((variant,index)=>({variant,index,q:accepted(accept||"*/*",variant.mimeType)})).filter((item)=>item.q>0).sort((a,b)=>b.q-a.q||a.index-b.index)[0]?.variant}export function imageResponseHeaders(variant){return{"Content-Type":variant.mimeType,"Content-Length":String(variant.bytes),"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${variant.cacheKey}"`,Vary:"Accept","X-Image-Width":String(variant.width),"X-Image-Height":String(variant.height)}}export function signImageTransform(path,expires,secret){return createHmac("sha256",secret).update(`${path}
|
|
1
|
+
import{createHash,createHmac,randomUUID,timingSafeEqual}from"node:crypto";import{mkdir,readFile,realpath,rename,stat,writeFile}from"node:fs/promises";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,extname,isAbsolute,relative,resolve}from"node:path";import{decode,encode,imageToSplatHash,resize}from"ts-images";export*from"./app-icons";export*from"./app-store";export*from"./fonts";export*from"./generate";export*from"./social";export*from"./splash";export*from"./theme";export*from"./upload";const mime={avif:"image/avif",webp:"image/webp",jpeg:"image/jpeg",png:"image/png"};function integer(name,value,min,max){if(!Number.isInteger(value)||value<min||value>max)throw new TypeError(`${name} must be between ${min} and ${max}`)}let codecs;function codecFingerprint(){if(codecs!==undefined)return codecs;const version=(name,from)=>{try{return JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,from),"utf8")).version??"?"}catch{return"?"}};let imagesDir=import.meta.dir;try{imagesDir=dirname(Bun.resolveSync("ts-images/package.json",import.meta.dir))}catch{}codecs=[`ts-images@${version("ts-images",import.meta.dir)}`,`ts-webp@${version("@stacksjs/ts-webp",imagesDir)}`,`ts-avif@${version("@stacksjs/ts-avif",imagesDir)}`].join(",");return codecs}export function resolveImageSource(source,root=process.cwd()){const allowed=resolve(root);const candidate=isAbsolute(source)?resolve(source):resolve(allowed,source);const relation=relative(allowed,candidate);if(source.includes("\x00")||relation===".."||relation.startsWith("../")||isAbsolute(relation))throw new Error("Image source must stay inside the configured root");if(existsSync(candidate)&&existsSync(allowed)){const realRoot=realpathSync(allowed);const realCandidate=realpathSync(candidate);const realRelation=relative(realRoot,realCandidate);if(realRelation===".."||realRelation.startsWith("../")||isAbsolute(realRelation))throw new Error("Image source must stay inside the configured root");return realCandidate}return candidate}export class ImageBuilder{source;targetWidths=[480,768,1280,1920];targetFormats=["avif","webp","jpeg"];targetFit="inside";targetHeight;targetAspectRatio;targetPosition="center";includeOriginal=true;targetStorage;targetQuality=82;options;constructor(source,options={}){this.source=source;const root=options.root??process.cwd();this.options={...options,root,outputDir:options.outputDir??resolve(root,"public/media/images"),publicPath:options.publicPath??"/media/images",concurrency:options.concurrency??4,upscale:options.upscale??false}}widths(widths){if(!widths.length)throw new TypeError("Image widths are required");widths.forEach((value)=>integer("Image width",value,1,16384));this.targetWidths=[...new Set(widths)].sort((a,b)=>a-b);return this}formats(formats){if(!formats.length)throw new TypeError("Image formats are required");this.targetFormats=[...new Set(formats)];return this}fit(fit){this.targetFit=fit;return this}height(value){integer("Image height",value,1,16384);this.targetHeight=value;this.targetAspectRatio=undefined;return this}aspectRatio(value){if(!Number.isFinite(value)||value<=0||value>100)throw new TypeError("Image aspect ratio must be between 0 and 100");this.targetAspectRatio=value;this.targetHeight=undefined;return this}position(value){this.targetPosition=value;return this}preset(value){const presets={avatar:{widths:[64,128,256,512],ratio:1,fit:"cover",original:false},content:{widths:[320,640,960,1280,1920],fit:"inside",original:true},hero:{widths:[640,1280,1920,2560],ratio:16/9,fit:"cover",original:true},thumbnail:{widths:[160,320,640],ratio:16/9,fit:"cover",original:false}};const preset=presets[value];this.targetWidths=[...preset.widths];this.targetFit=preset.fit;this.targetAspectRatio="ratio"in preset?preset.ratio:undefined;this.targetHeight=undefined;this.includeOriginal=preset.original;return this}quality(value){integer("Image quality",value,1,100);this.targetQuality=value;return this}original(include){this.includeOriginal=include;return this}output(dir,publicPath="/media/images"){this.options.outputDir=resolve(dir);this.options.publicPath=`/${publicPath.replace(/^\/+|\/+$/g,"")}`;return this}storage(adapter,prefix="media/images"){this.targetStorage={adapter,prefix:prefix.replace(/^\/+|\/+$/g,"")};return this}async generate(){integer("Image concurrency",this.options.concurrency,1,32);const sourcePath=resolveImageSource(this.source,this.options.root);if(this.options.authorize&&!await this.options.authorize(sourcePath,this.options.authorizationContext))throw new Error("Image delivery is not authorized");const realRoot=await realpath(resolve(this.options.root));const realSource=await realpath(sourcePath);const realRelation=relative(realRoot,realSource);if(realRelation===".."||realRelation.startsWith("../")||isAbsolute(realRelation))throw new Error("Image source must stay inside the configured root");const MAX_IMAGE_SOURCE_BYTES=100*1024*1024;const MAX_IMAGE_PIXELS=1e8;const info=await stat(realSource);if(info.size>MAX_IMAGE_SOURCE_BYTES)throw new Error(`Image source exceeds maximum allowed size (${MAX_IMAGE_SOURCE_BYTES} bytes)`);const bytes=new Uint8Array(await readFile(realSource));const hash=createHash("sha256").update(bytes).digest("hex");const decoded=await decode(bytes);if(decoded.width*decoded.height>MAX_IMAGE_PIXELS)throw new Error(`Image dimensions (${decoded.width}x${decoded.height}) exceed maximum allowed pixel count`);const widths=this.targetWidths.filter((width)=>this.options.upscale||width<=decoded.width);if(this.includeOriginal&&!widths.includes(decoded.width))widths.push(decoded.width);const tasks=[...new Set(widths)].sort((a,b)=>a-b).flatMap((width)=>this.targetFormats.map((format)=>({width,format})));const variants=[];let cursor=0;await Promise.all(Array.from({length:Math.min(tasks.length,this.options.concurrency)},async()=>{while(cursor<tasks.length){const task=tasks[cursor++];variants.push(await this.variant(decoded,hash,sourcePath,task.width,task.format))}}));variants.sort((a,b)=>a.width-b.width||this.targetFormats.indexOf(a.format)-this.targetFormats.indexOf(b.format));return{source:{width:decoded.width,height:decoded.height,hash},variants,placeholder:Buffer.from(imageToSplatHash(decoded)).toString("base64url")}}async variant(source,hash,sourcePath,width,format){const height=this.targetHeight??(this.targetAspectRatio?Math.max(1,Math.round(width/this.targetAspectRatio)):undefined);if(!this.options.upscale&&(width>source.width||height!==undefined&&height>source.height))throw new TypeError(`Image variant ${width}x${height??"auto"} would upscale the source`);const output=width===source.width&&height===undefined?source:resize(source,{width,height,fit:this.targetFit,position:this.targetPosition});if(!this.options.upscale&&(output.width>source.width||output.height>source.height))throw new TypeError(`Image variant ${output.width}x${output.height} would upscale the source`);const cacheKey=createHash("sha256").update(`${hash}:${width}:${height??"auto"}:${format}:${this.targetFit}:${this.targetPosition}:${this.targetQuality}:${codecFingerprint()}`).digest("hex");const stem=basename(sourcePath,extname(sourcePath)).replace(/[^a-zA-Z0-9_-]/g,"-")||"image";const filename=`${stem}-${output.width}x${output.height}-${cacheKey.slice(0,16)}.${format==="jpeg"?"jpg":format}`;const path=resolve(this.options.outputDir,filename);if(this.targetStorage){const key=this.targetStorage.prefix?`${this.targetStorage.prefix}/${filename}`:filename;if(await this.targetStorage.adapter.fileExists(key)){const existing=await this.targetStorage.adapter.stat(key);return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});const written=await this.targetStorage.adapter.write(key,encoded);return{width:output.width,height:output.height,bytes:written.size,format,mimeType:mime[format],path:key,url:await this.targetStorage.adapter.publicUrl(key),cacheKey}}const existing=await stat(path).catch(()=>null);if(existing)return{width:output.width,height:output.height,bytes:existing.size,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey};const encoded=await encode(output,format,{quality:this.targetQuality,progressive:true});await mkdir(this.options.outputDir,{recursive:true});const temporary=`${path}.${process.pid}.${randomUUID()}.tmp`;await writeFile(temporary,encoded);await rename(temporary,path);return{width:output.width,height:output.height,bytes:encoded.byteLength,format,mimeType:mime[format],path,url:`${this.options.publicPath}/${filename}`,cacheKey}}}export function image(source,options={}){return new ImageBuilder(source,options)}function accepted(accept,mimeType){const[type,subtype]=mimeType.split("/");let best=0;for(const item of accept.split(",")){const[range="*/*",...params]=item.trim().toLowerCase().split(";").map((value)=>value.trim());const[acceptedType,acceptedSubtype]=range.split("/");if(acceptedType!=="*"&&acceptedType!==type||acceptedSubtype!=="*"&&acceptedSubtype!==subtype)continue;const raw=params.find((param)=>param.startsWith("q="));best=Math.max(best,raw?Number.parseFloat(raw.slice(2))||0:1)}return best}export function negotiateImageVariant(variants,accept="*/*",width){const widths=[...new Set(variants.map((item)=>item.width))].sort((a,b)=>a-b);const target=width===undefined?widths.at(-1):widths.find((value)=>value>=width)??widths.at(-1);return variants.filter((item)=>item.width===target).map((variant,index)=>({variant,index,q:accepted(accept||"*/*",variant.mimeType)})).filter((item)=>item.q>0).sort((a,b)=>b.q-a.q||a.index-b.index)[0]?.variant}export function imageResponseHeaders(variant){return{"Content-Type":variant.mimeType,"Content-Length":String(variant.bytes),"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${variant.cacheKey}"`,Vary:"Accept","X-Image-Width":String(variant.width),"X-Image-Height":String(variant.height)}}export function signImageTransform(path,expires,secret){return createHmac("sha256",secret).update(`${path}
|
|
2
2
|
${expires}`).digest("base64url")}export function verifyImageTransform(path,expires,signature,secret,now=Date.now()){if(!Number.isInteger(expires)||expires*1000<=now)return false;const expected=Buffer.from(signImageTransform(path,expires,secret));const actual=Buffer.from(signature);return expected.length===actual.length&&timingSafeEqual(expected,actual)}
|
package/dist/social.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir}from"node:fs/promises";import process from"node:process";import{generateSocialCards,renderSocialCard}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";const PRESET_SIZES={og:{width:1200,height:630},twitter:{width:1200,height:600},square:{width:1200,height:1200},portrait:{width:1200,height:1500}};export function socialCardName(path){const trimmed=path.replace(/^\/+|\/+$/g,"");return trimmed===""?"og":trimmed.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}async function socialCardTheme(images,root){const social=themed(images,images.social);const fonts=await loadFonts(images.fonts,root);const mark=await markPainter(social.mark,root,{colorScheme:social.markColorScheme});const presets=social.presets?.length?social.presets:["og"];return{social,presets,deviceOptions:device(social.device),shared:{titleFont:fonts.title,bodyFont:fonts.body,brand:social.brand,drawMark:mark?.draw,markAspect:mark?.aspect,markPlate:social.markPlate===false?null:color(social.markPlate),surface:background(social.background,root),color:color(social.color),mutedColor:color(social.mutedColor),accent:color(social.accent),format:social.format??"jpeg",quality:social.quality,presets}}}export function textSizes(set,page){return{titleSize:page?.titleSize??set?.titleSize,eyebrowSize:page?.eyebrowSize??set?.eyebrowSize,subtitleSize:page?.subtitleSize??set?.subtitleSize}}function cardForeground(shot,deviceOptions,root,label){if(!shot)return;return{image:requireProjectFile(shot,root,label),radius:deviceOptions?.radius,borderColor:deviceOptions?.borderColor,shadow:deviceOptions?.shadow,scale:deviceOptions?.scale}}export async function generateSocialCardSet(images,root=process.cwd()){if(images.social?.enabled!==true)return[];const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const outputDir=projectFile(social.outputDir??"public/social",root);const publicPath=`/${(social.publicPath??"/social").replace(/^\/+|\/+$/g,"")}`;await mkdir(outputDir,{recursive:true});const pages=social.pages?.length?social.pages:[{path:"/",title:social.brand??"Home"}];const results=[];for(const page of pages){const name=socialCardName(page.path);const shot=page.foreground??social.foreground;const files=await generateSocialCards(outputDir,{...shared,...textSizes(social.text,page.text),name,title:page.title,eyebrow:page.eyebrow,subtitle:page.subtitle,foreground:cardForeground(shot,deviceOptions,root,`Product shot for ${page.path}`)});const urls=Object.fromEntries(Object.entries(files).map(([preset,file])=>[preset,`${publicPath}/${file.slice(file.lastIndexOf("/")+1)}`]));results.push({path:page.path,name,files,urls,width:PRESET_SIZES[presets[0]].width,height:PRESET_SIZES[presets[0]].height,title:page.title})}return results}export async function renderOnDemandSocialCard(images,card,root=process.cwd()){if(images.social?.enabled!==true)return null;const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const preset=card.preset??presets[0];const{width,height}=PRESET_SIZES[preset];const format=shared.format;const{presets:_presets,...cardOptions}=shared;const bytes=await renderSocialCard({...cardOptions,...textSizes(social.text),width,height,title:card.title,eyebrow:card.eyebrow,subtitle:card.subtitle,foreground:cardForeground(card.foreground??social.foreground,deviceOptions,root,"On-demand product shot")});return{bytes,contentType:format==="jpeg"?"image/jpeg":`image/${format}`,width,height}}export function socialMetaTags(card,siteUrl,format="jpeg"){const base=siteUrl.replace(/\/+$/,"");const primary=`${base}${card.urls.og??Object.values(card.urls)[0]}`;const mimeType=format==="jpeg"?"image/jpeg":`image/${format}`;const tags=[`<meta property="og:image" content="${primary}">`,`<meta property="og:image:type" content="${mimeType}">`,`<meta property="og:image:width" content="${card.width}">`,`<meta property="og:image:height" content="${card.height}">`,`<meta property="og:image:alt" content="${escapeAttribute(card.title)}">`,`<meta name="twitter:card" content="summary_large_image">`,`<meta name="twitter:image" content="${primary}">`,`<meta name="twitter:image:alt" content="${escapeAttribute(card.title)}">`];return tags}function escapeAttribute(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}
|
|
1
|
+
import{mkdir}from"node:fs/promises";import process from"node:process";import{generateSocialCards,renderSocialCard}from"ts-images";import{loadFonts}from"./fonts";import{background,color,device,markPainter,projectFile,requireProjectFile,themed}from"./theme";const PRESET_SIZES={og:{width:1200,height:630},twitter:{width:1200,height:600},square:{width:1200,height:1200},portrait:{width:1200,height:1500}};export function socialCardName(path){const trimmed=path.replace(/^\/+|\/+$/g,"");return trimmed===""?"og":trimmed.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}async function socialCardTheme(images,root){const social=themed(images,images.social);const fonts=await loadFonts(images.fonts,root);const mark=await markPainter(social.mark,root,{colorScheme:social.markColorScheme});const presets=social.presets?.length?social.presets:["og"];return{social,presets,deviceOptions:device(social.device),shared:{titleFont:fonts.title,bodyFont:fonts.body,brand:social.brand,drawMark:mark?.draw,markAspect:mark?.aspect,markPlate:social.markPlate===false?null:color(social.markPlate),surface:background(social.background,root),color:color(social.color),mutedColor:color(social.mutedColor),accent:color(social.accent),format:social.format??"jpeg",quality:social.quality,presets}}}export function textSizes(set,page){return{titleSize:page?.titleSize??set?.titleSize,eyebrowSize:page?.eyebrowSize??set?.eyebrowSize,subtitleSize:page?.subtitleSize??set?.subtitleSize}}function cardForeground(shot,deviceOptions,root,label){if(!shot)return;return{image:requireProjectFile(shot,root,label),radius:deviceOptions?.radius,borderColor:deviceOptions?.borderColor,shadow:deviceOptions?.shadow,scale:deviceOptions?.scale}}export async function generateSocialCardSet(images,root=process.cwd()){if(images.social?.enabled!==true)return[];const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const outputDir=projectFile(social.outputDir??"public/social",root);const publicPath=`/${(social.publicPath??"/social").replace(/^\/+|\/+$/g,"")}`;await mkdir(outputDir,{recursive:true});const pages=social.pages?.length?social.pages:[{path:"/",title:social.brand??"Home"}];const results=[];for(const page of pages){const name=socialCardName(page.path);const shot=page.foreground??social.foreground;const files=await generateSocialCards(outputDir,{...shared,...textSizes(social.text,page.text),name,title:page.title,eyebrow:page.eyebrow,subtitle:page.subtitle,foreground:cardForeground(shot,deviceOptions,root,`Product shot for ${page.path}`)});const urls=Object.fromEntries(Object.entries(files).map(([preset,file])=>[preset,`${publicPath}/${file.slice(file.lastIndexOf("/")+1)}`]));results.push({path:page.path,name,files,urls,width:PRESET_SIZES[presets[0]].width,height:PRESET_SIZES[presets[0]].height,title:page.title})}return results}export async function renderOnDemandSocialCard(images,card,root=process.cwd()){if(images.social?.enabled!==true)return null;const{social,presets,deviceOptions,shared}=await socialCardTheme(images,root);const preset=card.preset??presets[0];if(!Object.hasOwn(PRESET_SIZES,preset))throw new TypeError(`Unknown social card preset: ${String(preset)}`);const{width,height}=PRESET_SIZES[preset];const format=shared.format;const{presets:_presets,...cardOptions}=shared;const bytes=await renderSocialCard({...cardOptions,...textSizes(social.text),width,height,title:card.title,eyebrow:card.eyebrow,subtitle:card.subtitle,foreground:cardForeground(card.foreground??social.foreground,deviceOptions,root,"On-demand product shot")});return{bytes,contentType:format==="jpeg"?"image/jpeg":`image/${format}`,width,height}}export function socialMetaTags(card,siteUrl,format="jpeg"){const base=siteUrl.replace(/\/+$/,"");const primary=`${base}${card.urls.og??Object.values(card.urls)[0]}`;const mimeType=format==="jpeg"?"image/jpeg":`image/${format}`;const tags=[`<meta property="og:image" content="${escapeAttribute(primary)}">`,`<meta property="og:image:type" content="${escapeAttribute(mimeType)}">`,`<meta property="og:image:width" content="${card.width}">`,`<meta property="og:image:height" content="${card.height}">`,`<meta property="og:image:alt" content="${escapeAttribute(card.title)}">`,`<meta name="twitter:card" content="summary_large_image">`,`<meta name="twitter:image" content="${escapeAttribute(primary)}">`,`<meta name="twitter:image:alt" content="${escapeAttribute(card.title)}">`];return tags}function escapeAttribute(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}
|
package/dist/upload.d.ts
CHANGED
|
@@ -1,8 +1,29 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Bound decoding, apply camera orientation, and publish pixels without private
|
|
3
|
+
* metadata. Optionally scale down, re-encode, keep the smaller of the requested
|
|
4
|
+
* and the source encoding, and cut a thumbnail, all from one decode.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sanitizeImageUpload(bytes: Uint8Array, options?: SanitizeImageUploadOptions): Promise<SanitizedImage>;
|
|
3
7
|
export declare interface SanitizedImage {
|
|
4
8
|
bytes: Uint8Array
|
|
5
9
|
width: number
|
|
6
10
|
height: number
|
|
7
|
-
format:
|
|
11
|
+
format: UploadImageFormat
|
|
12
|
+
thumbnail?: SanitizedThumbnail
|
|
8
13
|
}
|
|
14
|
+
export declare interface SanitizedThumbnail {
|
|
15
|
+
bytes: Uint8Array
|
|
16
|
+
width: number
|
|
17
|
+
height: number
|
|
18
|
+
format: UploadImageFormat
|
|
19
|
+
}
|
|
20
|
+
export declare interface SanitizeImageUploadOptions {
|
|
21
|
+
maxBytes?: number
|
|
22
|
+
maxPixels?: number
|
|
23
|
+
maxDimension?: number
|
|
24
|
+
format?: UploadImageFormat
|
|
25
|
+
quality?: number
|
|
26
|
+
keepIfSmaller?: boolean
|
|
27
|
+
thumbnail?: { maxDimension: number, format?: UploadImageFormat, quality?: number }
|
|
28
|
+
}
|
|
29
|
+
export type UploadImageFormat = 'jpeg' | 'png' | 'webp';
|
package/dist/upload.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decode,encode,getMetadata}from"ts-images";export async function sanitizeImageUpload(bytes,options={}){const maxBytes=options.maxBytes??12*1024*1024;const maxPixels=options.maxPixels??40000000;if(!Number.isSafeInteger(maxBytes)||maxBytes<=0||!Number.isSafeInteger(maxPixels)||maxPixels<=0)throw new RangeError("Image limits must be positive whole numbers");if(!bytes.byteLength||bytes.byteLength>maxBytes)throw new RangeError("Image exceeds the upload byte limit");const metadata=await getMetadata(bytes);const sourceFormat=String(metadata.format).toLowerCase();const
|
|
1
|
+
import{decode,encode,getMetadata,resize}from"ts-images";const FORMATS=["jpeg","png","webp"];const DEFAULT_QUALITY=90;function positiveWhole(value,name){if(value!==undefined&&(!Number.isSafeInteger(value)||value<=0))throw new RangeError(`${name} must be a positive whole number`)}function checkQuality(value,name){if(value!==undefined&&(!Number.isInteger(value)||value<1||value>100))throw new RangeError(`${name} must be a whole number from 1 to 100`)}function checkFormat(value,name){if(value!==undefined&&!FORMATS.includes(value))throw new TypeError(`${name} must be jpeg, png or webp`)}function pixelsOnly(image){return{width:image.width,height:image.height,data:image.data,colorSpace:image.colorSpace,hasAlpha:image.hasAlpha,bitDepth:image.bitDepth}}function fitWithin(image,maxDimension){if(maxDimension===undefined)return image;const longest=Math.max(image.width,image.height);if(longest<=maxDimension)return image;const scale=maxDimension/longest;const width=Math.max(1,Math.round(image.width*scale));const height=Math.max(1,Math.round(image.height*scale));return pixelsOnly(resize(image,{width,height,fit:"fill"}))}export async function sanitizeImageUpload(bytes,options={}){const maxBytes=options.maxBytes??12*1024*1024;const maxPixels=options.maxPixels??40000000;if(!Number.isSafeInteger(maxBytes)||maxBytes<=0||!Number.isSafeInteger(maxPixels)||maxPixels<=0)throw new RangeError("Image limits must be positive whole numbers");positiveWhole(options.maxDimension,"maxDimension");checkQuality(options.quality,"quality");checkFormat(options.format,"format");if(options.thumbnail){positiveWhole(options.thumbnail.maxDimension,"thumbnail.maxDimension");if(options.thumbnail.maxDimension===undefined)throw new RangeError("thumbnail.maxDimension must be a positive whole number");checkQuality(options.thumbnail.quality,"thumbnail.quality");checkFormat(options.thumbnail.format,"thumbnail.format")}if(!bytes.byteLength||bytes.byteLength>maxBytes)throw new RangeError("Image exceeds the upload byte limit");const metadata=await getMetadata(bytes);const sourceFormat=String(metadata.format).toLowerCase();const source=sourceFormat==="jpg"?"jpeg":sourceFormat;if(!FORMATS.includes(source))throw new TypeError("Send a JPEG, PNG or WebP photo");if(!Number.isSafeInteger(metadata.width)||!Number.isSafeInteger(metadata.height)||metadata.width<=0||metadata.height<=0||metadata.width*metadata.height>maxPixels)throw new RangeError("Image exceeds the decoded pixel limit");const decoded=pixelsOnly(await decode(bytes,{applyOrientation:true}));const pixels=fitWithin(decoded,options.maxDimension);const format=options.format??source;const quality=options.quality??DEFAULT_QUALITY;let output=await encode(pixels,format,{quality});let outputFormat=format;if(options.keepIfSmaller&&(format!==source||quality!==DEFAULT_QUALITY)){const sanitized=await encode(pixels,source,{quality:DEFAULT_QUALITY});if(output.byteLength>=sanitized.byteLength){output=sanitized;outputFormat=source}}if(output.byteLength>maxBytes)throw new RangeError("Normalized image exceeds the upload byte limit");const result={bytes:output,width:pixels.width,height:pixels.height,format:outputFormat};if(options.thumbnail){const small=fitWithin(pixels,options.thumbnail.maxDimension);const thumbnailFormat=options.thumbnail.format??outputFormat;const thumbnailBytes=await encode(small,thumbnailFormat,{quality:options.thumbnail.quality??quality});result.thumbnail={bytes:thumbnailBytes,width:small.width,height:small.height,format:thumbnailFormat}}return result}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/image",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.755",
|
|
6
6
|
"description": "Native responsive image delivery for Stacks.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"license": "MIT",
|
|
@@ -32,10 +32,10 @@
|
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@stacksjs/ts-svg": "0.1.8",
|
|
35
|
-
"@stacksjs/types": "0.75.
|
|
35
|
+
"@stacksjs/types": "0.75.755",
|
|
36
36
|
"ts-images": "0.2.35"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"better-dx": "^0.2.
|
|
39
|
+
"better-dx": "^0.2.41"
|
|
40
40
|
}
|
|
41
41
|
}
|