示例工程 40-node-api-native-modules
40-node-api-native-modules/app/shared/ipc.ts
export const CH = {
snapshot: "native:snapshot",
hash: "native:hash",
benchmark: "native:benchmark",
setFallback: "native:set-fallback",
reload: "native:reload",
refresh: "native:refresh",
} as const;
export type EventRow = {
at: number;
kind: string;
detail: string;
};
export type AbiInfo = {
platform: string;
arch: string;
modules: string;
napi: string;
node: string;
electron: string;
};
export type NativeInfo = {
loaded: boolean;
path: string;
version: string;
error: string;
forcedFallback: boolean;
source: "native" | "fallback";
};
export type HashResult = {
inputLength: number;
byteLength: number;
nativeHash: string;
jsHash: string;
equal: boolean;
usedNative: boolean;
nativeMs: number;
jsMs: number;
at: number;
};
export type BenchRow = {
label: string;
size: number;
nativeMs: number;
jsMs: number;
equal: boolean;
nativeRepeats: number;
jsRepeats: number;
};
export type Snapshot = {
abi: AbiInfo;
native: NativeInfo;
lastHash: HashResult | null;
bench: BenchRow[];
events: EventRow[];
};
export function assertHashReq(
value: unknown,
): asserts value is { text: string } {
if (typeof value !== "object" || value === null) {
throw new Error("BAD_HASH_REQ");
}
const text = (value as { text?: unknown }).text;
if (typeof text !== "string" || text.length === 0 || text.length > 100_000) {
throw new Error("BAD_HASH_TEXT");
}
}
export function assertFallbackReq(
value: unknown,
): asserts value is { enabled: boolean } {
if (typeof value !== "object" || value === null) {
throw new Error("BAD_FALLBACK_REQ");
}
if (typeof (value as { enabled?: unknown }).enabled !== "boolean") {
throw new Error("BAD_FALLBACK_REQ");
}
}