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 | 5x 5x 5x 5x 5x 5x 2x 2x 1x 4x 15x 4x 11x 5x 1x 1x 5x 4x 4x 4x 2x 2x 2x 8x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 2x 1x | /**
* The site's Cloudinary account (the add-on on the `design-system-2-site`
* Heroku app), over the REST Upload and Admin APIs, so no SDK.
*
* File names are content hashes, so an asset never changes once uploaded:
* uploads use `overwrite: false` and rerunning one is a no-op.
*
* Docs: https://cloudinary.com/documentation/image_upload_api_reference_upload.md,
* https://cloudinary.com/documentation/admin_api and
* https://cloudinary.com/documentation/authentication_signatures
*/
import { createHash } from 'node:crypto';
import { HttpError, retryAfterMs, withRetry } from './zeroheight/http.js';
/** Cloudinary account of the site. */
export const CLOUDINARY_CLOUD = 'hl955tqfo';
/** Folder (and public id prefix) of the content images. */
export const CLOUDINARY_FOLDER = 'slds2-site/content';
/** Public URL prefix of the content images. */
export const IMAGE_URL_PREFIX = `https://res.cloudinary.com/${CLOUDINARY_CLOUD}/image/upload/${CLOUDINARY_FOLDER}/`;
/** Admin API caps: resources per list page, public ids per delete. */
const LIST_PAGE_SIZE = 500;
const DELETE_BATCH = 100;
const CLOUDINARY_URL_RE = /^cloudinary:\/\/([^:]+):([^@]+)@(.+)$/;
/**
* `cloudinary://<key>:<secret>@<cloud>`, as Heroku sets `CLOUDINARY_URL`.
* @param {string} url
*/
export function parseCloudinaryUrl(url) {
const m = url.trim().match(CLOUDINARY_URL_RE);
if (!m) throw new Error('CLOUDINARY_URL is not a cloudinary://key:secret@cloud URL');
return { apiKey: m[1], apiSecret: m[2], cloudName: m[3] };
}
/**
* SHA-256 of the params sorted by name, joined as `k=v&…`, with the secret
* appended (Cloudinary accepts SHA-1 or SHA-256; the SDKs' `signature_algorithm`).
* @param {Record<string, string>} params every param sent except `file`, `api_key`, `resource_type`, `cloud_name`
* @param {string} secret
*/
export function signParams(params, secret) {
const payload = Object.keys(params)
.sort()
.map((k) => `${k}=${params[k]}`)
.join('&');
return createHash('sha256').update(payload + secret).digest('hex');
}
/**
* `abc.png` -> public id `slds2-site/content/abc`. Cloudinary keeps the format
* apart from the public id; the delivery URL puts the extension back.
* @param {string} name
*/
export const publicId = (name) => `${CLOUDINARY_FOLDER}/${name.replace(/\.[^.]+$/, '')}`;
/**
* @param {Response} res
* @param {string} what
*/
async function throwIfFailed(res, what) {
if (res.ok) return;
const detail = await res.json().catch(() => null);
const message = `Cloudinary ${what}: HTTP ${res.status} ${detail?.error?.message ?? ''}`.trim();
throw new HttpError(message, res.status, retryAfterMs(res));
}
/**
* @param {{
* cloudName: string,
* apiKey: string,
* apiSecret: string,
* fetchImpl?: typeof fetch,
* now?: () => number,
* }} opts
*/
export function createCloudinaryClient({ cloudName, apiKey, apiSecret, fetchImpl = fetch, now = Date.now }) {
const base = `https://api.cloudinary.com/v1_1/${cloudName}`;
const auth = { Authorization: `Basic ${Buffer.from(`${apiKey}:${apiSecret}`).toString('base64')}` };
return {
/**
* @param {string} name content-hash file name, e.g. `0d4e5b9b2be33178.jpg`
* @param {Buffer} data
*/
upload: (name, data) =>
withRetry(async () => {
/** @type {Record<string, string>} */
const params = {
asset_folder: CLOUDINARY_FOLDER,
overwrite: 'false',
public_id: publicId(name),
timestamp: String(Math.floor(now() / 1000)),
};
const body = new FormData();
for (const [k, v] of Object.entries(params)) body.append(k, v);
body.append('api_key', apiKey);
body.append('signature', signParams(params, apiSecret));
body.append('file', new Blob([new Uint8Array(data)]), name);
const res = await fetchImpl(`${base}/image/upload`, { method: 'POST', body });
await throwIfFailed(res, `upload ${name}`);
}),
/**
* File names (`<hash>.<ext>`) of every asset in the content folder.
* @returns {Promise<string[]>}
*/
async list() {
/** @type {string[]} */
const names = [];
let cursor = '';
do {
const qs = new URLSearchParams({ prefix: `${CLOUDINARY_FOLDER}/`, max_results: String(LIST_PAGE_SIZE) });
if (cursor) qs.set('next_cursor', cursor);
const body = await withRetry(async () => {
const res = await fetchImpl(`${base}/resources/image/upload?${qs}`, { headers: auth });
await throwIfFailed(res, 'list');
return res.json();
});
for (const r of body.resources ?? []) names.push(`${r.public_id.split('/').pop()}.${r.format}`);
cursor = body.next_cursor ?? '';
} while (cursor);
return names;
},
/**
* Delete assets of the content folder by file name.
* @param {string[]} names
* @returns {Promise<string[]>} the names actually deleted
*/
async destroy(names) {
/** @type {string[]} */
const deleted = [];
for (let i = 0; i < names.length; i += DELETE_BATCH) {
const batch = names.slice(i, i + DELETE_BATCH);
const qs = new URLSearchParams(batch.map((n) => ['public_ids[]', publicId(n)]));
const body = await withRetry(async () => {
const res = await fetchImpl(`${base}/resources/image/upload?${qs}`, { method: 'DELETE', headers: auth });
await throwIfFailed(res, 'delete');
return res.json();
});
for (const n of batch) if (body.deleted?.[publicId(n)] === 'deleted') deleted.push(n);
}
return deleted;
},
};
}
|