Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@giphy/js-util

Package Overview
Dependencies
Maintainers
1
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@giphy/js-util - npm Package Compare versions

Comparing version 0.0.0-canary-20230620165510 to 0.0.0-canary-20230621031504

dist/bestfit.d.ts

87

dist/index.d.ts

@@ -1,79 +0,8 @@

import { IRendition, IGif, IImage, IImages } from '@giphy/js-types';
declare const setRenditionScaleUpMaxPixels: (pixels: number) => void;
/**
* Finds image rendition that best fits a given container preferring images
* ##### Note: all renditions are assumed to have the same aspect ratio
*
* When we have a portrait target and landscape gif, we choose a higher rendition to match
* the height of the portrait target, otherwise it's blurry (same applies for landscape to portrait)
*
* @name bestfit
* @function
* @param {Array.<Object>} renditions available image renditions each having a width and height property
* @param {Number} width
* @param {Number} height
* @param {Number} scaleUpMaxPixels the maximum pixels an asset should be scaled up
*/
declare function bestfit(renditions: Array<IRendition>, width: number, height: number, scaleUpMaxPixels?: number): IRendition;
declare function mapValues(object: any, mapFn: (val: any, key: string) => any): any;
declare function forEach(object: any, mapFn: (val: any, key: any) => void): void;
declare function take<T>(arr: T[], count?: number): T[];
declare function without<T>(arr: T[], values: T[]): T[];
declare function pick<T extends object, U extends keyof T>(object: T, pick: Array<U>): Pick<T, U>;
/**
* @param el HTMLElement
* @returns calculated properties of DOMReact
*/
declare const getClientRect: (el: HTMLElement) => DOMRectReadOnly;
declare const getPingbackId: () => string;
declare const getSpecificRendition: ({ images, is_sticker: isSticker }: IGif, renditionLabel: string, isStill?: boolean, useVideo?: boolean) => string;
interface IRenditionWithName extends IRendition {
renditionName: keyof IImages;
}
declare const getBestVideo: (video: IGif['video'], width: number, height: number) => IImage | undefined;
declare const getBestRendition: (images: IImages, gifWidth: number, gifHeight: number, scaleUpMaxPixels?: number) => IRenditionWithName;
type Options = {
isStill?: boolean;
useVideo?: boolean;
scaleUpMaxPixels?: number;
};
declare const getBestRenditionUrl: ({ images, video, type }: IGif, gifWidth: number, gifHeight: number, options?: Options) => keyof IImages | '';
declare const getGifHeight: ({ images }: IGif, gifWidth: number) => number;
declare const getGifWidth: ({ images }: IGif, gifHeight: number) => number;
/**
* GIF Text - Alt Text: Generates alt text for
* GIF images based on username and tags.
* @prop {Gif}
* @return {String} GIF alt text.
*/
declare const getAltText: ({ alt_text, user, tags, is_sticker, title }: IGif) => string;
declare enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3
}
declare const Logger: {
ENABLED: boolean;
LEVEL: number;
PREFIX: string;
debug: (...msg: any) => void;
info: (...msg: any) => void;
warn: (...msg: any) => void;
error: (...msg: any) => void;
};
type GiphySDKRequestHeader = 'X-GIPHY-SDK-NAME' | 'X-GIPHY-SDK-VERSION' | 'X-GIPHY-SDK-PLATFORM';
declare const getGiphySDKRequestHeaders: () => Headers | undefined;
declare const appendGiphySDKRequestHeader: (key: GiphySDKRequestHeader, value: string) => void | undefined;
declare const appendGiphySDKRequestParam: (key: GiphySDKRequestHeader, value: string) => void | undefined;
declare const checkIfWebP: Promise<unknown>;
export { LogLevel, Logger, appendGiphySDKRequestHeader, appendGiphySDKRequestParam, bestfit, checkIfWebP, forEach, getAltText, getBestRendition, getBestRenditionUrl, getBestVideo, getClientRect, getGifHeight, getGifWidth, getGiphySDKRequestHeaders, getPingbackId, getSpecificRendition, mapValues, pick, setRenditionScaleUpMaxPixels, take, without };
export { default as bestfit, setRenditionScaleUpMaxPixels } from './bestfit';
export * from './collections';
export { default as getClientRect } from './get-client-rect-from-el';
export { default as getPingbackId } from './get-pingback-id';
export { getAltText, getBestRendition, getBestRenditionUrl, getBestVideo, getGifHeight, getGifWidth, getSpecificRendition, } from './gif-utils';
export * from './log';
export * from './sdk-headers';
export { checkIfWebP } from './webp-check';

