@ecency/render-helper 2.5.38 → 2.5.40

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
  /**
@@ -65,7 +65,7 @@ var INTERNAL_POST_TAG_REGEX = /^(.+?)\/(@[\w.\d-]+)\/(.*)$/i;
65
65
  var INTERNAL_POST_REGEX = /^\/(@[\w.\d-]+)\/(.*)$/i;
66
66
  var CUSTOM_COMMUNITY_REGEX = /^https?:\/\/(.*)\/c\/(hive-\d+)(.*)/i;
67
67
  var YOUTUBE_REGEX = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|shorts\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i;
68
- var YOUTUBE_EMBED_REGEX = /^(https?:)?\/\/www\.youtube\.com\/(embed|shorts)\/.*/i;
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
71
  var BITCHUTE_REGEX = /^(?:https?:\/\/)?(?:www\.)?bitchute\.com\/(?:video|embed)\/([a-z0-9]+)/i;
@@ -419,8 +419,31 @@ function createDoc(html) {
419
419
  return null;
420
420
  }
421
421
  }
422
+ function hashBody(body) {
423
+ const s = typeof body === "string" ? body : "";
424
+ let h = 2166136261;
425
+ for (let i = 0; i < s.length; i++) {
426
+ h ^= s.charCodeAt(i);
427
+ h = Math.imul(h, 16777619);
428
+ }
429
+ return `${s.length}.${(h >>> 0).toString(36)}`;
430
+ }
431
+ var bodyHashes = /* @__PURE__ */ new WeakMap();
432
+ function entryBodyHash(entry) {
433
+ const body = entry.body;
434
+ if (typeof body !== "string" || typeof entry !== "object" || entry === null) {
435
+ return hashBody(body);
436
+ }
437
+ const stored = bodyHashes.get(entry);
438
+ if (stored && stored.body === body) {
439
+ return stored.hash;
440
+ }
441
+ const hash = hashBody(body);
442
+ bodyHashes.set(entry, { body, hash });
443
+ return hash;
444
+ }
422
445
  function makeEntryCacheKey(entry) {
423
- return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}`;
446
+ return `${entry.author}-${entry.permlink}-${entry.last_update}-${entry.updated}-${entryBodyHash(entry)}`;
424
447
  }
425
448
  function stripHtmlTags(s) {
426
449
  const n = s.length;
@@ -512,6 +535,10 @@ function extractYtStartTime(url) {
512
535
  return "";
513
536
  }
514
537
  }
538
+ function youtubeVideoLinkClass(matchedUrl) {
539
+ const base = "markdown-video-link markdown-video-link-youtube";
540
+ return /youtube\.com\/shorts\//i.test(matchedUrl) ? `${base} markdown-video-link-youtube-portrait` : base;
541
+ }
515
542
  function sanitizePermlink(permlink) {
516
543
  if (!permlink || typeof permlink !== "string") {
517
544
  return "";
@@ -746,6 +773,27 @@ function buildPictureSources(rawUrl) {
746
773
  return { avif, webp };
747
774
  }
748
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
+
749
797
  // src/methods/sanitize-html.method.ts
750
798
  var EMBED_SRC_DATA_ATTRS = /* @__PURE__ */ new Set(["data-embed-src", "data-video-href"]);
751
799
  var isSafeNavValue = (value) => {
@@ -760,9 +808,34 @@ var isProxyPSrcset = (srcset) => {
760
808
  const candidates = srcset.split(",").map((c) => c.trim().split(/\s+/)[0]).filter(Boolean);
761
809
  return candidates.length > 0 && candidates.every((url) => url.startsWith(`${base}/p/`));
762
810
  };
763
- 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;
764
837
  const cleaned = xss(html, {
765
- whiteList: ALLOWED_ATTRIBUTES,
838
+ whiteList,
766
839
  stripIgnoreTag: true,
767
840
  stripIgnoreTagBody: ["style"],
768
841
  css: false,
@@ -781,6 +854,9 @@ function sanitizeHtml(html) {
781
854
  if ((tag === "video" || tag === "audio") && ["src", "poster"].includes(name) && !/^https?:\/\//.test(decodedLower)) return "";
782
855
  if (tag === "audio" && name === "preload" && decodedLower !== "metadata" && decodedLower !== "none") return "";
783
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
+ }
784
860
  if (tag === "span" && name === "class" && decoded.toLowerCase().trim() === "wr") return "";
785
861
  if (EMBED_SRC_DATA_ATTRS.has(name) && !isAllowedEmbedSrc(decoded)) return "";
786
862
  if (name === "data-href" && !isSafeNavValue(decoded)) return "";
@@ -790,10 +866,11 @@ function sanitizeHtml(html) {
790
866
  return void 0;
791
867
  }
792
868
  });
793
- return cleaned.replace(
869
+ const withoutBareSource = cleaned.replace(
794
870
  /<source\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi,
795
871
  (t) => /\btype\s*=\s*["'](?:image\/avif|image\/webp)["']/i.test(t) ? t : ""
796
872
  );
873
+ return preserveImageDimensions ? enforceImageDimensionPair(withoutBareSource) : withoutBareSource;
797
874
  }
798
875
 
799
876
  // src/methods/img.method.ts
@@ -821,9 +898,10 @@ function wrapInPicture(el, rawUrl) {
821
898
  picture.appendChild(webp);
822
899
  picture.appendChild(el);
823
900
  }
824
- function img(el, state, forApp = true) {
901
+ function img(el, state, forApp = true, renderOptions) {
825
902
  const src = el.getAttribute("src") || "";
826
903
  const decodedSrc = decodeImageSrc(src);
904
+ const reserved = renderOptions?.preserveImageDimensions ? authorPixelSize(el.getAttribute("width"), el.getAttribute("height")) : null;
827
905
  ["onerror", "dynsrc", "lowsrc", "width", "height"].forEach((attr) => el.removeAttribute(attr));
828
906
  const isInvalid = !src || decodedSrc.startsWith("javascript") || decodedSrc.startsWith("vbscript") || decodedSrc === "x";
829
907
  if (isInvalid) {
@@ -839,6 +917,10 @@ function img(el, state, forApp = true) {
839
917
  el.removeAttribute("sizes");
840
918
  return;
841
919
  }
920
+ if (reserved) {
921
+ el.setAttribute("width", reserved.width);
922
+ el.setAttribute("height", reserved.height);
923
+ }
842
924
  el.setAttribute("itemprop", "image");
843
925
  const avatarRoute = new RegExp(`^${trimTrailingSlash(getProxyBase()).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/u/[^/]+/avatar(?:/[a-z]+)?$`);
844
926
  const classTokens = (el.getAttribute("class") || "").split(/\s+/);
@@ -1313,7 +1395,8 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1313
1395
  }
1314
1396
  let match = href.match(YOUTUBE_REGEX);
1315
1397
  if (match && match[1] && el.textContent.trim() === href) {
1316
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
1398
+ const videoClass = youtubeVideoLinkClass(match[0]);
1399
+ el.setAttribute("class", videoClass);
1317
1400
  el.removeAttribute("href");
1318
1401
  const vid = match[1];
1319
1402
  const thumbnail = proxifyImageSrc(`https://img.youtube.com/vi/${vid.split("?")[0]}/hqdefault.jpg`, 0, 0, "match");
@@ -1338,7 +1421,7 @@ function a(el, forApp, parentDomain = "ecency.com", seoContext, renderOptions) {
1338
1421
  iframe2.setAttribute("allowfullscreen", "");
1339
1422
  wrapper.appendChild(iframe2);
1340
1423
  el.appendChild(wrapper);
1341
- el.setAttribute("class", "markdown-video-link markdown-video-link-youtube er-youtube");
1424
+ el.setAttribute("class", `${videoClass} er-youtube`);
1342
1425
  } else {
1343
1426
  const thumbImg = el.ownerDocument.createElement("img");
1344
1427
  thumbImg.setAttribute("class", "no-replace video-thumbnail");
@@ -1610,8 +1693,20 @@ function iframe(el, parentDomain = "ecency.com", forApp = false, renderOptions)
1610
1693
  el.parentNode.removeChild(el);
1611
1694
  return;
1612
1695
  }
1613
- if (src.match(YOUTUBE_EMBED_REGEX)) {
1614
- el.setAttribute("src", stripQueryString(src));
1696
+ const ytMatch = src.match(YOUTUBE_EMBED_REGEX);
1697
+ if (ytMatch) {
1698
+ let stripped = stripQueryString(src);
1699
+ if (!/^(https?:)?\/\/www\./i.test(stripped)) {
1700
+ stripped = stripped.replace(/^(https?:)?\/\/(?:m\.)?youtube\.com/i, "https://www.youtube.com");
1701
+ }
1702
+ el.setAttribute("src", stripped);
1703
+ if (ytMatch[2].toLowerCase() === "shorts") {
1704
+ const shortId = stripped.match(/\/shorts\/([A-Za-z0-9_-]{11})\/?(?=[?#]|$)/i);
1705
+ if (shortId) {
1706
+ el.setAttribute("src", `https://www.youtube.com/embed/${shortId[1]}`);
1707
+ el.setAttribute("class", "portrait-embed");
1708
+ }
1709
+ }
1615
1710
  return;
1616
1711
  }
1617
1712
  if (src.match(BITCHUTE_REGEX)) {
@@ -1935,7 +2030,7 @@ function text(node, forApp, renderOptions) {
1935
2030
  const startTime = extractYtStartTime(nodeValue);
1936
2031
  const container = node.ownerDocument.createElement("p");
1937
2032
  const anchor = node.ownerDocument.createElement("a");
1938
- anchor.setAttribute("class", "markdown-video-link markdown-video-link-youtube");
2033
+ anchor.setAttribute("class", youtubeVideoLinkClass(e[0]));
1939
2034
  anchor.setAttribute("data-embed-src", embedSrc);
1940
2035
  anchor.setAttribute("data-youtube", vid);
1941
2036
  if (startTime) {
@@ -1994,7 +2089,7 @@ function traverse(node, forApp, depth = 0, state = { firstImageFound: false }, p
1994
2089
  text(child, forApp, renderOptions);
1995
2090
  }
1996
2091
  if (child.nodeName.toLowerCase() === "img") {
1997
- img(child, state, forApp);
2092
+ img(child, state, forApp, renderOptions);
1998
2093
  }
1999
2094
  if (child.nodeName.toLowerCase() === "p") {
2000
2095
  p(child);
@@ -2128,7 +2223,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2128
2223
  output = serializer.serializeToString(doc);
2129
2224
  } catch (error) {
2130
2225
  try {
2131
- const preSanitized = sanitizeHtml(output);
2226
+ const preSanitized = sanitizeHtml(output, renderOptions);
2132
2227
  const dom = htmlparser2.parseDocument(preSanitized, {
2133
2228
  // lenient options - don't throw on malformed HTML
2134
2229
  lowerCaseTags: false,
@@ -2139,7 +2234,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2139
2234
  traverse(doc, forApp, 0, { firstImageFound: false }, parentDomain, seoContext, renderOptions);
2140
2235
  output = serializer.serializeToString(doc);
2141
2236
  } catch (fallbackError) {
2142
- output = sanitizeHtml(output || md.render(input));
2237
+ output = sanitizeHtml(output || md.render(input), renderOptions);
2143
2238
  }
2144
2239
  }
2145
2240
  if (forApp && output && entityPlaceholders.length > 0) {
@@ -2149,7 +2244,7 @@ function markdownToHTML(input, forApp, parentDomain = "ecency.com", seoContext,
2149
2244
  });
2150
2245
  }
2151
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();
2152
- return sanitizeHtml(output);
2247
+ return sanitizeHtml(output, renderOptions);
2153
2248
  }
2154
2249
  var mdInstance = null;
2155
2250
  function getMd() {
@@ -2171,11 +2266,16 @@ var cache = new LRUCache({ max: 500 });
2171
2266
  function setCacheSize(size) {
2172
2267
  cache = new LRUCache({ max: size });
2173
2268
  }
2174
- function cacheGet(key) {
2175
- return cache.get(key);
2269
+ var MEMO_MISS = /* @__PURE__ */ Symbol("memo-miss");
2270
+ function entryMemoGet(key, body, meta) {
2271
+ const slot = cache.get(key);
2272
+ if (slot === void 0 || slot.body !== body || slot.meta !== meta) {
2273
+ return MEMO_MISS;
2274
+ }
2275
+ return slot.value;
2176
2276
  }
2177
- function cacheSet(key, value) {
2178
- cache.set(key, value);
2277
+ function entryMemoSet(key, body, meta, value) {
2278
+ cache.set(key, { body, meta, value });
2179
2279
  }
2180
2280
 
2181
2281
  // src/markdown-2-html.ts
@@ -2199,9 +2299,9 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
2199
2299
  logIfSlow(performance.now() - t02, `body_len=${obj.length}`);
2200
2300
  return res2;
2201
2301
  }
2202
- 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 : ""}`;
2203
- const item = cacheGet(key);
2204
- if (item) {
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" : ""}`;
2303
+ const item = entryMemoGet(key, obj.body);
2304
+ if (item !== MEMO_MISS) {
2205
2305
  return item;
2206
2306
  }
2207
2307
  const cleanBody = cleanReply(obj.body);
@@ -2211,7 +2311,7 @@ function markdown2Html(obj, forApp = true, _webp = false, parentDomain = "ecency
2211
2311
  performance.now() - t0,
2212
2312
  `author=@${obj.author} permlink=${obj.permlink} body_len=${obj.body?.length ?? 0}`
2213
2313
  );
2214
- cacheSet(key, res);
2314
+ entryMemoSet(key, obj.body, void 0, res);
2215
2315
  return res;
2216
2316
  }
2217
2317
 
@@ -2719,6 +2819,23 @@ function firstMetaUrl(value) {
2719
2819
  }
2720
2820
  return void 0;
2721
2821
  }
2822
+ function metaFingerprint(jsonMetadata) {
2823
+ let meta;
2824
+ if (typeof jsonMetadata === "object") {
2825
+ meta = jsonMetadata;
2826
+ } else {
2827
+ try {
2828
+ meta = JSON.parse(jsonMetadata);
2829
+ } catch {
2830
+ meta = null;
2831
+ }
2832
+ }
2833
+ try {
2834
+ return JSON.stringify([meta?.thumbnails, meta?.image]);
2835
+ } catch {
2836
+ return {};
2837
+ }
2838
+ }
2722
2839
  function proxifyFound(src, width, height, format) {
2723
2840
  return proxifyImageSrc(decodeEntities(src), width, height, format);
2724
2841
  }
@@ -2841,12 +2958,13 @@ function catchPostImage(obj, width = 0, height = 0, format = "match", options =
2841
2958
  return null;
2842
2959
  }
2843
2960
  const key = `${makeEntryCacheKey(obj)}-${width}x${height}-${format}${fastMode ? "-fast" : ""}`;
2844
- const item = cacheGet(key);
2845
- if (item !== void 0) {
2961
+ const meta = metaFingerprint(obj.json_metadata);
2962
+ const item = entryMemoGet(key, obj.body, meta);
2963
+ if (item !== MEMO_MISS) {
2846
2964
  return item;
2847
2965
  }
2848
2966
  const res = getImage(obj, width, height, format, fastMode);
2849
- cacheSet(key, res);
2967
+ entryMemoSet(key, obj.body, meta, res);
2850
2968
  return res;
2851
2969
  }
2852
2970
  var summaryRenderer = new Remarkable({
@@ -2931,12 +3049,12 @@ function getPostBodySummary(obj, length, platform) {
2931
3049
  return postBodySummary(obj, normalizedLength, normalizedPlatform);
2932
3050
  }
2933
3051
  const key = `${makeEntryCacheKey(obj)}-sum-${normalizedLength}-${normalizedPlatform}`;
2934
- const item = cacheGet(key);
2935
- if (item) {
3052
+ const item = entryMemoGet(key, obj.body);
3053
+ if (item !== MEMO_MISS) {
2936
3054
  return item;
2937
3055
  }
2938
3056
  const res = postBodySummary(obj.body, normalizedLength, normalizedPlatform);
2939
- cacheSet(key, res);
3057
+ entryMemoSet(key, obj.body, void 0, res);
2940
3058
  return res;
2941
3059
  }
2942
3060