All files / packages/design-system-2-site/src/lib/zeroheight images.js

99.08% Statements 108/109
98.18% Branches 54/55
100% Functions 18/18
98.85% Lines 86/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                                            3x                 3x     3x 3x   3x       3x     3x                     3x                         38x 38x 15x 3x                 44x 44x   3x   41x   39x 4x     35x 3x             18x                 18x 18x 19x 19x 19x 2x 2x                     103x 103x 53x                 31x 31x 31x 31x               38x 38x 36x                   29x 22x 22x   29x                                                                         18x   18x   18x 18x 18x   18x     18x 28x 28x 27x 27x 27x 27x 27x 27x       18x 5x 5x 1x 1x   4x       18x 18x 35x 35x 32x     32x 18x 12x 14x 2x 2x   12x 12x   1x         32x 18x 18x 18x 17x 16x 18x   2x       18x    
/**
 * Host content images on the site's Cloudinary account: download each image
 * once, name it by the sha256 of its bytes, upload it, and rewrite refs to
 * `IMAGE_URL_PREFIX`.
 *
 * Sources:
 *   - `zeroheight://image/<pageId>/<hash>` from MCP `get-page` (bytes via
 *     `get-page-asset`; the URI hash isn't the bytes' sha256, and the page id
 *     changes per release, so the index is keyed by the URI hash alone)
 *   - remote images on hosts that go away with Zeroheight or the POC
 *
 * `zeroheight-images.json` maps each source key to its file so reruns skip
 * images already uploaded. `refresh` downloads them all again, to catch an
 * image replaced in Zeroheight under the same ref, or an asset gone from
 * Cloudinary.
 */
 
import { createHash } from 'node:crypto';
import { IMAGE_URL_PREFIX } from '../cloudinary.js';
import { mapPool } from './http.js';
 
/** Hosts whose images must be rehosted (they go away with Zeroheight or the POC). */
export const REMOTE_IMAGE_HOSTS = [
  'zeroheight-uploads.s3.eu-west-1.amazonaws.com',
  'zeroheight-user-uploads.s3.eu-west-1.amazonaws.com',
  'res.cloudinary.com',
  'www.lightningdesignsystem.com',
  'sfdc-map.surge.sh',
];
 
/** Cloudinary account of the POC (`ldss-cms`). */
const POC_CLOUDINARY_ACCOUNT = 'hqglkpaqj';
 
/** Parallel remote downloads. */
const DOWNLOAD_CONCURRENCY = 4;
const MAX_REDIRECTS = 3;
 