@@ -1,320 +0,41 @@

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
return a;
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/log.ts
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
return LogLevel2;
})(LogLevel || {});
var Logger = {
ENABLED: typeof window !== "undefined" && typeof location !== "undefined" && location.search.indexOf("giphy-debug") !== -1,
LEVEL: 0,
PREFIX: "GiphyJS",
debug: (...msg) => {
if (Logger.ENABLED && Logger.LEVEL <= 0 /* DEBUG */) {
console.debug(Logger.PREFIX, ...msg);
}
},
info: (...msg) => {
if (Logger.ENABLED && Logger.LEVEL <= 1 /* INFO */) {
console.info(Logger.PREFIX, ...msg);
}
},
warn: (...msg) => {
if (Logger.ENABLED && Logger.LEVEL <= 2 /* WARN */) {
console.warn(Logger.PREFIX, ...msg);
}
},
error: (...msg) => {
if (Logger.ENABLED && Logger.LEVEL <= 3 /* ERROR */) {
console.error(Logger.PREFIX, ...msg);
}
}
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
// src/bestfit.ts
var closestArea = (width, height, renditions) => {
let currentBest = Infinity;
let result;
renditions.forEach((rendition) => {
const widthPercentage = rendition.width / width;
const heightPercentage = rendition.height / height;
const areaPercentage = widthPercentage * heightPercentage;
const testBest = Math.abs(1 - areaPercentage);
if (testBest < currentBest) {
currentBest = testBest;
result = rendition;
}
});
return result;
};
var SCALE_UP_MAX_PIXELS = 50;
var setRenditionScaleUpMaxPixels = (pixels) => {
Logger.debug(`@giphy/js-util set rendition selection scale up max pixels to ${pixels}`);
SCALE_UP_MAX_PIXELS = pixels;
};
function bestfit(renditions, width, height, scaleUpMaxPixels = SCALE_UP_MAX_PIXELS) {
let [largestRendition] = renditions;
const testRenditions = renditions.filter((rendition) => {
if (rendition.width * rendition.height > largestRendition.width * largestRendition.height) {
largestRendition = rendition;
}
return width - rendition.width <= scaleUpMaxPixels && height - rendition.height <= scaleUpMaxPixels;
});
if (testRenditions.length === 0) {
return largestRendition;
}
return closestArea(width, height, testRenditions);
}
var bestfit_default = bestfit;
// src/collections.ts
function mapValues(object, mapFn) {
if (Array.isArray(object)) {
throw `This map is just for objects, just use array.map for arrays`;
}
return Object.keys(object).reduce((result, key) => {
result[key] = mapFn(object[key], key);
return result;
}, {});
}
function forEach(object, mapFn) {
if (Array.isArray(object)) {
throw `This map is just for objects, just use array.forEach for arrays`;
}
return Object.keys(object).forEach((key) => {
mapFn(object[key], key);
});
}
function take(arr, count = 0) {
return arr.slice(0, count);
}
function without(arr, values) {
return arr.filter((val) => values.indexOf(val) === -1);
}
function pick(object, pick2) {
const res = {};
pick2.forEach((key) => {
if (object[key] !== void 0) {
res[key] = object[key];
}
});
return res;
}
// src/get-client-rect-from-el.ts
var getClientRect = (el) => {
let left = 0;
let top = 0;
const width = el.offsetWidth;
const height = el.offsetHeight;
do {
left += el.offsetLeft;
top += el.offsetTop;
el = el.offsetParent;
} while (el);
const result = {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
x: left,
y: top
};
return __spreadProps(__spreadValues({}, result), { toJSON: () => JSON.stringify(result) });
};
var get_client_rect_from_el_default = getClientRect;
// src/get-pingback-id.ts
import { v4 as uuid } from "uuid";
var pingbackId = "";
var idLength = 16;
var noUUIDRandom = () => {
let result = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < idLength; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
var getPingbackId = () => {
if (!pingbackId) {
try {
pingbackId = sessionStorage.getItem("giphyPingbackId");
} catch (_) {
}
if (!pingbackId) {
const hexTime = (/* @__PURE__ */ new Date()).getTime().toString(16);
try {
pingbackId = `${hexTime}${uuid().replace(/-/g, "")}`.substring(0, idLength);
} catch (error) {
pingbackId = noUUIDRandom();
}
try {
sessionStorage.setItem("giphyPingbackId", pingbackId);
} catch (_) {
}
}
}
return pingbackId;
};
var get_pingback_id_default = getPingbackId;
// src/webp-check.ts
var SUPPORTS_WEBP = null;
var checkIfWebP = new Promise((resolve) => {
if (typeof Image === "undefined") {
resolve(false);
}
const webp = new Image();
webp.onload = () => {
SUPPORTS_WEBP = true;
resolve(SUPPORTS_WEBP);
};
webp.onerror = () => {
SUPPORTS_WEBP = false;
resolve(SUPPORTS_WEBP);
};
webp.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
});
// src/gif-utils.ts
var getSpecificRendition = ({ images, is_sticker: isSticker }, renditionLabel, isStill = false, useVideo = false) => {
if (!images || !renditionLabel)
return "";
isStill = isStill && !useVideo;
const rendition = images[`${renditionLabel}${isStill ? "_still" : ""}`];
if (rendition) {
if (isSticker || isStill) {
return rendition.url;
}
const webP = SUPPORTS_WEBP && rendition.webp;
return useVideo ? rendition.mp4 : webP || rendition.url;
}
return "";
};
var getBestVideo = (video, width, height) => {
let assets = video == null ? void 0 : video.assets;
if (assets) {
assets = __spreadValues({}, assets);
delete assets.source;
const filteredAssets = Object.values(assets).sort((a, b) => a.width - b.width);
return bestfit_default(filteredAssets, width, height);
}
};
var getRenditions = (type, images, video) => type === "video" && video && video.previews && !Object.keys(images).length ? video.previews : images;
var getBestRendition = (images, gifWidth, gifHeight, scaleUpMaxPixels) => {
const checkRenditions = pick(images, [
"original",
"fixed_width",
"fixed_height",
"fixed_width_small",
"fixed_height_small"
]);
const testImages = Object.entries(checkRenditions).map(([renditionName, val]) => __spreadValues({
renditionName
}, val));
return bestfit_default(testImages, gifWidth, gifHeight, scaleUpMaxPixels);
};
var getBestRenditionUrl = ({ images, video, type }, gifWidth, gifHeight, options = { isStill: false, useVideo: false }) => {
if (!gifWidth || !gifHeight || !images)
return "";
const { useVideo, isStill, scaleUpMaxPixels } = options;
const renditions = getRenditions(type, images, video);
const { renditionName } = getBestRendition(renditions, gifWidth, gifHeight, scaleUpMaxPixels);
const key = `${renditionName}${isStill && !useVideo ? "_still" : ""}`;
const rendition = renditions[key];
const match = useVideo ? rendition.mp4 : SUPPORTS_WEBP && rendition.webp ? rendition.webp : rendition.url;
return match || "";
};
var getGifHeight = ({ images }, gifWidth) => {
const { fixed_width } = images;
if (fixed_width) {
const { width, height } = fixed_width;
const aspectRatio = width / height;
return Math.round(gifWidth / aspectRatio);
}
return 0;
};
var getGifWidth = ({ images }, gifHeight) => {
const { fixed_width } = images;
if (fixed_width) {
const { width, height } = fixed_width;
const aspectRatio = width / height;
return Math.round(gifHeight * aspectRatio);
}
return 0;
};
var getAltText = ({ alt_text, user, tags = [], is_sticker = false, title = "" }) => {
if (alt_text) {
return alt_text;
}
if (title) {
return title;
}
const username = user && user.username || "";
const filteredTags = take(without(tags, ["transparent"]), username ? 4 : 5);
return `${username ? `${username} ` : ``}${filteredTags.join(" ")} ${is_sticker ? "Sticker" : "GIF"}`;
};
// src/sdk-headers.ts
var gl = (typeof window !== "undefined" ? window : global) || {};
gl._GIPHY_SDK_HEADERS_ = gl._GIPHY_SDK_HEADERS_ || (gl.Headers ? new gl.Headers({
"X-GIPHY-SDK-PLATFORM": "web"
}) : void 0);
var getGiphySDKRequestHeaders = () => gl._GIPHY_SDK_HEADERS_;
var appendGiphySDKRequestHeader = (key, value) => {
var _a;
return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
};
var appendGiphySDKRequestParam = (key, value) => {
var _a;
return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
};
export {
LogLevel,
Logger,
appendGiphySDKRequestHeader,
appendGiphySDKRequestParam,
bestfit_default as bestfit,
checkIfWebP,
forEach,
getAltText,
getBestRendition,
getBestRenditionUrl,
getBestVideo,
get_client_rect_from_el_default as getClientRect,
getGifHeight,
getGifWidth,
getGiphySDKRequestHeaders,
get_pingback_id_default as getPingbackId,
getSpecificRendition,
mapValues,
pick,
setRenditionScaleUpMaxPixels,
take,
without
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkIfWebP = exports.getSpecificRendition = exports.getGifWidth = exports.getGifHeight = exports.getBestVideo = exports.getBestRenditionUrl = exports.getBestRendition = exports.getAltText = exports.getPingbackId = exports.getClientRect = exports.setRenditionScaleUpMaxPixels = exports.bestfit = void 0;
var bestfit_1 = require("./bestfit");
Object.defineProperty(exports, "bestfit", { enumerable: true, get: function () { return __importDefault(bestfit_1).default; } });
Object.defineProperty(exports, "setRenditionScaleUpMaxPixels", { enumerable: true, get: function () { return bestfit_1.setRenditionScaleUpMaxPixels; } });
__exportStar(require("./collections"), exports);
var get_client_rect_from_el_1 = require("./get-client-rect-from-el");
Object.defineProperty(exports, "getClientRect", { enumerable: true, get: function () { return __importDefault(get_client_rect_from_el_1).default; } });
var get_pingback_id_1 = require("./get-pingback-id");
Object.defineProperty(exports, "getPingbackId", { enumerable: true, get: function () { return __importDefault(get_pingback_id_1).default; } });
var gif_utils_1 = require("./gif-utils");
Object.defineProperty(exports, "getAltText", { enumerable: true, get: function () { return gif_utils_1.getAltText; } });
Object.defineProperty(exports, "getBestRendition", { enumerable: true, get: function () { return gif_utils_1.getBestRendition; } });
Object.defineProperty(exports, "getBestRenditionUrl", { enumerable: true, get: function () { return gif_utils_1.getBestRenditionUrl; } });
Object.defineProperty(exports, "getBestVideo", { enumerable: true, get: function () { return gif_utils_1.getBestVideo; } });
Object.defineProperty(exports, "getGifHeight", { enumerable: true, get: function () { return gif_utils_1.getGifHeight; } });
Object.defineProperty(exports, "getGifWidth", { enumerable: true, get: function () { return gif_utils_1.getGifWidth; } });
Object.defineProperty(exports, "getSpecificRendition", { enumerable: true, get: function () { return gif_utils_1.getSpecificRendition; } });
__exportStar(require("./log"), exports);
__exportStar(require("./sdk-headers"), exports);
var webp_check_1 = require("./webp-check");
Object.defineProperty(exports, "checkIfWebP", { enumerable: true, get: function () { return webp_check_1.checkIfWebP; } });
//# sourceMappingURL=index.js.map
{
"scripts": {
"lint": "run -T eslint . --ext .ts,.tsx",
"clean": "rm -rf ./dist",
"clean": "rm -rf ./dist ./esm",
"dev": "tsc --watch",
"build": "run -T tsup src/index.ts --format cjs,esm --dts && run -T publint",
"build": "tsc && npm run build:esm",
"build:esm": "tsc -p ./tsconfig-esm.json",
"prepublish": "npm run clean && npm run build",

@@ -12,20 +13,12 @@ "test": "run -T jest --config ./jestconfig.js",

"name": "@giphy/js-util",
"version": "0.0.0-canary-20230620165510",
"version": "0.0.0-canary-20230621031504",
"main": "dist/index.js",
"description": "Shared giphy js utils",
"homepage": "https://github.com/Giphy/giphy-js/tree/master/packages/util",
"main": "dist/index.cjs",
"types": "dist/index.d.ts",
"module": "dist/index.js",
"type": "module",
"module": "esm/index.js",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"esm/",
"src/**/*"

@@ -32,0 +25,0 @@ ],

@@ -6,3 +6,8 @@ import { IGif, IImages, ImageAllTypes, IUser } from '@giphy/js-types'

jest.mock('../webp-check')
describe('response parsing', () => {
afterEach(() => {
require('../webp-check').__setWebP(false)
})
test('getGifHeight getGifWidth', () => {

@@ -72,4 +77,5 @@ const gif = {

expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { useVideo: true })).toBe(fixedWidth.mp4)
expect(getBestRenditionUrl(dummyGif as IGif, 10, 10)).toBe(fixedWidth.url)
expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { isStill: true })).toBe(fixedWidthStill.url)
require('../webp-check').__setWebP(true)
expect(getBestRenditionUrl(dummyGif as IGif, 10, 10)).toBe(fixedWidth.webp)
expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { isStill: true })).toBe(fixedWidthStill.webp)
})

@@ -103,3 +109,4 @@

expect(getSpecificRendition(dummyGif as IGif, 'fixed_width_still', true, true)).toBe(fixedWidthStill.mp4)
expect(getSpecificRendition(dummyGif as IGif, 'fixed_width')).toBe(fixedWidth.url)
require('../webp-check').__setWebP(true)
expect(getSpecificRendition(dummyGif as IGif, 'fixed_width')).toBe(fixedWidth.webp)
expect(getSpecificRendition(dummyGif as IGif, 'dsakfjslkj')).toBe('')

@@ -106,0 +113,0 @@ expect(getSpecificRendition({} as IGif, 'fixed_width')).toBe('')

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc