@ecency/render-helper 2.5.39 → 2.5.41

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.
@@ -38,6 +38,19 @@ interface RenderOptions {
38
38
  * internal is the point of a self-hosted blog.
39
39
  */
40
40
  externalProfileBase?: string;
41
+ /**
42
+ * When true, author-supplied pixel `width` and `height` on a body `<img>`
43
+ * are kept. Browsers map that pair to an aspect ratio, so a consumer whose
44
+ * images are `max-width: 100%; height: auto` reserves the box before the
45
+ * file loads. The default strips both attributes, which is what every
46
+ * current consumer renders, so opting in is a layout change: the author's
47
+ * pixel size becomes the reserved box (still capped by `max-width`).
48
+ *
49
+ * Only a unitless pair inside a sane range is kept. Percentages, a single
50
+ * side, and `style` are not: `style` stays blocked outright, because it is
51
+ * the attribute an author would use to inject CSS.
52
+ */
53
+ preserveImageDimensions?: boolean;
41
54
  }
42
55
 
43
56
  /**
@@ -68,7 +68,7 @@ var YOUTUBE_REGEX = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|shorts\
68
68
  var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/(?:www\.|m\.)?youtube\.com\/(embed|shorts)\/.*/i;
69
69
  var VIMEO_REGEX = /(https?:\/\/)?(www\.)?(?:vimeo)\.com.*(?:videos|video|channels|)\/([\d]+)/i;