const ZH_IMAGE_RE = /zeroheight:\/\/image\/\d+\/([0-9a-f]{64})/g;
// `[` and `]` end a URL too, so `[url](url)` yields two refs, not one. So does
// `&quot;` (a URL inside an escaped directive attribute), but not a bare `&`:
// signed URLs have query strings.
const REMOTE_URL_RE = /https?:\/\/(?:(?!&quot;)[^\s()[\]"'<>])+/g;
 
/** @type {Record<string, string>} */
const EXTENSIONS = {
  'image/png': '.png',
  'image/jpeg': '.jpg',
  'image/gif': '.gif',
  'image/svg+xml': '.svg',
  'image/webp': '.webp',
  'video/mp4': '.mp4',
  'application/pdf': '.pdf',
};
 
/** Leading bytes per type, for uploads served as a generic `octet-stream`. */
const SIGNATURES = [
  { type: 'image/png', bytes: [0x89, 0x50, 0x4e, 0x47] },
  { type: 'image/jpeg', bytes: [0xff, 0xd8, 0xff] },
  { type: 'image/gif', bytes: [0x47, 0x49, 0x46, 0x38] },
  { type: 'application/pdf', bytes: [0x25, 0x50, 0x44, 0x46] },
];
 
/**
 * The declared type, or the one the bytes show when it's a generic `octet-stream`.
 * @param {Buffer} data
 * @param {string} mimeType
 */
export function detectType(data, mimeType) {
  const declared = mimeType.split(';')[0].trim();
  if (!declared.endsWith('/octet-stream')) return declared;
  const match = SIGNATURES.find((s) => s.bytes.every((b, i) => data[i] === b));
  return match?.type ?? declared;
}
 
/**
 * @param {string} url
 * @returns {boolean}
 */
export function isRemoteImageUrl(url) {
  let parsed;
  try {
    parsed = new URL(url);
  } catch {
    return false;
  }
  if (!REMOTE_IMAGE_HOSTS.includes(parsed.hostname)) return false;
  // On lightningdesignsystem.com only uploaded assets count; pages are links.
  if (parsed.hostname === 'www.lightningdesignsystem.com') {
    return /^\/(uploads|images\/zhapp)\//.test(parsed.pathname);
  }
  // Only the POC's Cloudinary account goes away; the SLDS one stays remote.
  if (parsed.hostname === 'res.cloudinary.com') return parsed.pathname.startsWith(`/${POC_CLOUDINARY_ACCOUNT}/`);
  return true;
}
 
/**
 * Directive attributes escape `&` as `&amp;`; undo it so signed URLs stay byte-exact.
 * @param {string} ref
 */
export const decodeRef = (ref) => ref.replace(/&amp;/g, '&');
 
/**
 * Fetch `url`, following redirects by hand so every hop stays on an allowlisted host.
 * @param {typeof fetch} fetchImpl
 * @param {string} url
 * @returns {Promise<Response>}
 */
async function fetchAllowed(fetchImpl, url) {
  let target = url;
  for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
    const res = await fetchImpl(target, { redirect: 'manual' });
    const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
    if (!location) return res;
    target = new URL(location, target).href;
    if (!isRemoteImageUrl(target)) throw new Error('Redirect to a host that is not allowlisted');
  }
  throw new Error('Too many redirects');
}
 
/**
 * Index key for a source: the Zeroheight image hash, or the URL without its
 * (signed, expiring) query string.
 * @param {string} ref
 */
export function sourceKey(ref) {
  const zh = ref.match(/^zeroheight:\/\/image\/\d+\/([0-9a-f]{64})$/);
  if (zh) return `zh:${zh[1]}`;
  return ref.split('?')[0];
}
 
/**
 * Every image ref in a markdown string that needs rehosting.
 * @param {string} md
 * @returns {string[]} unique refs in document order
 */
export function collectImageRefs(md) {
  const refs = new Set();
  for (const m of md.matchAll(ZH_IMAGE_RE)) refs.add(m[0]);
  for (const m of md.matchAll(REMOTE_URL_RE)) if (isRemoteImageUrl(m[0])) refs.add(m[0]);
  return [...refs];
}
 
/**
 * @param {Buffer} data
 * @param {string} mimeType
 */
export function imageFileName(data, mimeType) {
  const ext = EXTENSIONS[detectType(data, mimeType)];
  if (!ext) throw new Error(`Unsupported image type: ${mimeType}`);
  return `${createHash('sha256').update(data).digest('hex').slice(0, 16)}${ext}`;
}
 
/**
 * Replace every resolved ref with its hosted URL.
 * @param {string} md
 * @param {Map<string, string>} files ref -> file name
 */
export function rewriteImageRefs(md, files) {
  /** @param {string} ref */
  const swap = (ref) => {
    const file = files.get(ref);
    return file ? `${IMAGE_URL_PREFIX}${file}` : ref;
  };
  return md.replace(ZH_IMAGE_RE, swap).replace(REMOTE_URL_RE, (url) => (isRemoteImageUrl(url) ? swap(url) : url));
}
 
/**
 * Download every ref not already in the index (every ref with `refresh`) and
 * store it (upload it). With `refresh`, every download is stored again, since
 * the index can list an asset gone from Cloudinary; a ref that fails to
 * download keeps its current file and is reported in `kept`.
 * @param {{
 *   refs: string[],
 *   index: Record<string, string>,
 *   getPageAssets: (uris: string[]) => Promise<import('./mcp-client.js').AssetResult[]>,
 *   fetchImpl?: typeof fetch,
 *   hasFile: (name: string) => boolean,
 *   writeFile: (name: string, data: Buffer) => void | Promise<void>,
 *   batchSize?: number,
 *   refresh?: boolean,
 * }} opts
 * @returns {Promise<{
 *   files: Map<string, string>,
 *   downloaded: number,
 *   changed: number,
 *   failed: { ref: string, error: string }[],
 *   kept: { ref: string, error: string }[],
 * }>} `changed`: refs now pointing to a different file
 */
export async function resolveImages({
  refs,
  index,
  getPageAssets,
  fetchImpl = fetch,
  hasFile,
  writeFile,
  batchSize = 10,
  refresh = false,
}) {
  /** @type {Map<string, string>} */
  const files = new Map();
  /** @type {{ ref: string, error: string }[]} */
  const failed = [];
  /** @type {{ ref: string, error: string }[]} */
  const kept = [];
  let downloaded = 0;
  let changed = 0;
  /** Files stored in this run (two refs can share one). */
  const stored = new Set();
 
  /** @param {string} ref @param {Buffer} data @param {string} mimeType */
  const store = async (ref, data, mimeType) => {
    const name = imageFileName(data, mimeType);
    if (!stored.has(name) && (refresh || !hasFile(name))) await writeFile(name, data);
    stored.add(name);
    const known = index[sourceKey(ref)];
    if (known && known !== name) changed++;
    index[sourceKey(ref)] = name;
    files.set(ref, name);
    downloaded++;
  };
 
  /** @param {string} ref @param {string} error */
  const fail = (ref, error) => {
    const known = index[sourceKey(ref)];
    if (refresh && known) {
      files.set(ref, known);
      kept.push({ ref, error });
    } else {
      failed.push({ ref, error });
    }
  };
 
  const missing = [];
  for (const ref of refs) {
    const known = index[sourceKey(ref)];
    if (!refresh && known && hasFile(known)) files.set(ref, known);
    else missing.push(ref);
  }
 
  const zhRefs = missing.filter((r) => r.startsWith('zeroheight://'));
  for (let i = 0; i < zhRefs.length; i += batchSize) {
    for (const result of await getPageAssets(zhRefs.slice(i, i + batchSize))) {
      if ('error' in result) {
        fail(result.uri, result.error);
        continue;
      }
      try {
        await store(result.uri, result.data, result.mimeType);
      } catch (err) {
        fail(result.uri, /** @type {Error} */ (err).message);
      }
    }
  }
 
  const remoteRefs = missing.filter((r) => !r.startsWith('zeroheight://'));
  await mapPool(remoteRefs, DOWNLOAD_CONCURRENCY, async (ref) => {
    try {
      const res = await fetchAllowed(fetchImpl, decodeRef(ref));
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const mimeType = res.headers.get('content-type') ?? '';
      await store(ref, Buffer.from(await res.arrayBuffer()), mimeType);
    } catch (err) {
      fail(ref, /** @type {Error} */ (err).message);
    }
  });
 
  return { files, downloaded, changed, failed, kept };
}