@takumi-rs/core2.22.158.9 kB
import { createRequire } from "module";
import { defaultStore, fetchImages, fetchImagesSettled } from "@takumi-rs/helpers/renderer";
import { fontFromUrl } from "@takumi-rs/helpers";
// index.js
const require = createRequire(import.meta.url);
const { readFileSync } = require(/* turbopackOptional: true */ "fs");
let nativeBinding = null;
let __napiLoadedBindingTarget = "native";
let __napiRequiredNativeBinding = null;
const loadErrors = [];
const isMusl = () => {
let musl = false;
if (process.platform === "linux") {
musl = isMuslFromFilesystem();
if (musl === null) musl = isMuslFromReport();
if (musl === null) musl = isMuslFromChildProcess();
}
return musl;
};
const isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-");
const isMuslFromFilesystem = () => {
try {
return readFileSync("/usr/bin/ldd", "utf-8").includes("musl");
} catch {
return null;
}
};
const isMuslFromReport = () => {
let report = null;
if (process.report && typeof process.report.getReport === "function") {
process.report.excludeNetwork = true;
report = process.report.getReport();
}
if (!report) return null;
if (report.header && report.header.glibcVersionRuntime) return false;
if (Array.isArray(report.sharedObjects)) {
if (report.sharedObjects.some(isFileMusl)) return true;
}
return false;
};
const isMuslFromChildProcess = () => {
try {
return require(/* turbopackOptional: true */ "child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl");
} catch (e) {
return false;
}
};
function requireNative() {
if (process.env.TAKUMI_CORE_TARGET) try {
const overrideBinding = require(/* turbopackOptional: true */ process.env.TAKUMI_CORE_TARGET);
__napiLoadedBindingTarget = overrideBinding && typeof overrideBinding.__napiBindingTarget === "string" ? overrideBinding.__napiBindingTarget : "native";
return overrideBinding;
} catch (err) {
loadErrors.push(err);
}
else if (process.platform === "android") {
if (process.arch === "arm64") {
try {
return require(/* turbopackOptional: true */ "../core.android-arm64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-android-arm64/core.android-arm64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-android-arm64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "arm") {
try {
return require(/* turbopackOptional: true */ "../core.android-arm-eabi.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-android-arm-eabi/core.android-arm-eabi.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-android-arm-eabi/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Android ${process.arch}`));
} else if (process.platform === "win32") {
if (process.arch === "x64") {
if (process.config && process.config.variables && process.config.variables.shlib_suffix === "dll.a" || process.config && process.config.variables && process.config.variables.node_target_type === "shared_library") {
try {
return require(/* turbopackOptional: true */ "../core.win32-x64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-x64-gnu/core.win32-x64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-x64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.win32-x64-msvc.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-x64-msvc/core.win32-x64-msvc.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-x64-msvc/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "ia32") {
try {
return require(/* turbopackOptional: true */ "../core.win32-ia32-msvc.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-ia32-msvc/core.win32-ia32-msvc.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-ia32-msvc/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "arm64") {
try {
return require(/* turbopackOptional: true */ "../core.win32-arm64-msvc.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-arm64-msvc/core.win32-arm64-msvc.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-win32-arm64-msvc/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Windows: ${process.arch}`));
} else if (process.platform === "darwin") {
try {
return require(/* turbopackOptional: true */ "../core.darwin-universal.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-universal/core.darwin-universal.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-universal/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
if (process.arch === "x64") {
try {
return require(/* turbopackOptional: true */ "../core.darwin-x64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-x64/core.darwin-x64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-x64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "arm64") {
try {
return require(/* turbopackOptional: true */ "../core.darwin-arm64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-arm64/core.darwin-arm64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-darwin-arm64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on macOS: ${process.arch}`));
} else if (process.platform === "freebsd") {
if (process.arch === "x64") {
try {
return require(/* turbopackOptional: true */ "../core.freebsd-x64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-x64/core.freebsd-x64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-x64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "arm64") {
try {
return require(/* turbopackOptional: true */ "../core.freebsd-arm64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-arm64/core.freebsd-arm64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-arm64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "ppc64") {
try {
return require(/* turbopackOptional: true */ "../core.freebsd-ppc64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-ppc64/core.freebsd-ppc64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-freebsd-ppc64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on FreeBSD: ${process.arch}`));
} else if (process.platform === "linux") {
if (process.arch === "x64") {
if (isMusl()) {
try {
return require(/* turbopackOptional: true */ "../core.linux-x64-musl.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-x64-musl/core.linux-x64-musl.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-x64-musl/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.linux-x64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-x64-gnu/core.linux-x64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-x64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "arm64") {
if (isMusl()) {
try {
return require(/* turbopackOptional: true */ "../core.linux-arm64-musl.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm64-musl/core.linux-arm64-musl.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm64-musl/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.linux-arm64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm64-gnu/core.linux-arm64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "arm") {
if (isMusl()) {
try {
return require(/* turbopackOptional: true */ "../core.linux-arm-musleabihf.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm-musleabihf/core.linux-arm-musleabihf.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm-musleabihf/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.linux-arm-gnueabihf.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm-gnueabihf/core.linux-arm-gnueabihf.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-arm-gnueabihf/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "loong64") {
if (isMusl()) {
try {
return require(/* turbopackOptional: true */ "../core.linux-loong64-musl.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-loong64-musl/core.linux-loong64-musl.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-loong64-musl/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.linux-loong64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-loong64-gnu/core.linux-loong64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-loong64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "riscv64") {
if (isMusl()) {
try {
return require(/* turbopackOptional: true */ "../core.linux-riscv64-musl.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-riscv64-musl/core.linux-riscv64-musl.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-riscv64-musl/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else {
try {
return require(/* turbopackOptional: true */ "../core.linux-riscv64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-riscv64-gnu/core.linux-riscv64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-riscv64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
}
} else if (process.arch === "ppc64") {
try {
return require(/* turbopackOptional: true */ "../core.linux-ppc64-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-ppc64-gnu/core.linux-ppc64-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-ppc64-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "s390x") {
try {
return require(/* turbopackOptional: true */ "../core.linux-s390x-gnu.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-s390x-gnu/core.linux-s390x-gnu.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-linux-s390x-gnu/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Linux: ${process.arch}`));
} else if (process.platform === "openharmony") {
if (process.arch === "arm64") {
try {
return require(/* turbopackOptional: true */ "../core.openharmony-arm64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-arm64/core.openharmony-arm64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-arm64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "x64") {
try {
return require(/* turbopackOptional: true */ "../core.openharmony-x64.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-x64/core.openharmony-x64.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-x64/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else if (process.arch === "arm") {
try {
return require(/* turbopackOptional: true */ "../core.openharmony-arm.node");
} catch (e) {
loadErrors.push(e);
}
try {
const binding = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-arm/core.openharmony-arm.node");
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-openharmony-arm/package.json").version;
if (bindingPackageVersion !== "2.22.1" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
return binding;
} catch (e) {
loadErrors.push(e);
}
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`));
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`));
}
function createLoadErrorChain(errors) {
return errors.reduce((previous, current) => {
let message;
try {
message = current && typeof current.message === "string" ? current.message : String(current);
} catch {
message = "Unknown error";
}
const error = new Error(message);
error.cause = previous;
return error;
}, null);
}
const __napiWasiFlavors = ["wasm32-wasi"];
const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR;
const __napiWasiFlavorRequested = typeof __napiWasiFlavor === "string" && __napiWasiFlavor.length > 0;
if (__napiWasiFlavorRequested && __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1) throw new Error("Unsupported WASI flavor \"" + __napiWasiFlavor + "\". Available flavors: " + __napiWasiFlavors.join(", "));
const forceWasiError = process.env.NAPI_RS_FORCE_WASI === "error";
const forceWasi = process.env.NAPI_RS_FORCE_WASI === "true" || forceWasiError || __napiWasiFlavorRequested;
if (!forceWasi) {
nativeBinding = requireNative();
__napiRequiredNativeBinding = nativeBinding;
}
if (!nativeBinding || forceWasi) {
let wasiBinding = null;
let wasiBindingLoaded = false;
const wasiBindingErrors = [];
const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => {
try {
require.resolve(specifier);
} catch (resolveError) {
if (!resolveError || resolveError.code !== "MODULE_NOT_FOUND") throw resolveError;
if (isPackage) {
try {
require.resolve(specifier + "/package.json");
} catch (packageError) {
if (packageError && packageError.code === "MODULE_NOT_FOUND") return resolveError;
throw resolveError;
}
throw resolveError;
}
return resolveError;
}
if (localArtifacts) {
let artifactError = null;
for (let i = 0; i < localArtifacts.length; i++) try {
require.resolve(localArtifacts[i]);
return null;
} catch (resolveError) {
if (!resolveError || resolveError.code !== "MODULE_NOT_FOUND") throw resolveError;
artifactError = resolveError;
}
return artifactError;
}
return null;
};
if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
let candidateError = null;
let candidateFailed = false;
try {
candidateError = __napiWasiResolveCandidate("./core.wasi.cjs", false, ["./core.wasm32-wasi.debug.wasm", "./core.wasm32-wasi.wasm"]);
candidateFailed = candidateError !== null;
if (!candidateFailed) {
wasiBinding = require(/* turbopackOptional: true */ "./core.wasi.cjs");
nativeBinding = wasiBinding;
__napiLoadedBindingTarget = "wasm32-wasi";
wasiBindingLoaded = true;
}
} catch (err) {
candidateError = err;
candidateFailed = true;
}
if (candidateFailed) {
wasiBindingErrors.push(candidateError);
loadErrors.push(candidateError);
}
}
if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) {
let candidateError = null;
let candidateFailed = false;
try {
candidateError = __napiWasiResolveCandidate("@takumi-rs/core-wasm32-wasi", true, void 0);
candidateFailed = candidateError !== null;
if (!candidateFailed) {
if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") {
const bindingPackageVersion = require(/* turbopackOptional: true */ "@takumi-rs/core-wasm32-wasi/package.json").version;
if (bindingPackageVersion !== "2.22.1") throw new Error(`WASI binding package version mismatch, expected 2.22.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
}
wasiBinding = require(/* turbopackOptional: true */ "@takumi-rs/core-wasm32-wasi/core.wasm32-wasi.node");
nativeBinding = wasiBinding;
__napiLoadedBindingTarget = "wasm32-wasi";
wasiBindingLoaded = true;
}
} catch (err) {
candidateError = err;
candidateFailed = true;
}
if (candidateFailed) {
wasiBindingErrors.push(candidateError);
loadErrors.push(candidateError);
}
}
if (!wasiBindingLoaded && forceWasi && !forceWasiError && !__napiWasiFlavorRequested) {
nativeBinding = requireNative();
__napiRequiredNativeBinding = nativeBinding;
}
if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) {
const error = /* @__PURE__ */ new Error(__napiWasiFlavorRequested ? "WASI binding for flavor \"" + __napiWasiFlavor + "\" not found" : "WASI binding not found and NAPI_RS_FORCE_WASI is set to error");
error.cause = createLoadErrorChain(wasiBindingErrors);
throw error;
}
}
if (!nativeBinding) {
if (loadErrors.length > 0) {
const error = /* @__PURE__ */ new Error((() => {
const variables = process.config?.variables;
const windowsAbi =
process.arch === "x64" &&
(variables?.shlib_suffix === "dll.a" || variables?.node_target_type === "shared_library")
? "gnu"
: "msvc";
const target =
process.platform === "linux"
? `linux-${process.arch}-${isMusl() ? "musl" : "gnu"}`
: process.platform === "win32"
? `win32-${process.arch}-${windowsAbi}`
: `${process.platform}-${process.arch}`;
return ["darwin-x64","darwin-arm64","linux-arm64-gnu","linux-arm64-musl","win32-arm64-msvc","linux-x64-gnu","linux-x64-musl","win32-x64-msvc"].includes(target)
? `Cannot find @takumi-rs/core-${target}. Keep @takumi-rs/core out of the bundle, and install @takumi-rs/core-${target} where the app runs. See https://takumi.kane.tw/docs/troubleshooting#cannot-find-native-binding`
: `@takumi-rs/core has no native binding for ${target}. Render with @takumi-rs/wasm instead. See https://takumi.kane.tw/docs/troubleshooting#cannot-find-native-binding`;
})());
error.cause = createLoadErrorChain(loadErrors);
throw error;
}
throw new Error(`Failed to load native binding`);
}
if (__napiLoadedBindingTarget === "native" && nativeBinding !== __napiRequiredNativeBinding) try {
const __napiBindingTargetDescriptor = Object.getOwnPropertyDescriptor(nativeBinding, "__napiBindingTarget");
if (__napiBindingTargetDescriptor && __napiWasiFlavors.indexOf(__napiBindingTargetDescriptor.value) !== -1 && nativeBinding.__napiBindingTarget === __napiBindingTargetDescriptor.value) __napiLoadedBindingTarget = __napiBindingTargetDescriptor.value;
} catch {}
const { Renderer: Renderer$1, setGlyphCacheMaxBytes } = nativeBinding;
// ../takumi-bindings-js/src/node-source.ts
const LONE_SURROGATE = /\p{Cs}/u;
/** The most arrays and objects `serde_json` reads nested inside each other. */
const MAX_DEPTH = 127;
/**
* A node tree as {@link JsonSource} when JSON keeps every value in it within {@link MAX_DEPTH}, the
* tree itself otherwise, and HTML as is.
* @internal
*/
function toNativeSource(source) {
if (typeof source === "string") return source;
const depths = /* @__PURE__ */ new WeakMap();
try {
return { json: JSON.stringify(source, function(key, value) {
if (this[key] !== value || LONE_SURROGATE.test(key) || !isJsonValue(value)) throw source;
if (typeof value === "object" && value !== null) {
const depth = (depths.get(this) ?? 0) + 1;
if (depth > MAX_DEPTH) throw source;
depths.set(value, depth);
}
return value ?? null;
}) };
} catch {
return source;
}
}
/** Whether JSON keeps `value` as the native side reads it from an object. */
function isJsonValue(value) {
switch (typeof value) {
case "string": return !LONE_SURROGATE.test(value);
case "number": return Number.isFinite(value);
case "boolean":
case "undefined": return true;
case "object": return value === null || Array.isArray(value) || [Object.prototype, null].includes(Object.getPrototypeOf(value));
default: return false;
}
}
// ../takumi-bindings-js/src/warning.ts
const shownCharacters = 20;
/** Prints `message` with `console.warn` in the form takumi's Rust warnings take. */
function warn(message) {
console.warn(`takumi: ${message}`);
}
/** The message of `cause`, which can be any thrown value. */
function messageOf(cause) {
if (cause instanceof Error) return cause.message;
try {
return String(cause);
} catch {
return "a value that has no text form";
}
}
/**
* Warns that the font `source` names, the URL of an `@font-face` file or of a font listed by URL and
* otherwise the key the renderer keeps the font under, failed to load with `error`.
*
* @internal
*/
function warnFontLoadFailed(source, error) {
warn(`Failed to load the font ${source}: ${messageOf(error)}`);
}
/**
* Warns about what a render found no font for, and about the images that failed to load.
*
* @internal
*/
function warnUndrawn(missingCharacters, unresolvedFamilies, failedImages) {
if (missingCharacters.length > 0) {
const shown = missingCharacters.slice(0, shownCharacters).join("");
const more = missingCharacters.length - shownCharacters;
warn(`No font draws "${shown}"${more > 0 ? ` or ${more} more characters` : ""}. Add a font that covers ${missingCharacters.length > 1 ? "them" : "it"} to \`fonts\`, or return one from \`loadFallbackFonts\`.`);
}
for (const family of unresolvedFamilies) warn(`No font provides the family "${family}". Add a font named "${family}" to \`fonts\`, or correct the name.`);
for (const { src, error } of failedImages) warn(`Failed to load the image ${src}: ${messageOf(error)}`);
}
// ../takumi-bindings-js/src/unicode-range.ts
/**
* The `unicodeRange` a font descriptor declares, or the deprecated `ranges`.
*
* @internal
*/
function unicodeRangeOf(font) {
if (typeof font !== "object" || font === null) return [];
if ("unicodeRange" in font && Array.isArray(font.unicodeRange)) return font.unicodeRange;
if ("ranges" in font && Array.isArray(font.ranges)) return font.ranges;
return [];
}
// ../takumi-bindings-js/src/renderer.ts
/**
* The scope of a render that lists the fonts under `listed` and saw `failed` fail. It leaves out
* what is empty, as a binding reads a present `undefined` as a value.
*
* @internal
*/
function fontScope(listed, failed) {
return {
...listed ? { listed } : {},
...failed.length > 0 ? { failed } : {}
};
}
function isBuffer(data) {
return data instanceof Uint8Array || data instanceof ArrayBuffer || typeof Buffer !== "undefined" && Buffer.isBuffer(data);
}
function asView(data) {
return data instanceof ArrayBuffer ? new Uint8Array(data) : data;
}
function extractFontBuffer(font) {
if (isBuffer(font)) return font;
if (typeof font.data !== "function") return font.data;
return font.data();
}
/** `font` with a URL string turned into a loader that downloads it with `fetch`. */
const toLoader = (font, fetch) => typeof font === "string" ? fontFromUrl(font, fetch) : font;
function createFontKey(font) {
if (isBuffer(font)) return font;
if ("key" in font && font.key) return font.key;
if (typeof font.data === "function") return faceKey(font);
return font.data;
}
/** The face descriptors `font` registers under, which a key must include to keep each face. */
function faceKey(font) {
const ranges = unicodeRangeOf(font).map(([start, end]) => `${start}-${end}`).join(",");
return [
font.subsetOf ?? font.name ?? "",
font.weight ?? "",
font.style ?? "",
ranges,
font.generic ?? ""
].join(":");
}
/**
* Normalize an {@link ImagesInput} into concrete, deduped {@link ImageSource} entries.
*
* @internal
*/
async function resolveImageLoaders(images) {
const { sources = [], cache } = Array.isArray(images) ? { sources: images } : images;
const bySrc = new Map(sources.map((image) => [image.src, image]));
return Promise.all([...bySrc.values()].map(async ({ src, data, cache: own }) => ({
src,
data: asView(typeof data === "function" ? await data() : data),
cache: own ?? cache
})));
}
/**
* The store a render's downloads go through. A caller's own `fetch` may send its credentials, so
* its downloads skip the store the renderers share.
*
* @internal
*/
function downloadStore(fetch) {
return fetch === void 0 ? defaultStore() : null;
}
/**
* A 53-bit hash of `bytes` with their length, after
* [cyrb53](https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
*/
function hashBytes(bytes) {
let h1 = 3735928559;
let h2 = 1103547991;
for (let index = 0; index < bytes.length; index++) {
const byte = bytes[index] ?? 0;
h1 = Math.imul(h1 ^ byte, 2654435761);
h2 = Math.imul(h2 ^ byte, 1597334677);
}
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
return `${bytes.length}:${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}`;
}
/**
* Font registration shared by every backend: asks the backend whether it still holds a font before
* loading it, loads a font once however many renders ask for it at the same time, and turns a set
* of {@link FontLoader}s plus an {@link ImagesInput} into the `fontFamilies`/`images` the binding
* expects. The backend keeps the fonts and evicts them; this keeps no record of its own.
* @internal
*/
var FontRegistry = class {
backend;
loading = /* @__PURE__ */ new Map();
/** A key for each buffer passed as a font, by its bytes, since the backend only takes string keys. */
bufferKeys = /* @__PURE__ */ new WeakMap();
/** The keys of fonts loaded with `cache: "none"` that no render has asked to keep since. */
transient = /* @__PURE__ */ new Set();
/** The keys of `transient` whose renders settled, forgotten once no render leases their files. */
unkept = /* @__PURE__ */ new Set();
/** The leases `leased` holds open. */
open = /* @__PURE__ */ new Set();
constructor(backend) {
this.backend = backend;
}
/**
* Registers one font unless the backend still holds it, its file leased to the render that
* `lease` names. Without a lease, as `registerFont` registers, it is never evicted.
*/
async register(font, lease) {
const loader = toLoader(font);
const key = this.keyOf(loader);
const pinned = lease === void 0;
const keeps = pinned || isBuffer(loader) || loader.cache !== "none";
const held = this.backend.cachedFonts(key, pinned, lease);
if (held) {
if (keeps) this.keep(key);
return held;
}
const pending = this.loading.get(key);
if (pending) return pending.then(() => this.register(loader, lease));
const load = Promise.resolve(extractFontBuffer(loader)).then((data) => {
const view = asView(data);
const input = isBuffer(loader) ? view : {
...loader,
data: view
};
return lease === void 0 ? this.backend.registerFont(input, key) : this.backend.cacheFont(input, key, lease);
}).then((families) => {
if (keeps) this.keep(key);
else {
this.transient.add(key);
if (lease !== void 0 && !this.open.has(lease)) {
this.unkept.add(key);
this.dropSettled();
}
}
return families;
}).finally(() => this.loading.delete(key));
this.loading.set(key, load);
return load;
}
/** Loads each of `fonts` the backend does not hold under `load`, and returns whether any was loaded. */
async cache(fonts, load) {
const loaders = fonts.map((font) => toLoader(font)).filter((loader) => !this.backend.cachedFonts(this.keyOf(loader), false, load.lease));
await Promise.all(loaders.map((loader) => this.admit(loader, load)));
return loaders.length > 0;
}
/** {@link register} for a render's `fonts` list, adding an optional font that fails to `load` instead of rejecting. */
async admit(loader, load) {
try {
return await this.register(loader, load.lease);
} catch (error) {
if (isBuffer(loader) || !loader.optional) throw error;
const key = this.keyOf(loader);
load.failed.push(key);
warnFontLoadFailed(key, error);
return [];
}
}
/** Calls `use` with a set of leases, released once what it returns settles. */
async leased(use) {
const lease = this.backend.leaseFonts();
this.open.add(lease);
try {
return await use(lease);
} finally {
this.open.delete(lease);
this.backend.releaseFonts(lease);
}
}
/** Calls `use`, and forgets the fonts of `fonts` loaded with `cache: "none"` when it fails. */
async dropOnFailure(fonts, use) {
try {
return await use();
} catch (error) {
this.dropUnkept(fonts);
throw error;
}
}
/**
* Forgets the fonts of `fonts` loaded with `cache: "none"` that no render asked to keep, once no
* render leases their files. A render calls it after it settles, which also forgets the ones an
* earlier render left because another render leased them then.
*/
dropUnkept(fonts) {
for (const font of fonts ?? []) {
const key = this.key(font);
if (this.transient.has(key)) this.unkept.add(key);
}
this.dropSettled();
}
/** Forgets the fonts under `unkept` that no render leases, leaving the others for a later call. */
dropSettled() {
if (this.unkept.size === 0) return;
for (const key of this.backend.dropFonts([...this.unkept])) {
this.transient.delete(key);
this.unkept.delete(key);
}
}
/** Marks the font under `key` as one a render asked to keep. */
keep(key) {
this.transient.delete(key);
this.unkept.delete(key);
}
/** `fonts` as loaders, each URL string downloading with `fetch` as the render's other downloads do. */
loaders(fonts, fetch) {
return fonts.map((font) => toLoader(font, fetch));
}
/** `fonts` described for a backend's needs pass. None when no font declares a `unicodeRange`. */
listed(fonts) {
const loaders = fonts.map((font) => toLoader(font));
if (!loaders.some((loader) => unicodeRangeOf(loader).length > 0)) return;
return loaders.map((loader) => {
const key = this.keyOf(loader);
if (isBuffer(loader) || !("name" in loader)) return { key };
const { name, weight, style } = loader;
return {
key,
name,
weight,
style,
unicodeRange: unicodeRangeOf(loader)
};
});
}
/** `fonts` without the ones whose keys `failed` lists. */
without(fonts, failed) {
return failed.length > 0 ? fonts.filter((font) => !failed.includes(this.key(font))) : fonts;
}
/** The keys the backend keeps `fonts` under. */
keys(fonts) {
return fonts.map((font) => this.key(font));
}
/** Removes from `failed` the keys of `fonts`, which load again. */
clearFailures(fonts, failed) {
const keys = new Set(fonts.map((font) => this.key(font)));
failed.splice(0, failed.length, ...failed.filter((source) => !keys.has(source)));
}
/** The key the backend keeps `font` under. */
key(font) {
return this.keyOf(toLoader(font));
}
keyOf(loader) {
const key = createFontKey(loader);
if (typeof key === "string") return key;
const buffer = this.bufferKeyOf(key);
return isBuffer(loader) ? buffer : `${buffer}:${faceKey(loader)}`;
}
bufferKeyOf(buffer) {
const known = this.bufferKeys.get(buffer);
if (known) return known;
const assigned = `buffer:${hashBytes(asView(buffer))}`;
this.bufferKeys.set(buffer, assigned);
return assigned;
}
/** Leases each of the `@font-face` files `urls` the backend still holds to `lease`, returning the others. */
leaseFontFiles(urls, lease) {
return urls.filter((url) => !this.backend.cachedFontFile(url, lease));
}
/** Fetches the `@font-face` files `urls` with `fetch` and loads each under `load`, adding the ones that fail to it. */
async loadFontFiles(urls, fetch, load) {
const { images, failed } = await fetchImagesSettled({
...fetch,
urls,
store: downloadStore(fetch.fetch)
});
const fetched = new Map(images.map(({ src, data }) => [src, data]));
const errors = new Map(failed.map(({ src, error }) => [src, error]));
const failures = await Promise.all(urls.map(async (url) => {
const data = fetched.get(url);
if (data === void 0) return [[url, errors.get(url) ?? /* @__PURE__ */ new Error(`Fetching ${url} needs your own fetch`)]];
try {
await this.backend.cacheFontFile(url, asView(data), load.lease);
return [];
} catch (error) {
return [[url, error]];
}
}));
for (const [url, error] of failures.flat()) {
load.failed.push(url);
warnFontLoadFailed(url, error);
}
}
/** Leases each held file the backend still holds, and loads the others again, returning the ones that failed. */
async holdFiles({ urls, load }, lease) {
const evicted = this.leaseFontFiles(urls, lease);
return evicted.length > 0 ? load(evicted, lease) : [];
}
/**
* Registers `fonts`, resolves lazy `images`, and leases the `@font-face` `files` a prepared render
* loaded, then calls `use` with the `images` and `fontFamilies` the binding expects. Every font
* stays leased until what `use` returns settles. Explicit `fontFamilies` wins over the registered
* set.
*/
async resolveResources(fonts, images, fontFamilies, use, { files, implicitFamilies = false } = {}) {
const resolvedImages = images ? await resolveImageLoaders(images) : void 0;
const loaders = fonts?.map((font) => toLoader(font)) ?? [];
return this.leased(async (lease) => {
const load = {
lease,
failed: []
};
const families = await Promise.all(loaders.map((loader) => this.admit(loader, load)));
const failed = [...load.failed, ...files ? await this.holdFiles(files, lease) : []];
const registered = fonts && !implicitFamilies ? [...new Set(families.flat().map((family) => family.name))] : void 0;
return use({
images: resolvedImages,
fontFamilies: fontFamilies ?? registered,
fontScope: fontScope(loaders.map((loader) => this.keyOf(loader)), failed)
});
});
}
};
// ../takumi-bindings-js/src/prepared.ts
function splitExtras({ fonts, images, signal, fontFamilies, loadFallbackFonts, ...layout }) {
return {
extras: {
fonts,
images,
signal,
fontFamilies,
loadFallbackFonts
},
layout
};
}
/**
* The options and listed fonts a binding's `needs` takes for `request` on top of `layout`.
*
* @internal
*/
function needsArgs(layout, { images, fonts, fontFamilies, fontScope }) {
return [{
...layout,
images,
fontFamilies,
fontScope
}, fonts];
}
let createPrepared;
let stateOf;
/** A source with its layout options, the font subsets its text uses, and the images it draws, fetched. */
var Prepared = class Prepared {
#state;
constructor(state) {
this.#state = state;
}
static {
createPrepared = (state) => new Prepared(state);
stateOf = (prepared) => prepared.#state;
}
};
/**
* Reads what `source` needs under `layout`, then loads its font subsets and fetches the images `extras.images` lacks.
*
* @internal
*/
async function prepareSource(registry, source, layout, extras, needs) {
const state = await collect(registry, source, layout, extras, needs, true);
const failed = await registry.dropOnFailure(state.fonts, async () => {
const failedFonts = await registry.resolveResources(state.fonts && registry.loaders(state.fonts, {
...state.fontFetch,
signal: extras.signal
}), void 0, state.fontFamilies, (resolved) => resolved.fontScope.failed ?? [], { implicitFamilies: state.implicitFamilies });
extras.signal?.throwIfAborted();
return failedFonts;
});
return createPrepared({
...state,
fonts: state.fonts && registry.without(state.fonts, failed),
failedFontFiles: [...state.failedFontFiles, ...failed]
});
}
/**
* {@link prepareSource} without fetching, running `needs` only when `fonts` holds `unicodeRange` subsets.
*
* @internal
*/
async function readSource(registry, source, layout, extras, needs) {
return createPrepared(await collect(registry, source, layout, extras, needs, false));
}
/** The `items` not `seen` yet, which join them. */
function unseen(items, seen) {
const fresh = items.filter((item) => !seen.has(item));
for (const item of fresh) seen.add(item);
return fresh;
}
/**
* Leases or loads the fonts `first` reaches under `load`, then reads again with `read` and loads
* what that reaches, until a read reaches nothing new. Returns the last read. The `@font-face`
* files and optional fonts that fail join `load.failed`, which each read moves on from.
*
* A file that fails moves its rule on to its next `src`, and a listed subset without a glyph its
* `unicodeRange` claims moves the character on to the next family, as a browser does. The next read
* reports either. Each URL and listed font loads at most once, so a font the renderer evicts to fit
* another cannot loop the reads.
*/
async function loadReached(registry, first, read, { tried, fetch, uncachedOf, signal }, load) {
const reached = (urls = []) => fetch ? unseen(urls, tried) : [];
let latest = first;
for (;;) {
const pending = reached(latest?.fontFiles);
const evicted = registry.leaseFontFiles([...pending, ...reached(latest?.loadedFontFiles)], load.lease);
if (fetch && evicted.length > 0) await registry.loadFontFiles(evicted, fetch, load);
signal?.throwIfAborted();
const loadedListed = await registry.cache(uncachedOf?.(latest) ?? [], load);
signal?.throwIfAborted();
if (pending.length === 0 && evicted.length === 0 && !loadedListed) return latest;
latest = await read(load.failed);
}
}
async function collect(registry, source, layout, extras, needs, fetchMissing) {
const { fonts, fontFamilies, images = [], signal, loadFallbackFonts } = extras;
signal?.throwIfAborted();
const resolvedFonts = await fonts;
signal?.throwIfAborted();
const listed = resolvedFonts && registry.listed(resolvedFonts);
const listedKeys = resolvedFonts && registry.keys(resolvedFonts);
const request = {
fonts: listed,
fontFamilies,
fontScope: fontScope(listedKeys, [])
};
let first;
const read = () => first ??= Promise.resolve(needs(request));
const { sources = [], cache, throwOnError = true, fetchCache, ...fetchOptions } = Array.isArray(images) ? { sources: images } : images;
const provided = await resolveImageLoaders({
sources,
cache
});
const failedImages = [];
const loadImages = async (urls) => {
const options = {
...fetchOptions,
urls,
sources: provided,
store: downloadStore(fetchOptions.fetch),
fetchCache,
signal
};
if (throwOnError) return fetchImages(options);
const settled = await fetchImagesSettled(options);
failedImages.push(...settled.failed);
return settled.images;
};
const entries = (fetchMissing ? await loadImages((await read()).images) : provided).map((image) => ({
cache,
...image
}));
const readWithImages = () => entries.length > 0 ? needs({
...request,
images: entries
}) : read();
const firstReached = listed || fetchMissing ? await readWithImages() : void 0;
const tried = /* @__PURE__ */ new Set();
const cached = /* @__PURE__ */ new Set();
const failedFontFiles = [];
const fontFetch = {
...fetchOptions,
fetchCache
};
const fetch = {
...fontFetch,
signal
};
const reread = (failed) => needs({
...request,
fonts: listedWithout(listed, failed),
images: entries,
fontScope: fontScope(listedKeys, failed)
});
/** Loads every font of `fonts` as the render does, then calls `use` with the families it falls back through. */
const resolveFonts = (fonts, families, use, implicitFamilies = false) => registry.resolveResources(fonts && registry.loaders(fonts, fetch), void 0, families, ({ fontFamilies: resolved, fontScope: { listed: keys, failed = [] } }) => {
failedFontFiles.push(...failed);
return use(resolved, keys);
}, { implicitFamilies });
/** Reads the source with every font of `fonts` loaded, falling back through `families` as the render does. */
const readLoaded = (fonts, families, implicitFamilies = false) => resolveFonts(fonts, families, (resolved, keys) => needs({
images: entries,
fontFamilies: resolved,
fontScope: fontScope(keys, failedFontFiles)
}), implicitFamilies);
const fontFileFetch = fetchMissing ? fetch : void 0;
const load = (lease) => ({
lease,
failed: failedFontFiles
});
const settled = await registry.dropOnFailure(resolvedFonts, () => registry.leased(async (lease) => {
const reached = await loadReached(registry, firstReached, reread, {
tried,
fetch: fontFileFetch,
uncachedOf: (needs) => listed && resolvedFonts ? registry.loaders(unseen(needs?.fonts ?? [], cached).flatMap((id) => resolvedFonts[id] ?? []), fetch) : [],
signal
}, load(lease));
const loads = listed && reached?.fonts;
const subset = loads ? resolvedFonts?.filter((_, id) => loads.includes(id)) : resolvedFonts;
const kept = subset && registry.without(subset, failedFontFiles);
if (!fetchMissing && !loadFallbackFonts) return {
fonts: kept,
fontFamilies,
coverage: void 0,
added: [],
implicitFamilies: false
};
const coverage = listed && kept?.length === subset?.length ? reached : resolvedFonts ? await readLoaded(kept, fontFamilies) : reached ?? await readWithImages();
const characters = coverage?.missingCharacters ?? [];
const added = characters.length > 0 ? await loadFallbackFonts?.([...characters]) ?? [] : [];
signal?.throwIfAborted();
if (added.length === 0) return {
fonts: kept,
fontFamilies,
coverage,
added,
implicitFamilies: false
};
const loadable = kept && registry.without(kept, failedFontFiles);
registry.clearFailures(added, failedFontFiles);
return registry.dropOnFailure(added, async () => {
const implicitFamilies = !resolvedFonts && !fontFamilies;
const families = fontFamilies && [.../* @__PURE__ */ new Set([...fontFamilies, ...await resolveFonts(added, void 0, (registered = []) => registered)])];
const all = [...loadable ?? [], ...added];
const read = () => readLoaded(all, families, implicitFamilies);
return {
fonts: all,
fontFamilies: families,
coverage: await loadReached(registry, await read(), read, {
tried,
fetch: fontFileFetch,
signal
}, load(lease)),
added,
implicitFamilies
};
});
}));
warnUndrawn(settled.coverage?.missingCharacters ?? [], settled.coverage?.unresolvedFamilies ?? [], failedImages);
return {
source,
layout,
fonts: settled.fonts && registry.without(settled.fonts, failedFontFiles),
loadedFonts: [...(listed ? resolvedFonts?.filter((_, id) => cached.has(id)) : resolvedFonts) ?? [], ...settled.added],
fontFamilies: settled.fontFamilies,
implicitFamilies: settled.implicitFamilies,
images: entries,
fontFiles: [...tried].filter((url) => !failedFontFiles.includes(url)),
failedFontFiles,
fontFetch,
reread
};
}
/** `listed` with each font whose key `failed` lists left as a bare key, so a read reaches the family after it. */
function listedWithout(listed, failed) {
if (!listed || failed.length === 0) return listed;
return listed.map((font) => failed.includes(font.key) ? { key: font.key } : font);
}
/**
* Calls `call` with the binding options for rendering `prepared` with `output`. The layout `prepared` holds wins.
*
* @internal
*/
function renderPrepared(registry, prepared, output, call) {
const state = stateOf(prepared);
const { signal, ...encoding } = output;
signal?.throwIfAborted();
const fetch = {
...state.fontFetch,
signal
};
const files = state.fontFiles.length > 0 ? {
urls: state.fontFiles,
load: async (urls, lease) => {
const load = {
lease,
failed: [...state.failedFontFiles]
};
await registry.loadFontFiles(urls, fetch, load);
if (load.failed.length === state.failedFontFiles.length) return [];
const tried = /* @__PURE__ */ new Set([...state.fontFiles, ...load.failed]);
await loadReached(registry, await state.reread(load.failed), state.reread, {
tried,
fetch,
signal
}, load);
return load.failed.slice(state.failedFontFiles.length);
}
} : void 0;
return registry.resolveResources(state.fonts && registry.loaders(state.fonts, fetch), state.images, state.fontFamilies, ({ images, fontFamilies, fontScope: { listed, failed = [] } }) => {
signal?.throwIfAborted();
return call(state.source, {
...encoding,
...state.layout,
images,
fontFamilies,
fontScope: fontScope(listed, [...state.failedFontFiles, ...failed])
}, signal);
}, {
files,
implicitFamilies: state.implicitFamilies
}).finally(() => registry.dropUnkept(state.loadedFonts));
}
// src/export.ts
var Renderer = class {
inner;
fonts;
constructor(options) {
this.inner = new Renderer$1(options);
this.fonts = new FontRegistry(this.inner);
}
/** Reads what `source` needs under `options`, then loads its font subsets and fetches its images. */
prepare(source, options) {
const { extras, layout } = splitExtras(options ?? {});
const native = toNativeSource(source);
return prepareSource(this.fonts, native, layout, extras, (request) => this.inner.needs(native, ...needsArgs(layout, request), extras.signal));
}
async render(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts, signal) => this.inner.render(native, opts, signal));
}
async renderSvg(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts, signal) => this.inner.renderSvg(native, opts, signal));
}
async measure(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts, signal) => this.inner.measure(native, opts, signal));
}
/** `source` read under `options` without fetching, for {@link render} and its siblings. */
read(source, options) {
const { extras, layout } = splitExtras(options);
const native = toNativeSource(source);
return readSource(this.fonts, native, layout, extras, (request) => this.inner.needs(native, ...needsArgs(layout, request), extras.signal));
}
/** Reads what every scene needs under `options`, then loads their font subsets and fetches their images. */
prepareAnimation(options) {
return this.readAnimation(options, prepareSource);
}
async renderAnimation(source, options = {}) {
const prepared = source instanceof Prepared ? source : await this.readAnimation(source, readSource);
return renderPrepared(this.fonts, prepared, { signal: source instanceof Prepared ? options.signal : source.signal }, (scenes, opts, signal) => this.inner.renderAnimation({
...opts,
scenes
}, signal));
}
/** The scenes of `options` read with `collect`, which fetches their images when it prepares them. */
readAnimation(options, collect) {
const { extras, layout: { scenes, ...layout } } = splitExtras(options);
const sources = scenes.map((scene) => ({
...scene,
node: toNativeSource(scene.node)
}));
return collect(this.fonts, sources, layout, extras, (request) => this.inner.animationNeeds(...needsArgs({
...layout,
scenes: sources
}, request), extras.signal));
}
registerFont(font) {
return this.fonts.register(font);
}
/**
* Removes every face registered under the family `name`, from any `registerFont` call and each
* `unicodeRange` subset alike; returns whether it had any. Takes a family `registerFont` returned
* as well. A later render that lists one of its fonts registers it again.
*/
unregisterFont(family) {
return this.inner.unregisterFont(family.name);
}
/** What the renderer's caches hold and how their lookups went since it was created. */
cacheStats() {
return this.inner.cacheStats();
}
/** Removes every registered font, leaving the bundled fallback font. */
clearFonts() {
this.inner.clearFonts();
}
};
export { Prepared, Renderer, setGlyphCacheMaxBytes };
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.