70
70
  var VIMEO_EMBED_REGEX = /https:\/\/player\.vimeo\.com\/video\/([0-9]+)(?:$|[?#])/;
71
- var BITCHUTE_REGEX = /^(?:https?:\/\/)?(?:www\.)?bitchute\.com\/(?:video|embed)\/([a-z0-9]+)/i;
71
+ var BITCHUTE_REGEX = /^(?:https?:\/\/)?(?:www\.)?bitchute\.com\/(?:video|embed)\/([a-z0-9_-]+)/i;
72
72
  var D_TUBE_REGEX = /(https?:\/\/d\.tube\/#!\/v\/)(\w+)\/(\w+)/g;
73
73
  var D_TUBE_REGEX2 = /(https?:\/\/d\.tube\/v\/)(\w+)\/(\w+)/g;
74
74
  var D_TUBE_EMBED_REGEX = /^https:\/\/emb\.d\.tube\/#!\/[^/?#]+\/[^/?#]+(?:$|[?#])/i;
@@ -773,6 +773,27 @@ function buildPictureSources(rawUrl) {
773
773
  return { avif, webp };
774
774
  }
775
775
 
776
+ // src/methods/image-dimensions.ts
777
+ var MAX_IMAGE_DIMENSION_PX = 8192;
778
+ var MAX_IMAGE_DIMENSION_RATIO = 40;
779
+ function parsePixelDimension(value) {
780
+ if (value == null) return null;
781
+ const trimmed = value.trim();
782
+ if (!/^\d{1,4}$/.test(trimmed)) return null;
783
+ const n = Number(trimmed);
784
+ if (n < 1 || n > MAX_IMAGE_DIMENSION_PX) return null;
785
+ return n;
786
+ }
787
+ function authorPixelSize(width, height) {
788
+ const w = parsePixelDimension(width);
789
+ const h = parsePixelDimension(height);
790
+ if (w == null || h == null) return null;
791
+ const larger = Math.max(w, h);
792
+ const smaller = Math.min(w, h);
793
+ if (larger / smaller > MAX_IMAGE_DIMENSION_RATIO) return null;
794
+ return { width: String(w), height: String(h) };
795
+ }
796
+
776
797
  // src/methods/sanitize-html.method.ts
777
798
  var EMBED_SRC_DATA_ATTRS = /* @__PURE__ */ new Set(["data-embed-src", "data-video-href"]);
778
799
  var isSafeNavValue = (value) => {
@@ -787,9 +808,34 @@ var isProxyPSrcset = (srcset) => {
787
808
  const candidates = srcset.split(",").map((c) => c.trim().split(/\s+/)[0]).filter(Boolean);
788
809
  return candidates.length > 0 && candidates.every((url) => url.startsWith(`${base}/p/`));
789
810
  };
790
- function sanitizeHtml(html) {
811
+ var QUOTED_ATTR = /\s([^\s"'>\/=]+)="([^"]*)"/g;
812
+ function enforceImageDimensionPair(html) {
813
+ return html.replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, (tag) => {
814
+ QUOTED_ATTR.lastIndex = 0;
815
+ const attrs = [];
816
+ let match;
817
+ while (match = QUOTED_ATTR.exec(tag)) {
818
+ attrs.push({ name: match[1].toLowerCase(), value: decodeEntities(match[2]) });
819
+ }
820
+ const width = attrs.find((attr) => attr.name === "width")?.value;
821
+ const height = attrs.find((attr) => attr.name === "height")?.value;
822
+ const src = (attrs.find((attr) => attr.name === "src")?.value ?? "").trim();
823
+ if (src && authorPixelSize(width, height)) return tag;
824
+ QUOTED_ATTR.lastIndex = 0;
825
+ return tag.replace(
826
+ QUOTED_ATTR,
827
+ (full, name) => name.toLowerCase() === "width" || name.toLowerCase() === "height" ? "" : full
828
+ );
829
+ });
830
+ }
831
+ function sanitizeHtml(html, options) {
832
+ const preserveImageDimensions = !!options?.preserveImageDimensions;
833
+ const whiteList = preserveImageDimensions ? {
834
+ ...ALLOWED_ATTRIBUTES,
835
+ img: [...ALLOWED_ATTRIBUTES.img ?? [], "width", "height"]
836
+ } : ALLOWED_ATTRIBUTES;
791
837
  const cleaned = xss(html, {
792
- whiteList: ALLOWED_ATTRIBUTES,
838
+ whiteList,
793
839
  stripIgnoreTag: true,
794
840
  stripIgnoreTagBody: ["style"],
795
841
  css: false,
@@ -808,6 +854,9 @@ function sanitizeHtml(html) {
808
854
  if ((tag === "video" || tag === "audio") && ["src", "poster"].includes(name) && !/^https?:\/\//.test(decodedLower)) return "";
809
855
  if (tag === "audio" && name === "preload" && decodedLower !== "metadata" && decodedLower !== "none") return "";
810
856
  if (tag === "img" && ["dynsrc", "lowsrc"].includes(name)) return "";
857
+ if (tag === "img" && (name === "width" || name === "height")) {
858
+ if (!preserveImageDimensions || parsePixelDimension(decoded) == null) return "";
859
+ }
811
860
  if (tag === "span" && name === "class" && decoded.toLowerCase().trim() === "wr") return "";
812
861
  if (EMBED_SRC_DATA_ATTRS.has(name) && !isAllowedEmbedSrc(decoded)) return "";
813
862
  if (name === "data-href" && !isSafeNavValue(decoded)) return "";
@@ -817,10 +866,11 @@ function sanitizeHtml(html) {
817
866
  return void 0;
818
867
  }
819
868
  });
820
- return cleaned.replace(
869
+ const withoutBareSource = cleaned.replace(
821
870
  /<source\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi,
822
871
  (t) => /\btype\s*=\s*["'](?:image\/avif|image\/webp)["']/i.test(t) ? t : ""
823
872
  );
873
+ return preserveImageDimensions ? enforceImageDimensionPair(withoutBareSource) : withoutBareSource;
824
874
  }
825
875
 
826
876
  // src/methods/img.method.ts
@@ -848,9 +898,10 @@ function wrapInPicture(el, rawUrl) {
848
898
  picture.appendChild(webp);
849
899
  picture.appendChild(el);
850
900
  }
851
- function img(el, state, forApp = true) {
901
+ function img(el, state, forApp = true, renderOptions) {
852
902
  const src = el.getAttribute("src") || "";
853
903
  const decodedSrc = decodeImageSrc(src);
904
+ const reserved = renderOptions?.preserveImageDimensions ? authorPixelSize(el.getAttribute("width"), el.getAttribute("height")) : null;
854
905
  ["onerror", "dynsrc", "lowsrc", "width", "height"].forEach((attr) => el.removeAttribute(attr));
855
906
  const isInvalid = !src || decodedSrc.startsWith("javascript") || decodedSrc.startsWith("vbscript") || decodedSrc === "x";
856
907
  if (isInvalid) {
@@ -866,6 +917,10 @@ function img(el, state, forApp = true) {
866
917
  el.removeAttribute("sizes");
867
918
  return;
868
919
  }
920
+ if (reserved) {
921
+ el.setAttribute("width", reserved.width);
922
+ el.setAttribute("height", reserved.height);
923
+ }
869
924
  el.setAttribute("itemprop", "image");
870
925
  const avatarRoute = new RegExp(`^${trimTrailingSlash(getProxyBase()).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/u/[^/]+/avatar(?:/[a-z]+)?$`);
871
926
  const classTokens = (el.getAttribute("class") || "").split(/\s+/);
@@ -2034,7 +2089,7 @@ function traverse(node, forApp, depth = 0, state = { firstImageFound: false }, p
2034
2089
  text(child, forApp, renderOptions);
2035
2090
  }
2036
2091
  if (child.nodeName.toLowerCase() === "img") {
2037
- img(child, state, forApp);
2092
+ img(child, state, forApp, renderOptions);
2038
2093
  }
2039
2094
  if (child.nodeName.toLowerCase() === "p") {
2040
2095
  p(child);
@@ -2168,7 +2223,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2168
2223
  output = serializer.serializeToString(doc);
2169
2224
  } catch (error) {
2170
2225
  try {
2171
- const preSanitized = sanitizeHtml(output);
2226
+ const preSanitized = sanitizeHtml(output, renderOptions);
2172
2227
  const dom = htmlparser2.parseDocument(preSanitized, {
2173
2228
  // lenient options - don't throw on malformed HTML
2174
2229
  lowerCaseTags: false,
@@ -2179,7 +2234,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2179
2234
  traverse(doc, forApp, 0, { firstImageFound: false }, parentDomain, seoContext, renderOptions);
2180
2235
  output = serializer.serializeToString(doc);
2181
2236
  } catch (fallbackError) {
2182
- output = sanitizeHtml(output || md.render(input));
2237
+ output = sanitizeHtml(output || md.render(input), renderOptions);
2183
2238
  }
2184
2239
  }
2185
2240
  if (forApp && output && entityPlaceholders.length > 0) {
@@ -2189,7 +2244,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2189
2244
  });
2190
2245
  }
2191
2246
  output = output.replace(/ xmlns="http:\/\/www.w3.org\/1999\/xhtml"/g, "").replace(/^<\?xml[^?]*\?>/, "").replace(/^<!DOCTYPE[^>]*>/i, "").replace(/<\/?html[^>]*>/g, "").replace(/<head[^>]*>[\s\S]*?<\/head>/g, "").replace('<body id="root">', "").replace("</body>", "").trim();
2192
- return sanitizeHtml(output);
2247
+ return sanitizeHtml(output, renderOptions);
2193
2248
  }
2194
2249
  var mdInstance = null;
2195
2250
  function getMd() {
@@ -2244,7 +2299,7 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
2244
2299
  logIfSlow(performance.now() - t02, `body_len=${obj.length}`);
2245
2300
  return res2;
2246
2301
  }
2247
- const key = `${makeEntryCacheKey(obj)}-md-${forApp ? "app" : "site"}-${parentDomain}${seoContext ? `-seo${seoContext.authorReputation ?? ""}-${seoContext.postPayout ?? ""}` : ""}${renderOptions?.embedVideosDirectly ? "-embed" : ""}${renderOptions?.inertAuthorAndTagChips ? "-inert" : ""}${renderOptions?.externalProfileBase ? "-ext" + renderOptions.externalProfileBase : ""}`;
2302
+ const key = `${makeEntryCacheKey(obj)}-md-${forApp ? "app" : "site"}-${parentDomain}${seoContext ? `-seo${seoContext.authorReputation ?? ""}-${seoContext.postPayout ?? ""}` : ""}${renderOptions?.embedVideosDirectly ? "-embed" : ""}${renderOptions?.inertAuthorAndTagChips ? "-inert" : ""}${renderOptions?.externalProfileBase ? "-ext" + renderOptions.externalProfileBase : ""}${renderOptions?.preserveImageDimensions ? "-imgdim" : ""}`;
2248
2303
  const item = entryMemoGet(key, obj.body);
2249
2304
  if (item !== MEMO_MISS) {
2250
2305
  return item;