feat(expand): P0-P3 素材扩库批次(发现器 + Google Fonts + Poly Haven + Noto Emoji 3D)

- P0: scripts/discover-sources.js 四通道候选发现,产出 candidates.json / registry.json

- P1: build-posters 新增 fontsource 适配器,接入 Google Fonts 2766 个 woff2

- P2: 新增 polyhaven 适配器,接入 Poly Haven CC0 纹理 238 张

- P3: build-icons 新增 gh-raster listPath(Git Tree 逐级下钻),接入 Noto Emoji 3D 3797 个 PNG

- 修复: GitHub Contents API 不支持目录分页导致重复/截断,改为 Git Tree 下钻并按路径去重;audit-files.json 同步重建

- 判定 noto-emoji-2d / twemoji-png 与既有 Iconify 源同图重复,不予收录

- 基线: 图标 264 源/448,551;海报 69 源/5,366;版本联动 20261108a
This commit is contained in:
sgp
2026-11-08 01:46:52 +08:00
parent 5bcd5ab0f2
commit b10184bf94
6829 changed files with 30261 additions and 452 deletions
+181 -10
View File
@@ -682,32 +682,190 @@ async function downloadGhFiles(src) {
* 产物:PNG 落盘 js/data/sources/{id}/files/,图标 svg 为 <image href="..."> 引用
* (渲染时相对页面路径可直接显示;导出时由 HGB_IconLib.inlineRasters 内联为 data URI)
*/
async function fetchTreeWithRetry(url, tries) {
let last;
for (let i = 0; i < (tries || 3); i++) {
try {
return JSON.parse(await fetch(url, 0, {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json'
}));
} catch (e) {
last = e;
await new Promise(r => setTimeout(r, 1500 * (i + 1)));
}
}
throw last;
}
/**
* emoji 名称映射(emoji-datasource 的 unified → short_name)
* 用于把 Twemoji / Noto 的纯码点文件名(1f600 / emoji_u1f600)还原为可搜索的英文名(grinning)
*/
async function loadNameMap(url) {
const arr = JSON.parse(await fetch(url, 0, { 'User-Agent': 'drawlogo-build', Accept: 'application/json' }));
const map = new Map();
for (const e of arr) {
// short_names 里常混有 "+1" 这类符号名,优先取可读的字母名(如 thumbsup)
const names = (e.short_names && e.short_names.length ? e.short_names : [e.short_name]).filter(Boolean);
const name = names.find(n => /^[a-z][a-z0-9-]*$/i.test(n) && n.length >= 2) || names[0];
if (!name) continue;
for (const k of [e.unified, e.non_qualified]) {
if (k) map.set(String(k).toLowerCase().replace(/_/g, '-'), name);
}
}
return map;
}
const GITHUB_TOKEN = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '';
/**
* GitHub API 专用 fetch(返回 {status, headers, body},timeout 60s,和项目内 fetch 兼容)
* 解决原 fetch 遇到 403 直接 reject 拿不到 status/headers 的问题
*/
function fetchGithubRaw(url, extraHeaders) {
return new Promise((resolve, reject) => {
const headers = {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json',
...(GITHUB_TOKEN ? { Authorization: 'Bearer ' + GITHUB_TOKEN } : {}),
...(extraHeaders || {})
};
const req = https.get(url, { timeout: 120000, headers }, (res) => {
// 非 2xx 也要读完 body 才能 resolve(否则连接被占用)
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => resolve({
status: res.statusCode,
headers: res.headers,
body: Buffer.concat(chunks).toString('utf8')
}));
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(new Error('timeout ' + url)); });
});
}
async function githubWaitForReset() {
try {
const rl = await fetchGithubRaw('https://api.github.com/rate_limit');
const data = JSON.parse(rl.body);
const reset = data?.resources?.core?.reset || (Date.now() / 1000 + 60);
const remaining = data?.resources?.core?.remaining ?? '?';
const waitMs = Math.max(2000, Math.round((reset - Date.now() / 1000) * 1000) + 3000);
console.warn(` ⏳ GitHub 限流(remaining=${remaining}),等 ${(waitMs/1000).toFixed(0)}s 恢复…`);
await new Promise(r => setTimeout(r, waitMs));
} catch (e) {
console.warn(` ⏳ GitHub rate_limit 查询失败,等 60s…`);
await new Promise(r => setTimeout(r, 60000));
}
}
/**
* 目录列举(Git Tree API 逐级定位子目录)
* —— 为什么不用 Contents API 分页:GitHub Contents 对目录**不支持 page 参数**,
* 每次返回同一页 1000 条(noto-emoji 3D 目录 5700+ 文件会被截断 + 重复写入)。
* —— 为什么不用 git/trees?recursive=1:noto-emoji 整树 9MB / 60s+ 易超时。
* 方案:从分支逐级下钻 git/trees/{sha}(每层一次请求,返回全部条目、无 base64),
* 5 次小请求即可拿全子目录(支持上万文件);带 403 自动等 reset + token 支持。
*/
async function listGithubDir(src) {
const gh = src.gh;
const branch = src.ghBranch || 'main';
const segs = String(src.listPath).split('/').filter(Boolean);
async function api(url) {
let tries = 0;
while (true) {
tries++;
let resp;
try { resp = await fetchGithubRaw(url); }
catch (e) {
if (tries >= 5) throw e;
console.warn(` ⚠️ ${src.id}: 网络错误 ${e.message},等 ${1500 * tries}ms 重试 (${tries}/5)`);
await new Promise(r => setTimeout(r, 1500 * tries));
continue;
}
if (resp.status === 403) {
await githubWaitForReset();
if (tries >= 5) throw new Error(`${src.id}: rate limit keep hitting after 5 retries`);
continue;
}
if (resp.status === 404) return null;
if (resp.status !== 200) throw new Error(`GitHub ${resp.status} (${src.id}): ${resp.body.substring(0, 200)}`);
return JSON.parse(resp.body);
}
}
// 下钻到目标目录拿 sha(分支名本身可作为 tree sha)
let sha = encodeURIComponent(branch);
for (const seg of segs) {
const t = await api(`https://api.github.com/repos/${gh}/git/trees/${sha}`);
if (!t) return [];
const node = (t.tree || []).find(x => x.path === seg && x.type === 'tree');
if (!node) { console.warn(` ⚠️ ${src.id}: 路径不存在 ${segs.join('/')}`); return []; }
sha = node.sha;
}
const t = await api(`https://api.github.com/repos/${gh}/git/trees/${sha}`);
if (!t) return [];
const prefix = segs.join('/') + '/';
return (t.tree || [])
.filter(x => x.type === 'blob')
.map(x => ({ type: 'blob', path: prefix + x.path, size: x.size }));
}
async function downloadGhRaster(src) {
const branch = src.ghBranch || 'main';
const api = `https://api.github.com/repos/${src.gh}/git/trees/${branch}?recursive=1`;
const tree = JSON.parse(await fetch(api, 0, {
'User-Agent': 'drawlogo-build',
Accept: 'application/vnd.github+json'
}));
let entries;
if (src.listPath) {
entries = await listGithubDir(src);
} else {
const api = `https://api.github.com/repos/${src.gh}/git/trees/${branch}?recursive=1`;
const tree = await fetchTreeWithRetry(api);
if (tree.truncated) console.warn(` ⚠️ ${src.id}: GitHub 文件树被截断,可能漏掉部分素材`);
entries = tree.tree || [];
}
const re = new RegExp(src.pathRe);
let picked = (tree.tree || []).filter(e => e.type === 'blob' && re.test(e.path));
let picked = entries.filter(e => e.type === 'blob' && re.test(e.path));
if (src.exclude) {
const ex = new RegExp(src.exclude);
picked = picked.filter(e => !ex.test(e.path));
}
// 去重(按路径):防止列举接口重复返回导致同名图标被反复写入、数据文件膨胀
const seenPaths = new Set();
picked = picked.filter(e => (seenPaths.has(e.path) ? false : (seenPaths.add(e.path), true)));
const cap = Number(src.maxItems) > 0 ? Math.min(Number(src.maxItems), picked.length) : picked.length;
picked = picked.slice(0, cap);
const expected = picked.length;
const dir = path.join(process.cwd(), 'js/data/sources', src.id, 'files');
fs.mkdirSync(dir, { recursive: true });
const nameMap = src.nameMapUrl ? await loadNameMap(src.nameMapUrl) : null;
const usedNames = new Set();
const base = `https://cdn.jsdelivr.net/gh/${src.gh}@${branch}/`;
let fail = 0;
const results = await mapLimit(picked, 12, async (e) => {
// 文件名 slug → 图标名:去掉 _3d / _3d_default 后缀,下划线转连字符
const slug = path.basename(e.path, '.png')
.replace(/_3d(?:_default)?$/i, '')
.replace(/_/g, '-');
const raw = path.basename(e.path, '.png');
const code = raw.replace(/^emoji_u/i, '').replace(/_/g, '-').toLowerCase();
// 文件名 slug → 图标名:优先取 emoji 短名,其次去掉 _3d 后缀,最后退回码点
let slug;
if (nameMap) {
slug = nameMap.get(code);
if (!slug) {
// 肤色变体(1f44d-1f3fb)在名称表里没有独立条目 → 拆掉肤色修饰符后回退到基础名
const parts = code.split('-');
const tones = [];
while (parts.length && /^1f3f[b-f]$/.test(parts[parts.length - 1])) tones.unshift(parts.pop());
const baseName = tones.length ? nameMap.get(parts.join('-')) : null;
slug = baseName ? baseName + '-skin-tone-' + tones.join('-') : null;
}
if (!slug) slug = raw.replace(/_/g, '-');
} else {
slug = raw.replace(/_3d(?:_default)?$/i, '').replace(/_/g, '-');
}
slug = String(slug).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || code;
if (usedNames.has(slug)) slug = slug + '-' + code; // 肤色/变体共用短名时保留码点后缀,避免覆盖
usedNames.add(slug);
try {
const buf = await fetchBuffer(base + e.path.split('/').map(encodeURIComponent).join('/'));
if (!buf || buf.length < 500) throw new Error('empty');
@@ -983,7 +1141,11 @@ async function main() {
const srcDir = path.join(process.cwd(), 'js/data/sources');
fs.mkdirSync(srcDir, { recursive: true });
// 环境变量 ONLY_IDS 可限定只跑特定源(逗号分隔),调试用
const onlyIds = process.env.ONLY_IDS ? new Set(process.env.ONLY_IDS.split(',').map(s => s.trim())) : null;
for (const src of SOURCES) {
if (onlyIds && !onlyIds.has(src.id)) continue;
let icons = null, fail = 0, usedUrl = '';
// 批次校验统计:expected=官方索引数(iconify 源);badViewBox=非法 viewBox 数
let expCount = null, badViewBox = 0;
@@ -1143,6 +1305,15 @@ async function main() {
console.log(`✅ ${src.name}: ${icons.length} 个图标(${type},失败 ${fail})`);
}
// ONLY_IDS 调试模式:只写按源数据文件,绝不覆盖 builtin-icons.js / manifest(否则索引被裁成 2 源)
if (onlyIds) {
console.log(`\n🧪 ONLY_IDS 调试模式:只处理 ${Object.keys(out.sources).length} 个源,共 ${grand} 个图标`);
console.log(' → 已写入 js/data/sources/*.js,跳过索引与 manifest 重建(请稍后跑全量构建收口)');
const passN = verifyReport.length - verifyFailCount;
console.log(`🔍 批次校验:${passN}/${verifyReport.length} 源通过`);
return;
}
out.meta.total = grand;
out.meta.sources = Object.keys(out.sources).length;
+144
View File
@@ -315,6 +315,135 @@ async function downloadDirFiles(src) {
return { items, ok, fail };
}
/**
* Fontsource 字体(Google Fonts 全字族自动发现)
* 配置:{ format:'fontsource', subsets:['latin'], weights:[400,700], maxFamilies?, exclude? }
* 说明:构建时拉取 https://api.fontsource.org/v1/fonts,按协议白名单 + 子集过滤,
* 逐个从 jsDelivr 下载 woff2(体积小、浏览器可直用),新增字族无需改配置。
*/
const FONT_LICENSE_OK = /^(OFL-1\.1|Apache-2\.0|CC0-1\.0|Unlicense|MIT)$/i;
async function downloadFontsource(src) {
const fonts = JSON.parse(await fetchText('https://api.fontsource.org/v1/fonts'));
const subsets = Array.isArray(src.subsets) && src.subsets.length ? src.subsets : ['latin'];
const weights = Array.isArray(src.weights) && src.weights.length ? src.weights : [400, 700];
let list = fonts.filter(f =>
f && f.id && FONT_LICENSE_OK.test(f.license || '') &&
(f.type === 'google') &&
Array.isArray(f.subsets) && f.subsets.some(s => subsets.includes(s))
);
if (src.exclude) {
const re = new RegExp(src.exclude);
list = list.filter(f => !re.test(f.id));
}
list = list.slice().sort((a, b) => String(a.id).localeCompare(String(b.id)));
if (Number(src.maxFamilies) > 0) list = list.slice(0, Number(src.maxFamilies));
const targets = [];
for (const f of list) {
const subset = subsets.find(s => (f.subsets || []).includes(s)) || 'latin';
const have = Array.isArray(f.weights) ? f.weights : [];
let use = weights.filter(w => have.includes(w));
if (!use.length && have.length) {
// 没有 400/700 时退化为最接近的标准字重
const near = w => have.reduce((a, b) => Math.abs(b - w) < Math.abs(a - w) ? b : a, have[0]);
use = [...new Set([near(400), near(700)])];
}
if (!use.length) use = [400];
for (const w of use) targets.push({ id: f.id, subset, weight: w });
}
let done = 0;
const results = await mapLimit(targets, 16, async (t) => {
const url = `https://cdn.jsdelivr.net/npm/@fontsource/${t.id}/files/${t.id}-${t.subset}-${t.weight}-normal.woff2`;
try {
const buf = await fetchBuffer(url);
if (!buf || buf.length < 400 || buf.slice(0, 4).toString('latin1') !== 'wOF2') throw new Error('bad woff2');
done++;
if (done % 500 === 0) console.log(` …已下载 ${done}/${targets.length}`);
return { t, buf };
} catch (e) { return null; }
});
const items = [];
let ok = 0, fail = 0;
for (const r of results) {
if (!r) { fail++; continue; }
const name = `${r.t.id}-${r.t.weight}`;
const it = await buildItem(src, name, name + '.woff2', r.buf, null);
if (it) { items.push(it); ok++; } else fail++;
}
return { items, ok, fail, expected: targets.length };
}
/**
* Poly Haven 纹理(CC0 自动发现)
* 配置:{ format:'polyhaven', maxItems:240, res:'1k', imageFormat:'jpg', categories?:[...], exclude? }
* 说明:按分类轮转挑选,保证纹理多样性(不要同一类木纹刷屏)。
*/
async function downloadPolyhaven(src) {
const all = JSON.parse(await fetchText('https://api.polyhaven.com/assets?t=textures'));
const res = src.res || '1k';
const imgFmt = src.imageFormat || 'jpg';
let ids = Object.keys(all);
if (Array.isArray(src.categories) && src.categories.length) {
const want = new Set(src.categories);
ids = ids.filter(id => (all[id].categories || []).some(c => want.has(c)));
}
if (src.exclude) {
const re = new RegExp(src.exclude);
ids = ids.filter(id => !re.test(id));
}
ids.sort();
// 分类轮转择优:每轮从各分类各取一个,直到达到上限
const buckets = new Map();
for (const id of ids) {
const cats = (all[id].categories || []).filter(c => !c.startsWith('collection:'));
const key = cats[0] || 'other';
if (!buckets.has(key)) buckets.set(key, []);
buckets.get(key).push(id);
}
const picked = [];
const keys = [...buckets.keys()].sort();
let round = 0;
while (picked.length < (Number(src.maxItems) || 240)) {
let added = 0;
for (const k of keys) {
const arr = buckets.get(k);
if (round < arr.length) { picked.push(arr[round]); added++; }
if (picked.length >= (Number(src.maxItems) || 240)) break;
}
if (!added) break;
round++;
}
let done = 0;
const results = await mapLimit(picked, 8, async (id) => {
try {
const files = JSON.parse(await fetchText('https://api.polyhaven.com/files/' + id));
const diffuse = files.Diffuse || files.diffuse || files.albedo;
const variant = diffuse && (diffuse[res] || diffuse[Object.keys(diffuse)[0]]);
const url = variant && variant[imgFmt] && variant[imgFmt].url;
if (!url) throw new Error('no url');
const buf = await fetchBuffer(url);
if (!buf || buf.length < 2000) throw new Error('empty');
done++;
if (done % 40 === 0) console.log(` …已下载 ${done}/${picked.length}`);
return { id, url, buf };
} catch (e) { return null; }
});
const items = [];
let ok = 0, fail = 0;
for (const r of results) {
if (!r) { fail++; continue; }
const it = await buildItem(src, r.id, r.id + '.' + imgFmt, r.buf, classifyPoster(r.id));
if (it) { items.push(it); ok++; } else fail++;
}
return { items, ok, fail, expected: picked.length };
}
/**
* 本地源:读取 js/data/posters/{id}/files 下预先生成的素材(不联网)
* 用于从 CSS 提取的图案、渐变与配色 JSON 等无独立文件的开源资源
@@ -433,6 +562,11 @@ async function buildItem(src, name, filePath, buf, c) {
} catch (e) { return null; }
}
if (ext === '.woff2') {
if (buf.slice(0, 4).toString('latin1') !== 'wOF2') return null; // woff2 魔数校验
return saveBinary(src, base, filePath, buf, 'font/woff2', null);
}
// 字体及其它二进制:保存 + 引用
return saveBinary(src, base, filePath, buf, 'application/octet-stream', null);
}
@@ -535,6 +669,16 @@ async function main() {
const r = await readLocalFiles(src);
items = r.items; fail = r.fail; expected = r.ok + r.fail;
usedUrl = 'local';
} else if (src.format === 'fontsource') {
console.log(`发现 ${src.name}(Fontsource 自动扫描字族)…`);
const r = await downloadFontsource(src);
items = r.items; fail = r.fail; expected = r.expected;
usedUrl = 'cdn.jsdelivr.net/npm/@fontsource';
} else if (src.format === 'polyhaven') {
console.log(`发现 ${src.name}(Poly Haven CC0 纹理)…`);
const r = await downloadPolyhaven(src);
items = r.items; fail = r.fail; expected = r.expected;
usedUrl = 'polyhaven.com';
} else {
throw new Error(`不支持的 format: ${src.format}`);
}
+237 -139
View File
@@ -2,174 +2,272 @@
/**
* 画个标 · 素材源发现器
*
* 扫描 Iconify 官方集合清单,与本地已收录源对比,输出:
* - 可直接新增的独立源(协议合规、非别名)
* - 别名/子集(同库不同 id,避免重复收录)
* - 协议不合规(BY-NC / BY-SA / BY-ND / GPL)
* - 需人工判断(品牌/商标风险、协议不明)
* 目标:把「找新素材源」从人工探测变成一次可重复运行的扫描,输出候选清单供准入筛选。
*
* 数据来源(全部公开 API,无需鉴权):
* 1. Iconify https://api.iconify.design/collections —— 图标集合全集与差值
* 2. Fontsource https://api.fontsource.org/v1/fonts —— Google Fonts 全字族
* 3. Poly Haven https://api.polyhaven.com/assets?t=textures —— CC0 纹理
* 4. GitHub https://api.github.com/search/repositories —— 主题检索(限流 10 次/分)
*
* 产物:
* js/data/candidates.json 候选清单(按 score 降序)
* js/data/sources/registry.json 源注册表(active 全量快照 + rejected 排除记录)
*
* 用法:
* node scripts/discover-sources.js
* node scripts/discover-sources.js --json # 只输出 JSON
*
* 输出文件:output/source-candidates.json(不入库)
* node scripts/discover-sources.js # 扫描并写入上述两个文件
* node scripts/discover-sources.js --dry # 只打印摘要,不写文件
* node scripts/discover-sources.js --only=iconify,font,texture
*/
'use strict';
const fs = require('fs');
const path = require('path');
const https = require('https');
const ROOT = path.resolve(__dirname, '..');
const OUT_DIR = path.join(ROOT, 'output');
const SOURCES_FILE = path.join(ROOT, 'js', 'data', 'icon-sources.js');
const ICON_SRC = path.join(ROOT, 'js', 'data', 'icon-sources.js');
const POSTER_SRC = path.join(ROOT, 'js', 'data', 'poster-sources.js');
const OUT_CANDIDATES = path.join(ROOT, 'js', 'data', 'candidates.json');
const OUT_REGISTRY = path.join(ROOT, 'js', 'data', 'sources', 'registry.json');
/** 已知别名 / 子集:这些 Iconify id 与本地已有源是同一套图标,不应重复收录 */
const ALIAS = {
ph: 'phosphor',
bi: 'bootstrap',
bx: 'boxicons',
ri: 'remix',
'ant-design': 'antd',
'radix-icons': 'radix',
'game-icons': 'gameicons',
'heroicons-outline': 'heroicons',
'heroicons-solid': 'heroicons',
'tabler-flags': 'tabler',
fa: 'fontawesome',
'fa-solid': 'fontawesome',
'fa-regular': 'fontawesome',
'fa-brands': 'fontawesome',
'fa6-solid': 'fontawesome',
'fa6-regular': 'fontawesome',
'fa6-brands': 'fontawesome'
};
/* ---------------- 准入规则(与项目规则一致) ---------------- */
const LICENSE_OK = /^(MIT|ISC|Apache-2\.0|Apache 2\.0|OFL-1\.1|CC0(-1\.0)?|Unlicense|BSD-3-Clause|BSD-2-Clause|MPL-2\.0)$/i;
const LICENSE_BLOCK = /BY-SA|BY-NC|BY-ND|\bGPL\b|NonCommercial|非商业|禁止商用/i;
/** 已知品牌/商标风险集合(可收录但需标注,不建议用于 LOGO) */
const BRAND_RISK = new Set(['arcticons', 'wordpress', 'brandico', 'entypo-social', 'fa6-brands']);
/** 已知排除项(协议/可拉取性/同质重复),避免每轮重复踩坑 */
const REJECTED = [
{ id: 'undraw', kind: 'poster', reason: '自定义协议禁止 AI/机器学习训练,与 AI 海报生成冲突' },
{ id: 'open-doodles', kind: 'poster', reason: 'CC0 但托管控于 Dropbox/Webflow,无可用直链仓库' },
{ id: 'hero-patterns', kind: 'poster', reason: '仓库无 LICENSE 文件,合规风险' },
{ id: 'arcticons', kind: 'icon', reason: 'CC BY-SA 4.0 传染性协议,不可商用收录' },
{ id: 'openmoji', kind: 'icon', reason: 'CC BY-SA 4.0 传染性协议(已通过 iconify 收录的源需复查)' },
{ id: '3dicons', kind: 'icon', reason: '仓库是站点源码,无批量静态素材(仅 12 张示例图)' },
{ id: 'svgwave', kind: 'poster', reason: '运行时生成器,无静态 SVG 产物' },
{ id: 'inkjet', kind: 'poster', reason: '运行时生成器,无静态 SVG 产物' },
{ id: 'mrmrs-patterns', kind: 'poster', reason: 'jsDelivr 未索引,无法直拉' },
{ id: 'dracula', kind: 'poster', reason: '主题色存于扩展仓库,主仓库无配色 JSON' },
{ id: 'montserrat', kind: 'poster', reason: '仓库体积超 jsDelivr 索引上限' },
{ id: 'noto-emoji-repo', kind: 'icon', reason: '1.4GB 仓库,整树枚举不稳定;改用 GitHub Trees API 分目录(P3 已用子树方式接入)' }
];
function fetchJson(url) {
return new Promise((resolve, reject) => {
https.get(url, { headers: { 'User-Agent': 'drawlogo-source-discovery' } }, res => {
let data = '';
res.on('data', c => { data += c; });
res.on('end', () => {
try { resolve(JSON.parse(data)); }
catch (e) { reject(new Error('解析失败: ' + url)); }
});
}).on('error', reject);
});
function readSources(file) {
if (!fs.existsSync(file)) return [];
delete require.cache[require.resolve(file)];
const list = require(file);
return Array.isArray(list) ? list : [];
}
function readExistingIds() {
const text = fs.readFileSync(SOURCES_FILE, 'utf8');
return new Set([...text.matchAll(/\bid:\s*'([^']+)'/g)].map(m => m[1]));
async function getJSON(url, headers) {
const r = await fetch(url, { headers: Object.assign({ 'User-Agent': 'drawlogo-discover' }, headers || {}) });
if (!r.ok) throw new Error(url + ' → HTTP ' + r.status);
return r.json();
}
/** 协议是否允许商用(与项目规则一致) */
function isCommercial(spdx) {
const s = String(spdx || '');
if (!s) return false;
return !/(^|[\s-])(NC|SA|ND)([\s-]|$)|NonCommercial|GPL/i.test(s);
const sleep = ms => new Promise(r => setTimeout(r, ms));
/* ---------------- 1. Iconify ---------------- */
async function scanIconify(iconSources) {
const used = new Set();
for (const s of iconSources) {
used.add(s.id);
if (s.npm) {
const m = String(s.npm).match(/@iconify-json\/([^@/\s]+)/);
if (m) used.add(m[1]);
}
}
const all = await getJSON('https://api.iconify.design/collections');
const out = [];
for (const [prefix, v] of Object.entries(all)) {
const aliases = v.aliases || [];
if (used.has(prefix) || aliases.some(a => used.has(a))) continue;
const license = (v.license && (v.license.spdx || v.license.title)) || '?';
out.push({
kind: 'icon',
provider: 'iconify',
id: prefix,
name: v.name || prefix,
volume: v.total || 0,
license,
licenseOk: LICENSE_OK.test(license) && !LICENSE_BLOCK.test(license),
category: v.category || '',
url: 'https://icon-sets.iconify.design/' + prefix + '/',
note: 'Iconify 集合,可直接用 format:iconify 接入'
});
}
return out;
}
function pad(s, n) {
s = String(s);
// 中文按 2 字符宽估算
let width = 0;
for (const ch of s) width += /[\u4e00-\u9fa5]/.test(ch) ? 2 : 1;
return s + ' '.repeat(Math.max(0, n - width));
/* ---------------- 2. Fontsource(Google Fonts) ---------------- */
async function scanFontsource(posterSources) {
const fonts = await getJSON('https://api.fontsource.org/v1/fonts');
const usedIds = new Set(posterSources.filter(s => s.type === 'font').map(s => s.id));
const out = [];
for (const f of fonts) {
if (!LICENSE_OK.test(f.license || '') || LICENSE_BLOCK.test(f.license || '')) continue;
if (!Array.isArray(f.subsets) || !f.subsets.includes('latin')) continue;
// 已收录的字体源(fontsource-xxx / noto-xxx)跳过
if (usedIds.has('fontsource-' + f.id)) continue;
const weights = (f.weights || []).filter(w => w === 400 || w === 700);
out.push({
kind: 'poster',
provider: 'fontsource',
id: f.id,
name: f.family,
volume: Math.max(1, weights.length),
license: f.license,
licenseOk: true,
category: 'font',
url: 'https://fontsource.org/fonts/' + f.id,
note: weights.length ? 'latin ' + weights.join('/') + ' 可用' : '缺 400/700 标准字重'
});
}
return out;
}
/* ---------------- 3. Poly Haven 纹理 ---------------- */
async function scanPolyhaven(posterSources) {
const used = new Set(posterSources.map(s => s.id));
if (used.has('polyhaven-textures')) return [];
const all = await getJSON('https://api.polyhaven.com/assets?t=textures');
const cats = {};
for (const id of Object.keys(all)) {
for (const c of (all[id].categories || [])) cats[c] = (cats[c] || 0) + 1;
}
const top = Object.entries(cats).sort((a, b) => b[1] - a[1]).slice(0, 8)
.map(([c, n]) => c + '(' + n + ')').join('、');
return [{
kind: 'poster',
provider: 'polyhaven',
id: 'polyhaven-textures',
name: 'Poly Haven Textures',
volume: Object.keys(all).length,
license: 'CC0-1.0',
licenseOk: true,
category: 'bg',
url: 'https://polyhaven.com/textures',
note: 'CC0 可商用免署名;分类:' + top
}];
}
/* ---------------- 4. GitHub 主题检索 ---------------- */
async function scanGithub() {
const topics = [
'topic:icon-set license:mit',
'topic:3d-icons license:mit',
'topic:emoji license:mit',
'topic:texture cc0-1.0'
];
const out = [];
for (const q of topics) {
try {
const j = await getJSON('https://api.github.com/search/repositories?q=' + encodeURIComponent(q) +
'&sort=stars&order=desc&per_page=10', { Accept: 'application/vnd.github+json' });
for (const r of (j.items || [])) {
const license = (r.license && r.license.spdx_id) || '?';
out.push({
kind: q.includes('texture') ? 'poster' : 'icon',
provider: 'github',
id: r.full_name.replace('/', '-').toLowerCase(),
name: r.full_name,
volume: r.stargazers_count,
license,
licenseOk: LICENSE_OK.test(license),
category: r.topics && r.topics.slice(0, 3).join(',') || '',
url: r.html_url,
note: '★' + r.stargazers_count + ' · 仓库 ' + Math.round(r.size / 1024) + 'MB(volume 为星数,需人工确认素材量)'
});
}
} catch (e) {
console.warn(' ⚠️ GitHub 检索失败(' + q + '):' + e.message);
}
await sleep(6500); // 未鉴权搜索接口限流 10 次/分钟
}
return out;
}
/* ---------------- 评分与输出 ---------------- */
function score(c) {
if (!c.licenseOk) return 0;
const vol = Math.min(c.volume, 50000) / 50000;
const kindWeight = c.kind === 'icon' ? 1 : 1.1;
return +(vol * 60 * kindWeight + 40).toFixed(1);
}
async function main() {
console.log('画个标 · 素材源发现器\n');
const dry = process.argv.includes('--dry');
const onlyArg = (process.argv.find(a => a.startsWith('--only=')) || '').replace('--only=', '');
const only = onlyArg ? new Set(onlyArg.split(',')) : null;
const existing = readExistingIds();
console.log(`本地已收录源: ${existing.size}`);
const iconSources = readSources(ICON_SRC);
const posterSources = readSources(POSTER_SRC);
console.log(`已收录:图标源 ${iconSources.length},海报源 ${posterSources.length}`);
const collections = await fetchJson('https://api.iconify.design/collections');
const allIds = Object.keys(collections);
console.log(`Iconify 官方集合: ${allIds.length}\n`);
const covered = [];
const candidates = [];
const aliases = [];
const nonCommercial = [];
for (const id of allIds) {
const info = collections[id] || {};
const item = {
id,
name: info.name || id,
total: info.total || 0,
license: (info.license && info.license.spdx) || (info.license && info.license.title) || '未知',
author: info.author && info.author.name ? info.author.name : '',
home: info.author && info.author.url ? info.author.url : '',
brandRisk: BRAND_RISK.has(id)
};
if (existing.has(id)) { covered.push(item); continue; }
if (ALIAS[id]) { aliases.push({ ...item, aliasOf: ALIAS[id] }); continue; }
if (!isCommercial(item.license)) { nonCommercial.push(item); continue; }
// 预判拉取方式:Iconify 集合统一走 npm @iconify-json/<id> + format:'iconify' + scaleMode:'body'
item.suggestConfig = {
format: 'iconify',
npm: '@iconify-json/' + id,
scaleMode: 'body',
type: item.brandRisk ? 'brand' : 'icon'
};
candidates.push(item);
const tasks = [
['iconify', () => scanIconify(iconSources)],
['font', () => scanFontsource(posterSources)],
['texture', () => scanPolyhaven(posterSources)],
['github', () => scanGithub()]
];
for (const [key, fn] of tasks) {
if (only && !only.has(key)) continue;
try {
const list = await fn();
console.log(`扫描 ${key}: ${list.length} 个候选`);
candidates.push(...list);
} catch (e) {
console.warn(`扫描 ${key} 失败:${e.message}`);
}
}
candidates.sort((a, b) => b.total - a.total);
for (const c of candidates) c.score = score(c);
candidates.sort((a, b) => b.score - a.score || b.volume - a.volume);
if (process.argv.includes('--json')) {
console.log(JSON.stringify({ candidates, aliases, nonCommercial }, null, 2));
const ok = candidates.filter(c => c.licenseOk);
const blocked = candidates.filter(c => !c.licenseOk);
// 注册表:active 全量快照 + rejected 记录
const registry = {
updatedAt: new Date().toISOString().slice(0, 10),
iconSources: {},
posterSources: {},
rejected: REJECTED
};
for (const s of iconSources) {
registry.iconSources[s.id] = {
format: s.format || '', license: s.license || '', type: s.type || '', added: s.added || ''
};
}
for (const s of posterSources) {
registry.posterSources[s.id] = {
format: s.format || '', license: s.license || '', type: s.type || '', added: s.added || ''
};
}
console.log(`\n可用候选 ${ok.length} 个(占比 ${(ok.length / Math.max(1, candidates.length) * 100).toFixed(0)}%),` +
`协议不合规 ${blocked.length} 个已排除`);
console.log('Top 10:');
for (const c of ok.slice(0, 10)) {
console.log(` ${String(c.score).padStart(5)} ${c.provider.padEnd(11)} ${c.id.padEnd(28)} ` +
`${String(c.volume).padStart(6)} ${c.license}`);
}
const byProvider = {};
for (const c of ok) byProvider[c.provider] = (byProvider[c.provider] || 0) + 1;
console.log('候选分布:' + JSON.stringify(byProvider));
if (dry) {
console.log('\n--dry 模式,未写文件');
return;
}
console.log('=== 可直接新增(协议合规、非别名)===');
console.log(pad('ID', 22) + pad('图标数', 9) + pad('协议', 18) + pad('品牌风险', 10) + '名称');
console.log('-'.repeat(100));
for (const c of candidates) {
console.log(
pad(c.id, 22) +
pad(c.total.toLocaleString('zh-CN'), 9) +
pad(c.license, 18) +
pad(c.brandRisk ? '是' : '-', 10) +
c.name
);
}
console.log('\n=== 别名 / 子集(跳过,避免重复)===');
console.log(aliases.map(a => `${a.id} → ${a.aliasOf}`).join(', ') || '无');
console.log('\n=== 协议不合规(跳过)===');
console.log(nonCommercial.map(a => `${a.id}(${a.license})`).join(', ') || '无');
const totalIcons = candidates.reduce((a, b) => a + b.total, 0);
console.log('\n=== 汇总 ===');
console.log(`已覆盖: ${covered.length}`);
console.log(`可新增独立源: ${candidates.length} 个,约 ${totalIcons.toLocaleString('zh-CN')} 个图标`);
console.log(`其中品牌风险: ${candidates.filter(c => c.brandRisk).length} 个`);
console.log(`别名/子集: ${aliases.length} 个`);
console.log(`协议不合规: ${nonCommercial.length} 个`);
fs.mkdirSync(OUT_DIR, { recursive: true });
const outFile = path.join(OUT_DIR, 'source-candidates.json');
fs.writeFileSync(outFile, JSON.stringify({
scannedAt: new Date().toISOString(),
iconifyTotal: allIds.length,
covered: covered.length,
candidates,
aliases,
nonCommercial
}, null, 2));
console.log(`\n候选清单已写入: ${path.relative(ROOT, outFile)}`);
fs.mkdirSync(path.dirname(OUT_REGISTRY), { recursive: true });
fs.writeFileSync(OUT_CANDIDATES, JSON.stringify({
generatedAt: new Date().toISOString(),
total: candidates.length,
candidates
}, null, 2) + '\n', 'utf8');
fs.writeFileSync(OUT_REGISTRY, JSON.stringify(registry, null, 2) + '\n', 'utf8');
console.log('\n已写入:' + path.relative(ROOT, OUT_CANDIDATES) + '、' + path.relative(ROOT, OUT_REGISTRY));
}
main().catch(e => {
console.error('发现失败:', e.message);
process.exit(1);
});
main().catch(e => { console.error('❌ 发现器失败:' + e.message); process.exit(1); });