feat: 建立可选字体包协议与安全注册器
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
export * from "./registry.js";
|
||||
export * from "./resolver.js";
|
||||
export * from "./schema.js";
|
||||
export * from "./types.js";
|
||||
@@ -0,0 +1,297 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
readFile,
|
||||
readdir,
|
||||
realpath,
|
||||
stat
|
||||
} from "node:fs/promises";
|
||||
import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||
import {
|
||||
MAXIMUM_FONT_PACK_COUNT,
|
||||
MAXIMUM_FONT_PACK_LICENSE_BYTES,
|
||||
MAXIMUM_FONT_PACK_MANIFEST_BYTES,
|
||||
compareSemanticVersions,
|
||||
fontPackManifestSchema,
|
||||
isAppVersionCompatible,
|
||||
semanticVersionSchema,
|
||||
type FontPackAsset,
|
||||
type FontPackManifest
|
||||
} from "./schema.js";
|
||||
import type {
|
||||
DiscoverFontPacksOptions,
|
||||
FontPackDiagnostic,
|
||||
FontPackRegistryResult,
|
||||
InstalledFontPack,
|
||||
InstalledFontPackAsset,
|
||||
InstalledFontPackFace
|
||||
} from "./types.js";
|
||||
|
||||
function sha256(content: Uint8Array | string) {
|
||||
return createHash("sha256").update(content).digest("hex");
|
||||
}
|
||||
|
||||
function isContainedPath(root: string, target: string) {
|
||||
const path = relative(root, target);
|
||||
return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
|
||||
}
|
||||
|
||||
async function readTrustedFile(
|
||||
packDirectory: string,
|
||||
asset: FontPackAsset | { path: string; bytes: number; sha256: string }
|
||||
) {
|
||||
const candidate = resolve(packDirectory, ...asset.path.split("/"));
|
||||
if (!isContainedPath(packDirectory, candidate)) {
|
||||
throw new Error(`资源越过字体包目录:${asset.path}`);
|
||||
}
|
||||
const linkStatus = await lstat(candidate);
|
||||
if (linkStatus.isSymbolicLink() || !linkStatus.isFile()) {
|
||||
throw new Error(`资源不是普通文件:${asset.path}`);
|
||||
}
|
||||
const realCandidate = await realpath(candidate);
|
||||
if (!isContainedPath(packDirectory, realCandidate)) {
|
||||
throw new Error(`资源真实路径越过字体包目录:${asset.path}`);
|
||||
}
|
||||
const fileStatus = await stat(realCandidate);
|
||||
if (fileStatus.size !== asset.bytes) {
|
||||
throw new Error(`资源大小不匹配:${asset.path}`);
|
||||
}
|
||||
const content = await readFile(realCandidate);
|
||||
if (sha256(content) !== asset.sha256) {
|
||||
throw new Error(`资源 SHA-256 不匹配:${asset.path}`);
|
||||
}
|
||||
return { absolutePath: realCandidate, content };
|
||||
}
|
||||
|
||||
async function loadPack(
|
||||
root: string,
|
||||
rootIndex: number,
|
||||
idDirectory: string,
|
||||
versionDirectory: string,
|
||||
appVersion: string
|
||||
): Promise<InstalledFontPack> {
|
||||
const packDirectory = await realpath(versionDirectory);
|
||||
if (!isContainedPath(root, packDirectory)) {
|
||||
throw new Error("字体包目录越过注册根目录");
|
||||
}
|
||||
const manifestPath = resolve(packDirectory, "font-pack.json");
|
||||
const manifestStatus = await lstat(manifestPath);
|
||||
if (
|
||||
manifestStatus.isSymbolicLink() ||
|
||||
!manifestStatus.isFile() ||
|
||||
manifestStatus.size > MAXIMUM_FONT_PACK_MANIFEST_BYTES
|
||||
) {
|
||||
throw new Error("font-pack.json 不是受支持的普通文件");
|
||||
}
|
||||
const manifest = fontPackManifestSchema.parse(
|
||||
JSON.parse(await readFile(manifestPath, "utf8")) as unknown
|
||||
);
|
||||
if (manifest.id !== idDirectory) {
|
||||
throw new Error(`清单 ID 与目录不一致:${manifest.id} != ${idDirectory}`);
|
||||
}
|
||||
const versionName = versionDirectory.split(/[\\/]/u).at(-1);
|
||||
if (manifest.version !== versionName) {
|
||||
throw new Error(`清单版本与目录不一致:${manifest.version} != ${versionName}`);
|
||||
}
|
||||
if (!isAppVersionCompatible(appVersion, manifest.compatibility)) {
|
||||
throw Object.assign(new Error("字体包与当前应用版本不兼容"), {
|
||||
code: "PACK_INCOMPATIBLE"
|
||||
});
|
||||
}
|
||||
const license = await readTrustedFile(packDirectory, {
|
||||
path: manifest.licenseFile,
|
||||
bytes: manifest.licenseBytes,
|
||||
sha256: manifest.licenseSha256
|
||||
});
|
||||
if (license.content.byteLength > MAXIMUM_FONT_PACK_LICENSE_BYTES) {
|
||||
throw new Error("字体包许可文件超过大小限制");
|
||||
}
|
||||
const faces: InstalledFontPackFace[] = [];
|
||||
for (const face of manifest.faces) {
|
||||
const web = await readTrustedFile(packDirectory, face.web);
|
||||
const docx = await readTrustedFile(packDirectory, face.docx);
|
||||
faces.push({
|
||||
...face,
|
||||
web: {
|
||||
...face.web,
|
||||
absolutePath: web.absolutePath,
|
||||
packDirectory
|
||||
},
|
||||
docx: {
|
||||
...face.docx,
|
||||
absolutePath: docx.absolutePath,
|
||||
packDirectory
|
||||
}
|
||||
});
|
||||
}
|
||||
const fingerprint = sha256(
|
||||
JSON.stringify({
|
||||
manifestVersion: manifest.manifestVersion,
|
||||
id: manifest.id,
|
||||
version: manifest.version,
|
||||
licenseSha256: manifest.licenseSha256,
|
||||
faces: manifest.faces.map((face) => ({
|
||||
id: face.id,
|
||||
targets: [...face.targets].sort(),
|
||||
weight: face.weight,
|
||||
style: face.style,
|
||||
web: face.web.sha256,
|
||||
docx: face.docx.sha256
|
||||
}))
|
||||
})
|
||||
);
|
||||
return {
|
||||
...manifest,
|
||||
root,
|
||||
directory: packDirectory,
|
||||
rootIndex,
|
||||
fingerprint,
|
||||
faces
|
||||
};
|
||||
}
|
||||
|
||||
function diagnostic(
|
||||
code: FontPackDiagnostic["code"],
|
||||
severity: FontPackDiagnostic["severity"],
|
||||
message: string,
|
||||
fields: Partial<Omit<FontPackDiagnostic, "code" | "severity" | "message">> = {}
|
||||
): FontPackDiagnostic {
|
||||
return { code, severity, message, ...fields };
|
||||
}
|
||||
|
||||
export async function discoverFontPacks(
|
||||
options: DiscoverFontPacksOptions
|
||||
): Promise<FontPackRegistryResult> {
|
||||
semanticVersionSchema.parse(options.appVersion);
|
||||
const diagnostics: FontPackDiagnostic[] = [];
|
||||
const candidates: InstalledFontPack[] = [];
|
||||
for (const [rootIndex, configuredRoot] of options.roots.entries()) {
|
||||
let root: string;
|
||||
const requestedRoot = resolve(configuredRoot);
|
||||
try {
|
||||
const requestedStatus = await lstat(requestedRoot);
|
||||
if (requestedStatus.isSymbolicLink() || !requestedStatus.isDirectory()) {
|
||||
diagnostics.push(
|
||||
diagnostic("ROOT_INVALID", "error", "字体包根目录不是普通目录", {
|
||||
root: requestedRoot
|
||||
})
|
||||
);
|
||||
continue;
|
||||
}
|
||||
root = await realpath(requestedRoot);
|
||||
} catch {
|
||||
diagnostics.push(
|
||||
diagnostic("ROOT_NOT_FOUND", "info", "字体包根目录不存在", {
|
||||
root: requestedRoot
|
||||
})
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const rootStatus = await lstat(root);
|
||||
if (rootStatus.isSymbolicLink() || !rootStatus.isDirectory()) {
|
||||
diagnostics.push(
|
||||
diagnostic("ROOT_INVALID", "error", "字体包根目录不是普通目录", { root })
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const idEntries = (await readdir(root, { withFileTypes: true })).sort((a, b) =>
|
||||
a.name.localeCompare(b.name, "en")
|
||||
);
|
||||
for (const idEntry of idEntries) {
|
||||
if (!idEntry.isDirectory() || idEntry.isSymbolicLink()) {
|
||||
continue;
|
||||
}
|
||||
const idDirectory = resolve(root, idEntry.name);
|
||||
const versionEntries = (await readdir(idDirectory, { withFileTypes: true })).sort(
|
||||
(a, b) => a.name.localeCompare(b.name, "en")
|
||||
);
|
||||
for (const versionEntry of versionEntries) {
|
||||
if (
|
||||
!versionEntry.isDirectory() ||
|
||||
versionEntry.isSymbolicLink() ||
|
||||
!semanticVersionSchema.safeParse(versionEntry.name).success
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
candidates.push(
|
||||
await loadPack(
|
||||
root,
|
||||
rootIndex,
|
||||
idEntry.name,
|
||||
resolve(idDirectory, versionEntry.name),
|
||||
options.appVersion
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
const incompatible =
|
||||
error instanceof Error &&
|
||||
"code" in error &&
|
||||
error.code === "PACK_INCOMPATIBLE";
|
||||
diagnostics.push(
|
||||
diagnostic(
|
||||
incompatible ? "PACK_INCOMPATIBLE" : "MANIFEST_INVALID",
|
||||
incompatible ? "warning" : "error",
|
||||
error instanceof Error ? error.message : "字体包加载失败",
|
||||
{
|
||||
root,
|
||||
packId: idEntry.name,
|
||||
packVersion: versionEntry.name
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const selected = new Map<string, InstalledFontPack>();
|
||||
for (const candidate of candidates.sort((left, right) => {
|
||||
if (left.rootIndex !== right.rootIndex) {
|
||||
return left.rootIndex - right.rootIndex;
|
||||
}
|
||||
const idOrder = left.id.localeCompare(right.id, "en");
|
||||
return idOrder !== 0
|
||||
? idOrder
|
||||
: compareSemanticVersions(right.version, left.version);
|
||||
})) {
|
||||
const existing = selected.get(candidate.id);
|
||||
if (!existing) {
|
||||
selected.set(candidate.id, candidate);
|
||||
continue;
|
||||
}
|
||||
diagnostics.push(
|
||||
diagnostic("PACK_SHADOWED", "info", "字体包版本被更高优先级版本覆盖", {
|
||||
root: candidate.root,
|
||||
packId: candidate.id,
|
||||
packVersion: candidate.version
|
||||
})
|
||||
);
|
||||
}
|
||||
const packs = [...selected.values()];
|
||||
if (packs.length > MAXIMUM_FONT_PACK_COUNT) {
|
||||
diagnostics.push(
|
||||
diagnostic("PACK_LIMIT_EXCEEDED", "error", "可用字体包数量超过限制")
|
||||
);
|
||||
packs.length = MAXIMUM_FONT_PACK_COUNT;
|
||||
}
|
||||
return {
|
||||
packs,
|
||||
diagnostics,
|
||||
fingerprint: sha256(
|
||||
packs.map((pack) => `${pack.id}@${pack.version}:${pack.fingerprint}`).join("\n")
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
export async function readInstalledFontPackAsset(
|
||||
asset: InstalledFontPackAsset
|
||||
) {
|
||||
const content = (
|
||||
await readTrustedFile(asset.packDirectory, {
|
||||
path: asset.path,
|
||||
bytes: asset.bytes,
|
||||
sha256: asset.sha256
|
||||
})
|
||||
).content;
|
||||
return new Uint8Array(content);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import type {
|
||||
FontPackDiagnostic,
|
||||
FontPackFaceRequest,
|
||||
FontPackFaceResolution,
|
||||
InstalledFontPack,
|
||||
ResolveFontPackFacesOptions
|
||||
} from "./types.js";
|
||||
|
||||
function normalizeFontFamily(value: string) {
|
||||
return value.trim().toLocaleLowerCase("en-US");
|
||||
}
|
||||
|
||||
function orderedPacks(
|
||||
packs: readonly InstalledFontPack[],
|
||||
preferredPackIds: readonly string[]
|
||||
) {
|
||||
const preference = new Map(
|
||||
preferredPackIds.map((id, index) => [id, index])
|
||||
);
|
||||
return [...packs].sort((left, right) => {
|
||||
const leftRank = preference.get(left.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
const rightRank = preference.get(right.id) ?? Number.MAX_SAFE_INTEGER;
|
||||
return leftRank !== rightRank
|
||||
? leftRank - rightRank
|
||||
: left.id.localeCompare(right.id, "en");
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveFontPackFaces(
|
||||
requests: readonly FontPackFaceRequest[],
|
||||
packs: readonly InstalledFontPack[],
|
||||
options: ResolveFontPackFacesOptions = {}
|
||||
): FontPackFaceResolution {
|
||||
const resolved: FontPackFaceResolution["resolved"] = [];
|
||||
const unmatched: FontPackFaceRequest[] = [];
|
||||
const diagnostics: FontPackDiagnostic[] = [];
|
||||
const candidates = orderedPacks(packs, options.preferredPackIds ?? []);
|
||||
for (const request of requests) {
|
||||
const requestNames = new Set(
|
||||
[request.family, ...(request.aliases ?? [])].map(normalizeFontFamily)
|
||||
);
|
||||
let match: FontPackFaceResolution["resolved"][number] | undefined;
|
||||
for (const pack of candidates) {
|
||||
const face = pack.faces.find(
|
||||
(candidate) =>
|
||||
candidate.weight === request.weight &&
|
||||
candidate.style === request.style &&
|
||||
candidate.targets.some((target) =>
|
||||
requestNames.has(normalizeFontFamily(target))
|
||||
)
|
||||
);
|
||||
if (face) {
|
||||
match = {
|
||||
request,
|
||||
pack,
|
||||
face,
|
||||
matchedFamily:
|
||||
face.targets.find((target) =>
|
||||
requestNames.has(normalizeFontFamily(target))
|
||||
) ?? request.family
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
resolved.push(match);
|
||||
continue;
|
||||
}
|
||||
unmatched.push(request);
|
||||
if (options.reportMissing) {
|
||||
diagnostics.push({
|
||||
code: "FONT_FACE_NOT_PROVIDED",
|
||||
severity: "info",
|
||||
message: `没有字体包提供 ${request.family} ${request.weight} ${request.style}`
|
||||
});
|
||||
}
|
||||
}
|
||||
return { resolved, unmatched, diagnostics };
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const FONT_PACK_MANIFEST_VERSION = 1;
|
||||
export const MAXIMUM_FONT_PACK_COUNT = 8;
|
||||
export const MAXIMUM_FONT_PACK_FACE_COUNT = 16;
|
||||
export const MAXIMUM_FONT_PACK_MANIFEST_BYTES = 128 * 1024;
|
||||
export const MAXIMUM_FONT_PACK_LICENSE_BYTES = 256 * 1024;
|
||||
export const MAXIMUM_FONT_PACK_WEB_FONT_BYTES = 8 * 1024 * 1024;
|
||||
export const MAXIMUM_FONT_PACK_DOCX_FONT_BYTES = 16 * 1024 * 1024;
|
||||
export const MAXIMUM_FONT_PACK_TOTAL_BYTES = 96 * 1024 * 1024;
|
||||
|
||||
const semanticVersionPattern =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
|
||||
const identifierPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
|
||||
const sha256Pattern = /^[a-f0-9]{64}$/u;
|
||||
const fontNamePattern = /^[\p{L}\p{N}\s._-]+$/u;
|
||||
|
||||
export const semanticVersionSchema = z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(semanticVersionPattern, "版本号必须是完整 SemVer")
|
||||
.refine(
|
||||
(value) => {
|
||||
const prerelease = semanticVersionPattern.exec(value)?.[4];
|
||||
return !prerelease
|
||||
? true
|
||||
: prerelease
|
||||
.split(".")
|
||||
.every((part) => !/^\d+$/u.test(part) || part === "0" || !part.startsWith("0"));
|
||||
},
|
||||
"SemVer 预发布数字标识不能包含前导零"
|
||||
);
|
||||
|
||||
const safeRelativePathSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(300)
|
||||
.refine(
|
||||
(value) =>
|
||||
!value.includes("\\") &&
|
||||
!value.includes("\0") &&
|
||||
!value.startsWith("/") &&
|
||||
!value.split("/").some((segment) => segment === ".." || segment === ""),
|
||||
"资源必须使用安全的 POSIX 相对路径"
|
||||
);
|
||||
|
||||
const fontAssetSchema = z
|
||||
.object({
|
||||
path: safeRelativePathSchema,
|
||||
sha256: z.string().regex(sha256Pattern),
|
||||
bytes: z.number().int().positive()
|
||||
})
|
||||
.strict();
|
||||
|
||||
const webFontAssetSchema = fontAssetSchema
|
||||
.extend({
|
||||
format: z.literal("woff2"),
|
||||
bytes: z.number().int().positive().max(MAXIMUM_FONT_PACK_WEB_FONT_BYTES)
|
||||
})
|
||||
.strict()
|
||||
.refine((asset) => asset.path.toLowerCase().endsWith(".woff2"), {
|
||||
message: "Web 字体资源必须使用 .woff2 扩展名",
|
||||
path: ["path"]
|
||||
});
|
||||
|
||||
const docxFontAssetSchema = fontAssetSchema
|
||||
.extend({
|
||||
format: z.literal("truetype"),
|
||||
bytes: z.number().int().positive().max(MAXIMUM_FONT_PACK_DOCX_FONT_BYTES)
|
||||
})
|
||||
.strict()
|
||||
.refine((asset) => asset.path.toLowerCase().endsWith(".ttf"), {
|
||||
message: "DOCX 字体资源必须使用静态 .ttf 文件",
|
||||
path: ["path"]
|
||||
});
|
||||
|
||||
const fontFamilySchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.regex(fontNamePattern, "字体家族名称包含不支持的字符");
|
||||
|
||||
export const fontPackFaceSchema = z
|
||||
.object({
|
||||
id: z.string().regex(identifierPattern),
|
||||
targets: z.array(fontFamilySchema).min(1).max(32),
|
||||
weight: z.number().int().min(100).max(900).multipleOf(100),
|
||||
style: z.enum(["normal", "italic"]),
|
||||
web: webFontAssetSchema,
|
||||
docx: docxFontAssetSchema
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const fontPackManifestSchema = z
|
||||
.object({
|
||||
manifestVersion: z.literal(FONT_PACK_MANIFEST_VERSION),
|
||||
id: z.string().regex(identifierPattern),
|
||||
version: semanticVersionSchema,
|
||||
name: z.string().trim().min(1).max(100),
|
||||
description: z.string().trim().max(500),
|
||||
license: z.string().trim().min(1).max(100),
|
||||
licenseFile: safeRelativePathSchema,
|
||||
licenseSha256: z.string().regex(sha256Pattern),
|
||||
licenseBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(MAXIMUM_FONT_PACK_LICENSE_BYTES),
|
||||
compatibility: z
|
||||
.object({
|
||||
minimumAppVersion: semanticVersionSchema,
|
||||
maximumAppVersionExclusive: semanticVersionSchema.optional()
|
||||
})
|
||||
.strict(),
|
||||
faces: z.array(fontPackFaceSchema).min(1).max(MAXIMUM_FONT_PACK_FACE_COUNT)
|
||||
})
|
||||
.strict()
|
||||
.superRefine((manifest, context) => {
|
||||
if (
|
||||
manifest.compatibility.maximumAppVersionExclusive !== undefined &&
|
||||
compareSemanticVersions(
|
||||
manifest.compatibility.maximumAppVersionExclusive,
|
||||
manifest.compatibility.minimumAppVersion
|
||||
) <= 0
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "应用兼容上限必须大于最低版本",
|
||||
path: ["compatibility", "maximumAppVersionExclusive"]
|
||||
});
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
const identities = new Set<string>();
|
||||
const paths = new Set<string>([manifest.licenseFile.toLowerCase()]);
|
||||
for (const [index, face] of manifest.faces.entries()) {
|
||||
if (
|
||||
new Set(face.targets.map((target) => target.toLowerCase())).size !==
|
||||
face.targets.length
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "字体面目标家族不能重复",
|
||||
path: ["faces", index, "targets"]
|
||||
});
|
||||
}
|
||||
if (ids.has(face.id)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `字体面 ID 重复:${face.id}`,
|
||||
path: ["faces", index, "id"]
|
||||
});
|
||||
}
|
||||
ids.add(face.id);
|
||||
const identity = `${face.targets.map((target) => target.toLowerCase()).sort().join("|")}:${face.weight}:${face.style}`;
|
||||
if (identities.has(identity)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "字体面目标、字重和样式重复",
|
||||
path: ["faces", index]
|
||||
});
|
||||
}
|
||||
identities.add(identity);
|
||||
for (const [kind, path] of [
|
||||
["web", face.web.path],
|
||||
["docx", face.docx.path]
|
||||
] as const) {
|
||||
const normalized = path.toLowerCase();
|
||||
if (paths.has(normalized)) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `字体包资源路径重复:${path}`,
|
||||
path: ["faces", index, kind, "path"]
|
||||
});
|
||||
}
|
||||
paths.add(normalized);
|
||||
}
|
||||
}
|
||||
const totalBytes = manifest.faces.reduce(
|
||||
(total, face) => total + face.web.bytes + face.docx.bytes,
|
||||
0
|
||||
);
|
||||
if (totalBytes > MAXIMUM_FONT_PACK_TOTAL_BYTES) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "字体包声明资源总大小超过限制",
|
||||
path: ["faces"]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type FontPackManifest = z.infer<typeof fontPackManifestSchema>;
|
||||
export type FontPackFace = z.infer<typeof fontPackFaceSchema>;
|
||||
export type FontPackAsset = FontPackFace["web"] | FontPackFace["docx"];
|
||||
|
||||
export function parseSemanticVersion(value: string) {
|
||||
const match = semanticVersionPattern.exec(value);
|
||||
if (!match) {
|
||||
throw new Error(`无效的 SemVer:${value}`);
|
||||
}
|
||||
return {
|
||||
major: Number(match[1]),
|
||||
minor: Number(match[2]),
|
||||
patch: Number(match[3]),
|
||||
prerelease: match[4]?.split(".") ?? []
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrerelease(left: string[], right: string[]) {
|
||||
if (left.length === 0 || right.length === 0) {
|
||||
return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
|
||||
}
|
||||
const length = Math.max(left.length, right.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftPart = left[index];
|
||||
const rightPart = right[index];
|
||||
if (leftPart === undefined || rightPart === undefined) {
|
||||
return leftPart === rightPart ? 0 : leftPart === undefined ? -1 : 1;
|
||||
}
|
||||
if (leftPart === rightPart) {
|
||||
continue;
|
||||
}
|
||||
const leftNumber = /^\d+$/u.test(leftPart) ? Number(leftPart) : undefined;
|
||||
const rightNumber = /^\d+$/u.test(rightPart) ? Number(rightPart) : undefined;
|
||||
if (leftNumber !== undefined && rightNumber !== undefined) {
|
||||
return leftNumber < rightNumber ? -1 : 1;
|
||||
}
|
||||
if (leftNumber !== undefined || rightNumber !== undefined) {
|
||||
return leftNumber !== undefined ? -1 : 1;
|
||||
}
|
||||
return leftPart < rightPart ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function compareSemanticVersions(left: string, right: string) {
|
||||
const a = parseSemanticVersion(left);
|
||||
const b = parseSemanticVersion(right);
|
||||
for (const key of ["major", "minor", "patch"] as const) {
|
||||
if (a[key] !== b[key]) {
|
||||
return a[key] < b[key] ? -1 : 1;
|
||||
}
|
||||
}
|
||||
return comparePrerelease(a.prerelease, b.prerelease);
|
||||
}
|
||||
|
||||
export function isAppVersionCompatible(
|
||||
appVersion: string,
|
||||
compatibility: FontPackManifest["compatibility"]
|
||||
) {
|
||||
return (
|
||||
compareSemanticVersions(appVersion, compatibility.minimumAppVersion) >= 0 &&
|
||||
(compatibility.maximumAppVersionExclusive === undefined ||
|
||||
compareSemanticVersions(
|
||||
appVersion,
|
||||
compatibility.maximumAppVersionExclusive
|
||||
) < 0)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { FontPackAsset, FontPackFace, FontPackManifest } from "./schema.js";
|
||||
|
||||
export type FontPackDiagnosticSeverity = "info" | "warning" | "error";
|
||||
|
||||
export type FontPackDiagnosticCode =
|
||||
| "ROOT_NOT_FOUND"
|
||||
| "ROOT_INVALID"
|
||||
| "PACK_LIMIT_EXCEEDED"
|
||||
| "PACK_LAYOUT_INVALID"
|
||||
| "MANIFEST_INVALID"
|
||||
| "PACK_INCOMPATIBLE"
|
||||
| "PACK_SHADOWED"
|
||||
| "RESOURCE_INVALID"
|
||||
| "FONT_FACE_NOT_PROVIDED";
|
||||
|
||||
export interface FontPackDiagnostic {
|
||||
code: FontPackDiagnosticCode;
|
||||
severity: FontPackDiagnosticSeverity;
|
||||
message: string;
|
||||
root?: string;
|
||||
packId?: string;
|
||||
packVersion?: string;
|
||||
faceId?: string;
|
||||
}
|
||||
|
||||
export type InstalledFontPackAsset = FontPackAsset & {
|
||||
absolutePath: string;
|
||||
packDirectory: string;
|
||||
};
|
||||
|
||||
export interface InstalledFontPackFace
|
||||
extends Omit<FontPackFace, "web" | "docx"> {
|
||||
web: InstalledFontPackAsset & { format: "woff2" };
|
||||
docx: InstalledFontPackAsset & { format: "truetype" };
|
||||
}
|
||||
|
||||
export interface InstalledFontPack
|
||||
extends Omit<FontPackManifest, "faces"> {
|
||||
root: string;
|
||||
directory: string;
|
||||
rootIndex: number;
|
||||
fingerprint: string;
|
||||
faces: InstalledFontPackFace[];
|
||||
}
|
||||
|
||||
export interface FontPackRegistryResult {
|
||||
packs: InstalledFontPack[];
|
||||
diagnostics: FontPackDiagnostic[];
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
export interface FontPackFaceRequest {
|
||||
family: string;
|
||||
aliases?: readonly string[];
|
||||
weight: number;
|
||||
style: "normal" | "italic";
|
||||
}
|
||||
|
||||
export interface ResolvedFontPackFace {
|
||||
request: FontPackFaceRequest;
|
||||
pack: InstalledFontPack;
|
||||
face: InstalledFontPackFace;
|
||||
matchedFamily: string;
|
||||
}
|
||||
|
||||
export interface FontPackFaceResolution {
|
||||
resolved: ResolvedFontPackFace[];
|
||||
unmatched: FontPackFaceRequest[];
|
||||
diagnostics: FontPackDiagnostic[];
|
||||
}
|
||||
|
||||
export interface DiscoverFontPacksOptions {
|
||||
roots: readonly string[];
|
||||
appVersion: string;
|
||||
}
|
||||
|
||||
export interface ResolveFontPackFacesOptions {
|
||||
preferredPackIds?: readonly string[];
|
||||
reportMissing?: boolean;
|
||||
}
|
||||
Reference in New Issue
Block a user